From 2007f06078b6569a2cfd9f361f17d765c07bc7f8 Mon Sep 17 00:00:00 2001 From: Hank Duan Date: Wed, 21 Oct 2015 17:03:49 +0100 Subject: [PATCH 001/678] feat(protractor): add flag to stop protractor from tracking $timeout --- docs/faq.md | 8 +++++++- docs/referenceConf.js | 7 +++++++ lib/protractor.js | 45 +++++++++++++++++++++++++++++++------------ lib/runner.js | 3 +-- scripts/test.js | 8 ++++++++ 5 files changed, 56 insertions(+), 15 deletions(-) diff --git a/docs/faq.md b/docs/faq.md index 0032c2118..9d7a5ea7d 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -193,7 +193,7 @@ You may need to insert a `browser.wait` condition to make sure the load is complete before continuing. How do I switch off an option in the CLI? ------------------------------------------------------------------------------- +----------------------------------------- i.e. `webdriver-manager update --chrome=false` does not work. This has to do with the way `optimist` parses command line args. In order to pass a false value, do one of the following: @@ -201,6 +201,12 @@ This has to do with the way `optimist` parses command line args. In order to pas 2) `webdriver-manager update --no-chrome` (see https://github.com/substack/node-optimist#negate-fields) +Why does Protractor fail when I decorate $timeout? +-------------------------------------------------- +Protractor tracks outstanding $timeouts by default, and reports them in the error message if Protractor fails to synchronize with Angular in time. + +However, in order to do this Protractor needs to decorate $timeout. This means if your app decorates $timeout, you must turn off this behavior for Protractor. To do so pass in the 'untrackOutstandingTimeouts' flag. + I still have a question ----------------------- diff --git a/docs/referenceConf.js b/docs/referenceConf.js index 2376f44b4..9ae715333 100644 --- a/docs/referenceConf.js +++ b/docs/referenceConf.js @@ -250,6 +250,13 @@ exports.config = { // CAUTION: This will cause your tests to slow down drastically. restartBrowserBetweenTests: false, + // Protractor will track outstanding $timeouts by default, and report them in + // the error message if Protractor fails to synchronize with Angular in time. + // In order to do this Protractor needs to decorate $timeout. + // CAUTION: If your app decorates $timeout, you must turn on this flag. This + // is false by default. + untrackOutstandingTimeouts: false, + // --------------------------------------------------------------------------- // ----- The test framework -------------------------------------------------- // --------------------------------------------------------------------------- diff --git a/lib/protractor.js b/lib/protractor.js index f8995068e..040e61e00 100644 --- a/lib/protractor.js +++ b/lib/protractor.js @@ -93,8 +93,11 @@ var buildElementHelper = function(ptor) { * @param {string=} opt_baseUrl A base URL to run get requests against. * @param {string=} opt_rootElement Selector element that has an ng-app in * scope. + * @param {boolean=} opt_untrackOutstandingTimeouts Whether Protractor should + * stop tracking outstanding $timeouts. */ -var Protractor = function(webdriverInstance, opt_baseUrl, opt_rootElement) { +var Protractor = function(webdriverInstance, opt_baseUrl, opt_rootElement, + opt_untrackOutstandingTimeouts) { // These functions should delegate to the webdriver instance, but should // wait for Angular to sync up before performing the action. This does not // include functions which are overridden by protractor below. @@ -216,6 +219,13 @@ var Protractor = function(webdriverInstance, opt_baseUrl, opt_rootElement) { } }); + /** + * If true, Protractor will track outstanding $timeouts and report them in the + * error message if Protractor fails to synchronize with Angular in time. + * @private {boolean} + */ + this.trackOutstandingTimeouts_ = !opt_untrackOutstandingTimeouts; + /** * Information about mock modules that will be installed during every * get(). @@ -382,10 +392,15 @@ Protractor.prototype.waitForAngular = function(opt_description) { var errMsg = 'Timed out waiting for Protractor to synchronize with ' + 'the page after ' + timeout + '. Please see ' + 'https://github.com/angular/protractor/blob/master/docs/faq.md'; - var pendingTimeoutsPromise = self.executeScript_( - 'return window.NG_PENDING_TIMEOUTS', - 'Protractor.waitForAngular() - getting pending timeouts' + description - ); + var pendingTimeoutsPromise; + if (self.trackOutstandingTimeouts_) { + pendingTimeoutsPromise = self.executeScript_( + 'return window.NG_PENDING_TIMEOUTS', + 'Protractor.waitForAngular() - getting pending timeouts' + description + ); + } else { + pendingTimeoutsPromise = webdriver.promise.fulfilled({}); + } var pendingHttpsPromise = self.executeScript_( clientSideScripts.getPendingHttpRequests, 'Protractor.waitForAngular() - getting pending https' + description, @@ -518,14 +533,15 @@ Protractor.prototype.getRegisteredMockModules = function() { * @private */ Protractor.prototype.addBaseMockModules_ = function() { - this.addMockModule('protractorBaseModule_', function() { - angular.module('protractorBaseModule_', []). + this.addMockModule('protractorBaseModule_', function(trackOutstandingTimeouts) { + var ngMod = angular.module('protractorBaseModule_', []). config(['$compileProvider', function($compileProvider) { if ($compileProvider.debugInfoEnabled) { $compileProvider.debugInfoEnabled(true); } - }]). - config(['$provide', function($provide) { + }]); + if (trackOutstandingTimeouts) { + ngMod.config(['$provide', function($provide) { $provide.decorator('$timeout', ['$delegate', function($delegate) { var $timeout = $delegate; @@ -567,7 +583,8 @@ Protractor.prototype.addBaseMockModules_ = function() { return extendedTimeout; }]); }]); - }); + } + }, this.trackOutstandingTimeouts_); }; /** @@ -1041,8 +1058,12 @@ Protractor.prototype.pause = function(opt_debugPort) { * * @param {webdriver.WebDriver} webdriver The configured webdriver instance. * @param {string=} opt_baseUrl A URL to prepend to relative gets. + * @param {boolean=} opt_untrackOutstandingTimeouts Whether Protractor should + * stop tracking outstanding $timeouts. * @return {Protractor} */ -exports.wrapDriver = function(webdriver, opt_baseUrl, opt_rootElement) { - return new Protractor(webdriver, opt_baseUrl, opt_rootElement); +exports.wrapDriver = function(webdriver, opt_baseUrl, opt_rootElement, + opt_untrackOutstandingTimeouts) { + return new Protractor(webdriver, opt_baseUrl, opt_rootElement, + opt_untrackOutstandingTimeouts); }; diff --git a/lib/runner.js b/lib/runner.js index ece9bd56e..9934e962d 100644 --- a/lib/runner.js +++ b/lib/runner.js @@ -182,7 +182,7 @@ Runner.prototype.createBrowser = function(plugins) { var driver = this.driverprovider_.getNewDriver(); var browser_ = protractor.wrapDriver(driver, - config.baseUrl, config.rootElement); + config.baseUrl, config.rootElement, config.untrackOutstandingTimeouts); browser_.params = config.params; if (plugins) { @@ -202,7 +202,6 @@ Runner.prototype.createBrowser = function(plugins) { } var self = this; - browser_.ready = driver.manage().timeouts().setScriptTimeout(config.allScriptsTimeout); diff --git a/scripts/test.js b/scripts/test.js index 38cc1d0a1..a1cdb0424 100755 --- a/scripts/test.js +++ b/scripts/test.js @@ -130,6 +130,14 @@ executor.addCommandlineTest('node lib/cli.js spec/errorTest/slowHttpAndTimeoutCo '*}'} ]); +executor.addCommandlineTest('node lib/cli.js spec/errorTest/slowHttpAndTimeoutConf.js ' + + '--untrackOutstandingTimeouts true') + .expectExitCode(1) + .expectErrors([ + {message: 'The following tasks were pending[\\s\\S]*\\$http: \/slowcall'}, + {message: '^((?!The following tasks were pending).)*$'} + ]); + // Check ngHint plugin executor.addCommandlineTest( From 31d1b72aba8ec809195c12cb7cff3d3472c07ad1 Mon Sep 17 00:00:00 2001 From: Hank Duan Date: Fri, 30 Oct 2015 12:10:31 -0700 Subject: [PATCH 002/678] chore(tests): test doesn't work without network --- spec/basic/lib_spec.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spec/basic/lib_spec.js b/spec/basic/lib_spec.js index 75abdf7eb..e8056b89c 100644 --- a/spec/basic/lib_spec.js +++ b/spec/basic/lib_spec.js @@ -110,7 +110,8 @@ describe('protractor library', function() { it('should allow self-wrapped webdriver instances', function() { var driver = protractor.wrapDriver(browser.driver); - driver.get('https://angularjs.org/'); + var url = browser.baseUrl + '/index.html'; + driver.get(url); }); describe('helper functions', function() { From 2bde92b3e745e09ad3876932b2d187365e9aaa31 Mon Sep 17 00:00:00 2001 From: Hank Duan Date: Tue, 3 Nov 2015 14:19:29 -0800 Subject: [PATCH 003/678] chore(jasmine): remove jasmine 1.3 and update docs. Also, use jasmine 2 for running all Protractor's unit tests. BREAKING CHANGE: Now, both jasmine and jasmine2 frameworks use jasmine 2.3. Users still using jasmine version <2 will have to upgrade. --- debugging/failureConf.js | 7 +- debugging/timeoutConf.js | 7 +- docs/control-flow.md | 5 +- docs/faq.md | 26 +--- docs/frameworks.md | 4 +- docs/jasmine-upgrade.md | 4 +- docs/referenceConf.js | 22 +-- docs/toc.md | 2 +- docs/tutorial.md | 8 +- docs/webdriver-vs-protractor.md | 2 +- example/conf.js | 4 +- lib/cli.js | 2 - lib/configParser.js | 2 - lib/frameworks/README.md | 2 +- lib/frameworks/jasmine.js | 137 +++++++++++------- lib/frameworks/jasmine2.js | 118 --------------- lib/runner.js | 5 +- lib/util.js | 2 - package.json | 2 - plugins/accessibility/spec/failureConfig.js | 2 +- plugins/accessibility/spec/successConfig.js | 2 +- plugins/console/spec/consoleFailConfig.js | 2 +- .../console/spec/consoleFailErrorConfig.js | 2 +- .../console/spec/consoleFailFilterConfig.js | 2 +- .../console/spec/consoleFailLogWarnings.js | 2 +- .../console/spec/consoleFailWarningConfig.js | 2 +- plugins/console/spec/consolePassConfig.js | 2 +- .../console/spec/consolePassLogWarnings.js | 2 +- plugins/ngHint/spec/failureConfig.js | 2 +- plugins/ngHint/spec/successConfig.js | 2 +- scripts/test.js | 25 ++-- scripts/unit_test.json | 3 +- spec/altRootConf.js | 2 +- spec/angular2Conf.js | 2 +- spec/basicConf.js | 7 +- spec/ciFullConf.js | 3 +- spec/ciSmokeConf.js | 3 +- spec/controlLockConf.js | 2 +- spec/directConnectConf.js | 2 +- .../afterLaunchChangesExitCodeConf.js | 4 +- spec/errorTest/multiFailureConf.js | 4 +- spec/errorTest/pluginsFailingConf.js | 7 +- spec/errorTest/shardedFailureConf.js | 4 +- spec/errorTest/singleFailureConf.js | 4 +- spec/errorTest/slowHttpAndTimeoutConf.js | 2 +- spec/errorTest/timeoutConf.js | 4 +- spec/interactionConf.js | 2 +- spec/multiConf.js | 2 +- spec/onCleanUpAsyncReturnValueConf.js | 2 +- spec/onCleanUpNoReturnValueConf.js | 2 +- spec/onCleanUpSyncReturnValueConf.js | 2 +- spec/onPrepareConf.js | 2 +- spec/onPrepareFileConf.js | 2 +- spec/onPreparePromiseConf.js | 2 +- spec/onPreparePromiseFileConf.js | 2 +- spec/plugins/browserGetSyncedConf.js | 7 +- spec/plugins/browserGetUnsyncedConf.js | 7 +- spec/plugins/jasmine2PostTestConf.js | 1 - ...PostTestConf.js => jasminePostTestConf.js} | 0 spec/plugins/multiPluginConf.js | 7 +- spec/plugins/smokeConf.js | 7 +- spec/plugins/waitForAngularConf.js | 7 +- spec/restartBrowserBetweenTestsConf.js | 7 +- spec/suitesConf.js | 2 +- spec/withLoginConf.js | 2 +- stress/conf.js | 7 +- website/index.html | 2 +- website/package.json | 2 +- website/protractor.conf.js | 3 - website/run-tests.js | 3 +- website/test/e2e/api_spec.js | 2 +- website/test/e2e/navigation_spec.js | 6 +- website/unit_test.json | 6 + 73 files changed, 177 insertions(+), 380 deletions(-) delete mode 100644 lib/frameworks/jasmine2.js delete mode 100644 spec/plugins/jasmine2PostTestConf.js rename spec/plugins/{jasmine1PostTestConf.js => jasminePostTestConf.js} (100%) create mode 100644 website/unit_test.json diff --git a/debugging/failureConf.js b/debugging/failureConf.js index dbd801598..f094378f6 100644 --- a/debugging/failureConf.js +++ b/debugging/failureConf.js @@ -15,11 +15,8 @@ exports.config = { baseUrl: env.baseUrl, - // ----- Options to be passed to minijasminenode. + // ----- Options to be passed to jasmine. jasmineNodeOpts: { - onComplete: null, - isVerbose: false, - showColors: true, - includeStackTrace: true + showColors: true } }; diff --git a/debugging/timeoutConf.js b/debugging/timeoutConf.js index 6659e4700..dc5e3fb32 100644 --- a/debugging/timeoutConf.js +++ b/debugging/timeoutConf.js @@ -15,11 +15,8 @@ exports.config = { baseUrl: env.baseUrl, - // ----- Options to be passed to minijasminenode. + // ----- Options to be passed to jasmine. jasmineNodeOpts: { - onComplete: null, - isVerbose: false, - showColors: true, - includeStackTrace: true + showColors: true } }; diff --git a/docs/control-flow.md b/docs/control-flow.md index 24ddc30dc..4d8c9e65e 100644 --- a/docs/control-flow.md +++ b/docs/control-flow.md @@ -3,7 +3,7 @@ The WebDriver Control Flow The [WebDriverJS API](https://github.com/SeleniumHQ/selenium/wiki/WebDriverJs#understanding_the_api) is based on [promises](https://github.com/SeleniumHQ/selenium/wiki/WebDriverJs#promises), which are managed by a [control flow](https://github.com/SeleniumHQ/selenium/wiki/WebDriverJs#control-flows) -and adapted for [Jasmine](http://jasmine.github.io/1.3/introduction.html). +and adapted for [Jasmine](http://jasmine.github.io/2.3/introduction.html). A short summary about how Protractor interacts with the control flow is presented below. @@ -42,8 +42,7 @@ Protractor Adaptations ---------------------- Protractor adapts Jasmine so that each spec automatically waits until the -control flow is empty before exiting. This means you don't need to worry -about calling runs() and waitsFor() blocks. +control flow is empty before exiting. Jasmine expectations are also adapted to understand promises. That's why this line works - the code actually adds an expectation task to the control flow, diff --git a/docs/faq.md b/docs/faq.md index 9d7a5ea7d..d337db8fd 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -106,18 +106,7 @@ The method to take a screenshot automatically on failure would depend on the typ * For failures of entire specs (such as timeout or an expectation within the spec failed), you can add a reporter as below: ```javascript -// Note: this is using Jasmine 1.3 reporter syntax. -jasmine.getEnv().addReporter(new function() { - this.reportSpecResults = function(spec) { - if (!spec.results().passed()) { - //take screenshot - } - }; -}); -``` - -```javascript -// Note: this is using Jasmine 2.1 reporter syntax. +// Note: this is using Jasmine 2 reporter syntax. jasmine.getEnv().addReporter(new function() { this.specDone = function(result) { if (result.failedExpectations.length >0) { @@ -131,18 +120,7 @@ Note, you can also choose to take a screenshot in `afterEach`. However, because * For failures of individual expectations, you can override jasmine's addMatcherResult/addExpectationResult function as such: ```javascript -// Jasmine 1.3. -var originalAddMatcherResult = jasmine.Spec.prototype.addMatcherResult; -jasmine.Spec.prototype.addMatcherResult = function() { - if (!arguments[0].passed()) { - //take screenshot - } - return originalAddMatcherResult.apply(this, arguments); -}; -``` - -```javascript -// Jasmine 2.1 +// Jasmine 2 var originalAddExpectationResult = jasmine.Spec.prototype.addExpectationResult; jasmine.Spec.prototype.addExpectationResult = function() { if (!arguments[0]) { diff --git a/docs/frameworks.md b/docs/frameworks.md index bda11d6c1..cd4679dba 100644 --- a/docs/frameworks.md +++ b/docs/frameworks.md @@ -1,13 +1,13 @@ Choosing a Framework ==================== -Protractor supports four behavior driven development (BDD) test frameworks: Jasmine 1.3, Jasmine 2.0, Mocha, and Cucumber. These frameworks are based on JavaScript and Node.js and provide the syntax, scaffolding, and reporting tools you will use to write and manage your tests. +Protractor supports three behavior driven development (BDD) test frameworks: Jasmine, Mocha, and Cucumber. These frameworks are based on JavaScript and Node.js and provide the syntax, scaffolding, and reporting tools you will use to write and manage your tests. Using Jasmine ------------- -Currently, Jasmine Versions 1.3 and 2.0 are supported. Jasmine 1.3 is the default test framework and is available for use when you install Protractor. However, we're in the process of upgrading to Jasmine 2.0, and will deprecate support for 1.3 in the future. For more information about Jasmine, see the [Jasmine GitHub site](http://jasmine.github.io/). For more information regarding how to upgrade to Jasmine 2.0 from 1.3, see the [Jasmine upgrade guide](/docs/jasmine-upgrade.md). +Currently, Jasmine Version 2.x is supported and the default test framework when you install Protractor. For more information about Jasmine, see the [Jasmine GitHub site](http://jasmine.github.io/). For more information regarding how to upgrade to Jasmine 2.x from 1.3, see the [Jasmine upgrade guide](/docs/jasmine-upgrade.md). Using Mocha diff --git a/docs/jasmine-upgrade.md b/docs/jasmine-upgrade.md index 799cd9e30..f683d79b6 100644 --- a/docs/jasmine-upgrade.md +++ b/docs/jasmine-upgrade.md @@ -9,8 +9,8 @@ Specify that you want to use jasmine2.x: ```javascript exports.config = { - // Specify you want to use jasmine 2.x as you would with mocha and cucumber. - framework: 'jasmine2' + // Specify you want to use jasmine 2.x as you would with mocha and cucumber. Note, 'jasmine' by default will use the latest jasmine framework. + framework: 'jasmine' }; ``` diff --git a/docs/referenceConf.js b/docs/referenceConf.js index 9ae715333..6f84036c7 100644 --- a/docs/referenceConf.js +++ b/docs/referenceConf.js @@ -262,7 +262,7 @@ exports.config = { // --------------------------------------------------------------------------- // Test framework to use. This may be one of: - // jasmine, jasmine2, cucumber, mocha or custom. + // jasmine, cucumber, mocha or custom. // // When the framework is set to "custom" you'll need to additionally // set frameworkPath with the path relative to the config file or absolute @@ -271,26 +271,12 @@ exports.config = { // See github.com/angular/protractor/blob/master/lib/frameworks/README.md // to comply with the interface details of your custom implementation. // - // Jasmine and Jasmine2 are fully supported as test and assertion frameworks. + // Jasmine is fully supported as test and assertion frameworks. // Mocha and Cucumber have limited support. You will need to include your // own assertion framework (such as Chai) if working with Mocha. - framework: 'jasmine2', + framework: 'jasmine', - // Options to be passed to minijasminenode. - // - // See the full list at https://github.com/juliemr/minijasminenode/tree/jasmine1 - jasmineNodeOpts: { - // If true, display spec names. - isVerbose: false, - // If true, print colors to the terminal. - showColors: true, - // If true, include stack traces in failures. - includeStackTrace: true, - // Default time to wait in ms before a test fails. - defaultTimeoutInterval: 30000 - }, - - // Options to be passed to jasmine2. + // Options to be passed to jasmine. // // See https://github.com/jasmine/jasmine-npm/blob/master/lib/jasmine.js // for the exact options available. diff --git a/docs/toc.md b/docs/toc.md index 546b2e885..d39419890 100644 --- a/docs/toc.md +++ b/docs/toc.md @@ -23,6 +23,6 @@ Reference - [Timeouts](/docs/timeouts.md) - [The WebDriver Control Flow](/docs/control-flow.md) - [How It Works](/docs/infrastructure.md) - - [Upgrading to Jasmine 2.0](/docs/jasmine-upgrade.md) + - [Upgrading to Jasmine 2.x](/docs/jasmine-upgrade.md) - [Mobile Setup](/docs/mobile-setup.md) - [FAQ](/docs/faq.md) diff --git a/docs/tutorial.md b/docs/tutorial.md index e5271088e..bb324e514 100644 --- a/docs/tutorial.md +++ b/docs/tutorial.md @@ -60,13 +60,13 @@ Now create the configuration file. Copy the following into conf.js: ```js // conf.js exports.config = { - framework: 'jasmine2', + framework: 'jasmine', seleniumAddress: 'http://localhost:4444/wd/hub', specs: ['spec.js'] } ``` -This configuration tells Protractor where your test files (`specs`) are, and where to talk to your Selenium Server (`seleniumAddress`). It specifies that we will be using Jasmine version 2 for the test framework. It will use the defaults for all other configuration. Chrome is the default browser. +This configuration tells Protractor where your test files (`specs`) are, and where to talk to your Selenium Server (`seleniumAddress`). It specifies that we will be using Jasmine for the test framework. It will use the defaults for all other configuration. Chrome is the default browser. Now run the test with @@ -157,7 +157,7 @@ Now that we've written some basic tests, let's take a look at the configuration ```js // conf.js exports.config = { - framework: 'jasmine2', + framework: 'jasmine', seleniumAddress: 'http://localhost:4444/wd/hub', specs: ['spec.js'], capabilities: { @@ -173,7 +173,7 @@ You can also run tests on more than one browser at once. Change conf.js to: ```js // conf.js exports.config = { - framework: 'jasmine2', + framework: 'jasmine', seleniumAddress: 'http://localhost:4444/wd/hub', specs: ['spec.js'], multiCapabilities: [{ diff --git a/docs/webdriver-vs-protractor.md b/docs/webdriver-vs-protractor.md index 0d1e35ae7..c40f9ec83 100644 --- a/docs/webdriver-vs-protractor.md +++ b/docs/webdriver-vs-protractor.md @@ -39,7 +39,7 @@ adding chaining and utilities for dealing with lists. See Jasmine Integration ------------------- -Protractor uses [`jasminewd`](https://github.com/angular/jasminewd), which +Protractor uses [`jasminewd2`](https://github.com/angular/jasminewd), which wraps around jasmine's `expect` so that you can write: ```js expect(el.getText()).toBe('Hello, World!') diff --git a/example/conf.js b/example/conf.js index 318c91091..24ee94d85 100644 --- a/example/conf.js +++ b/example/conf.js @@ -7,8 +7,8 @@ exports.config = { 'browserName': 'chrome' }, - // Framework to use. Jasmine 2 is recommended. - framework: 'jasmine2', + // Framework to use. Jasmine is recommended. + framework: 'jasmine', // Spec patterns are relative to the current working directly when // protractor is called. diff --git a/lib/cli.js b/lib/cli.js index 75dc0c7b1..5a17c8754 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -59,8 +59,6 @@ var optimist = require('optimist'). alias('platform-version', 'capabilities.version'). alias('tags', 'capabilities.tags'). alias('build', 'capabilities.build'). - alias('verbose', 'jasmineNodeOpts.isVerbose'). - alias('stackTrace', 'jasmineNodeOpts.includeStackTrace'). alias('grep', 'jasmineNodeOpts.grep'). alias('invert-grep', 'jasmineNodeOpts.invertGrep'). alias('explorer', 'elementExplorer'). diff --git a/lib/configParser.js b/lib/configParser.js index ab0b963e2..8f9798a7e 100644 --- a/lib/configParser.js +++ b/lib/configParser.js @@ -29,9 +29,7 @@ var ConfigParser = function() { params: {}, framework: 'jasmine', jasmineNodeOpts: { - isVerbose: false, showColors: true, - includeStackTrace: true, stackFilter: helper.filterStackTrace, defaultTimeoutInterval: (30 * 1000) }, diff --git a/lib/frameworks/README.md b/lib/frameworks/README.md index a7d0e7a38..49a28179b 100644 --- a/lib/frameworks/README.md +++ b/lib/frameworks/README.md @@ -53,7 +53,7 @@ to use your own framework via the config file: ```js exports.config = { - // set to "custom" instead of jasmine/jasmine2/mocha/cucumber. + // set to "custom" instead of jasmine/mocha/cucumber. framework: 'custom', // path relative to the current config file frameworkPath: './frameworks/my_custom_jasmine.js', diff --git a/lib/frameworks/jasmine.js b/lib/frameworks/jasmine.js index 7af99b0fa..0fe6a43d4 100644 --- a/lib/frameworks/jasmine.js +++ b/lib/frameworks/jasmine.js @@ -1,5 +1,55 @@ var q = require('q'); +var RunnerReporter = function(emitter) { + this.emitter = emitter; + this.testResult = [], + this.failedCount = 0; +}; + +RunnerReporter.prototype.jasmineStarted = function() { + // Need to initiate startTime here, in case reportSpecStarting is not + // called (e.g. when fit is used) + this.startTime = new Date(); +}; + +RunnerReporter.prototype.specStarted = function() { + this.startTime = new Date(); +}; + +RunnerReporter.prototype.specDone = function(result) { + var specInfo = { + name: result.description, + category: result.fullName.slice(0, -result.description.length).trim() + }; + if (result.status == 'passed') { + this.emitter.emit('testPass', specInfo); + } else if (result.status == 'failed') { + this.emitter.emit('testFail', specInfo); + this.failedCount++; + } + + var entry = { + description: result.description, + assertions: [], + duration: new Date().getTime() - this.startTime.getTime() + }; + + if (result.failedExpectations.length === 0) { + entry.assertions.push({ + passed: true + }); + } + + result.failedExpectations.forEach(function(item) { + entry.assertions.push({ + passed: item.passed, + errorMsg: item.passed ? undefined : item.message, + stackTrace: item.passed ? undefined : item.stack + }); + }); + this.testResult.push(entry); +}; + /** * Execute the Runner's test cases through Jasmine. * @@ -8,84 +58,61 @@ var q = require('q'); * @return {q.Promise} Promise resolved with the test results */ exports.run = function(runner, specs) { - var minijn = require('minijasminenode'); - - require('jasminewd'); + var JasmineRunner = require('jasmine'); + var jrunner = new JasmineRunner(); /* global jasmine */ - var testResult = []; + require('jasminewd2'); - var RunnerReporter = function(emitter) { - this.emitter = emitter; - - // Need to initiate startTime here, in case reportSpecStarting is not - // called (e.g. when iit is used) - this.startTime = new Date(); - }; - - RunnerReporter.prototype.reportRunnerStarting = function() {}; - RunnerReporter.prototype.reportRunnerResults = function() {}; - RunnerReporter.prototype.reportSuiteResults = function() {}; - RunnerReporter.prototype.reportSpecStarting = function() { - this.startTime = new Date(); - }; - RunnerReporter.prototype.reportSpecResults = function(spec) { - var specInfo = { - name: spec.description, - category: spec.suite.getFullName() - }; - if (!spec.results().skipped) { - if (spec.results().passed()) { - this.emitter.emit('testPass', specInfo); - } else { - this.emitter.emit('testFail', specInfo); - } - } - - var entry = { - description: spec.results().description, - assertions: [], - duration: new Date().getTime() - this.startTime.getTime() - }; - spec.results().getItems().forEach(function(item) { - entry.assertions.push({ - passed: item.passed(), - errorMsg: item.passed() ? undefined : item.message, - stackTrace: item.passed() ? undefined : item.trace.stack - }); - }); - testResult.push(entry); - }; - RunnerReporter.prototype.log = function() {}; + var jasmineNodeOpts = runner.getConfig().jasmineNodeOpts; // On timeout, the flow should be reset. This will prevent webdriver tasks // from overflowing into the next test and causing it to fail or timeout // as well. This is done in the reporter instead of an afterEach block // to ensure that it runs after any afterEach() blocks with webdriver tasks // get to complete first. - jasmine.getEnv().addReporter(new RunnerReporter(runner)); + var reporter = new RunnerReporter(runner); + jasmine.getEnv().addReporter(reporter); + + // Filter specs to run based on jasmineNodeOpts.grep and jasmineNodeOpts.invert. + jasmine.getEnv().specFilter = function(spec) { + var grepMatch = !jasmineNodeOpts || + !jasmineNodeOpts.grep || + spec.getFullName().match(new RegExp(jasmineNodeOpts.grep)) != null; + var invertGrep = !!(jasmineNodeOpts && jasmineNodeOpts.invertGrep); + if (grepMatch == invertGrep) { + spec.pend(); + } + return true; + }; return runner.runTestPreparer().then(function() { return q.promise(function(resolve, reject) { - var jasmineNodeOpts = runner.getConfig().jasmineNodeOpts; + if (jasmineNodeOpts && jasmineNodeOpts.defaultTimeoutInterval) { + jasmine.DEFAULT_TIMEOUT_INTERVAL = jasmineNodeOpts.defaultTimeoutInterval; + } + var originalOnComplete = runner.getConfig().onComplete; - jasmineNodeOpts.onComplete = function(jasmineRunner, log) { + jrunner.onComplete(function(passed) { try { if (originalOnComplete) { - originalOnComplete(jasmineRunner, log); + originalOnComplete(passed); } resolve({ - failedCount: jasmineRunner.results().failedCount, - specResults: testResult + failedCount: reporter.failedCount, + specResults: reporter.testResult }); } catch (err) { reject(err); } - }; + }); - minijn.addSpecs(specs); - minijn.executeSpecs(jasmineNodeOpts); + jrunner.configureDefaultReporter(jasmineNodeOpts); + jrunner.projectBaseDir = ''; + jrunner.specDir = ''; + jrunner.addSpecFiles(specs); + jrunner.execute(); }); }); }; diff --git a/lib/frameworks/jasmine2.js b/lib/frameworks/jasmine2.js deleted file mode 100644 index 0fe6a43d4..000000000 --- a/lib/frameworks/jasmine2.js +++ /dev/null @@ -1,118 +0,0 @@ -var q = require('q'); - -var RunnerReporter = function(emitter) { - this.emitter = emitter; - this.testResult = [], - this.failedCount = 0; -}; - -RunnerReporter.prototype.jasmineStarted = function() { - // Need to initiate startTime here, in case reportSpecStarting is not - // called (e.g. when fit is used) - this.startTime = new Date(); -}; - -RunnerReporter.prototype.specStarted = function() { - this.startTime = new Date(); -}; - -RunnerReporter.prototype.specDone = function(result) { - var specInfo = { - name: result.description, - category: result.fullName.slice(0, -result.description.length).trim() - }; - if (result.status == 'passed') { - this.emitter.emit('testPass', specInfo); - } else if (result.status == 'failed') { - this.emitter.emit('testFail', specInfo); - this.failedCount++; - } - - var entry = { - description: result.description, - assertions: [], - duration: new Date().getTime() - this.startTime.getTime() - }; - - if (result.failedExpectations.length === 0) { - entry.assertions.push({ - passed: true - }); - } - - result.failedExpectations.forEach(function(item) { - entry.assertions.push({ - passed: item.passed, - errorMsg: item.passed ? undefined : item.message, - stackTrace: item.passed ? undefined : item.stack - }); - }); - this.testResult.push(entry); -}; - -/** - * Execute the Runner's test cases through Jasmine. - * - * @param {Runner} runner The current Protractor Runner. - * @param {Array} specs Array of Directory Path Strings. - * @return {q.Promise} Promise resolved with the test results - */ -exports.run = function(runner, specs) { - var JasmineRunner = require('jasmine'); - var jrunner = new JasmineRunner(); - /* global jasmine */ - - require('jasminewd2'); - - var jasmineNodeOpts = runner.getConfig().jasmineNodeOpts; - - // On timeout, the flow should be reset. This will prevent webdriver tasks - // from overflowing into the next test and causing it to fail or timeout - // as well. This is done in the reporter instead of an afterEach block - // to ensure that it runs after any afterEach() blocks with webdriver tasks - // get to complete first. - var reporter = new RunnerReporter(runner); - jasmine.getEnv().addReporter(reporter); - - // Filter specs to run based on jasmineNodeOpts.grep and jasmineNodeOpts.invert. - jasmine.getEnv().specFilter = function(spec) { - var grepMatch = !jasmineNodeOpts || - !jasmineNodeOpts.grep || - spec.getFullName().match(new RegExp(jasmineNodeOpts.grep)) != null; - var invertGrep = !!(jasmineNodeOpts && jasmineNodeOpts.invertGrep); - if (grepMatch == invertGrep) { - spec.pend(); - } - return true; - }; - - return runner.runTestPreparer().then(function() { - return q.promise(function(resolve, reject) { - if (jasmineNodeOpts && jasmineNodeOpts.defaultTimeoutInterval) { - jasmine.DEFAULT_TIMEOUT_INTERVAL = jasmineNodeOpts.defaultTimeoutInterval; - } - - var originalOnComplete = runner.getConfig().onComplete; - - jrunner.onComplete(function(passed) { - try { - if (originalOnComplete) { - originalOnComplete(passed); - } - resolve({ - failedCount: reporter.failedCount, - specResults: reporter.testResult - }); - } catch (err) { - reject(err); - } - }); - - jrunner.configureDefaultReporter(jasmineNodeOpts); - jrunner.projectBaseDir = ''; - jrunner.specDir = ''; - jrunner.addSpecFiles(specs); - jrunner.execute(); - }); - }); -}; diff --git a/lib/runner.js b/lib/runner.js index 9934e962d..a7785a0dc 100644 --- a/lib/runner.js +++ b/lib/runner.js @@ -276,10 +276,9 @@ Runner.prototype.run = function() { // Do the framework setup here so that jasmine and mocha globals are // available to the onPrepare function. var frameworkPath = ''; - if (self.config_.framework === 'jasmine') { + if (self.config_.framework === 'jasmine' || + self.config_.framework === 'jasmine2') { frameworkPath = './frameworks/jasmine.js'; - } else if (self.config_.framework === 'jasmine2') { - frameworkPath = './frameworks/jasmine2.js'; } else if (self.config_.framework === 'mocha') { frameworkPath = './frameworks/mocha.js'; } else if (self.config_.framework === 'cucumber') { diff --git a/lib/util.js b/lib/util.js index ec26732d0..714feabbc 100644 --- a/lib/util.js +++ b/lib/util.js @@ -2,14 +2,12 @@ var q = require('q'), path = require('path'); var STACK_SUBSTRINGS_TO_FILTER = [ - 'node_modules/minijasminenode/lib/', 'node_modules/jasmine/', 'node_modules/selenium-webdriver', 'at Module.', 'at Object.Module.', 'at Function.Module', '(timers.js:', - 'jasminewd/index.js', 'jasminewd2/index.js', 'protractor/lib/' ]; diff --git a/package.json b/package.json index 7986e9bb1..309ca668b 100644 --- a/package.json +++ b/package.json @@ -14,8 +14,6 @@ "dependencies": { "request": "~2.57.0", "selenium-webdriver": "2.47.0", - "minijasminenode": "1.1.1", - "jasminewd": "1.1.0", "jasminewd2": "0.0.6", "jasmine": "2.3.2", "saucelabs": "~1.0.1", diff --git a/plugins/accessibility/spec/failureConfig.js b/plugins/accessibility/spec/failureConfig.js index 4fc1acabd..4ec69fb15 100644 --- a/plugins/accessibility/spec/failureConfig.js +++ b/plugins/accessibility/spec/failureConfig.js @@ -2,7 +2,7 @@ var env = require('../../../spec/environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: ['fail_spec.js'], baseUrl: env.baseUrl, plugins: [{ diff --git a/plugins/accessibility/spec/successConfig.js b/plugins/accessibility/spec/successConfig.js index a123a8d90..fa2757690 100644 --- a/plugins/accessibility/spec/successConfig.js +++ b/plugins/accessibility/spec/successConfig.js @@ -2,7 +2,7 @@ var env = require('../../../spec/environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: ['success_spec.js'], baseUrl: env.baseUrl, plugins: [{ diff --git a/plugins/console/spec/consoleFailConfig.js b/plugins/console/spec/consoleFailConfig.js index 335e2e09e..0787b841f 100644 --- a/plugins/console/spec/consoleFailConfig.js +++ b/plugins/console/spec/consoleFailConfig.js @@ -2,7 +2,7 @@ var env = require('../../../spec/environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: ['fail_spec.js'], baseUrl: env.baseUrl, plugins: [{ diff --git a/plugins/console/spec/consoleFailErrorConfig.js b/plugins/console/spec/consoleFailErrorConfig.js index e1c21baf2..42ec16798 100644 --- a/plugins/console/spec/consoleFailErrorConfig.js +++ b/plugins/console/spec/consoleFailErrorConfig.js @@ -2,7 +2,7 @@ var env = require('../../../spec/environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: ['fail_error_spec.js'], baseUrl: env.baseUrl, plugins: [{ diff --git a/plugins/console/spec/consoleFailFilterConfig.js b/plugins/console/spec/consoleFailFilterConfig.js index 30d0f5cea..f5a6ed239 100644 --- a/plugins/console/spec/consoleFailFilterConfig.js +++ b/plugins/console/spec/consoleFailFilterConfig.js @@ -2,7 +2,7 @@ var env = require('../../../spec/environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: ['fail_error_spec.js'], baseUrl: env.baseUrl, plugins: [{ diff --git a/plugins/console/spec/consoleFailLogWarnings.js b/plugins/console/spec/consoleFailLogWarnings.js index 7db6942be..d531866a0 100644 --- a/plugins/console/spec/consoleFailLogWarnings.js +++ b/plugins/console/spec/consoleFailLogWarnings.js @@ -2,7 +2,7 @@ var env = require('../../../spec/environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: ['fail_warning_spec.js'], baseUrl: env.baseUrl, plugins: [{ diff --git a/plugins/console/spec/consoleFailWarningConfig.js b/plugins/console/spec/consoleFailWarningConfig.js index ec03b5e30..cbb39425a 100644 --- a/plugins/console/spec/consoleFailWarningConfig.js +++ b/plugins/console/spec/consoleFailWarningConfig.js @@ -2,7 +2,7 @@ var env = require('../../../spec/environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: ['fail_warning_spec.js'], baseUrl: env.baseUrl, plugins: [{ diff --git a/plugins/console/spec/consolePassConfig.js b/plugins/console/spec/consolePassConfig.js index ecac0d2af..4cfddee76 100644 --- a/plugins/console/spec/consolePassConfig.js +++ b/plugins/console/spec/consolePassConfig.js @@ -2,7 +2,7 @@ var env = require('../../../spec/environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: ['pass_spec.js'], baseUrl: env.baseUrl, plugins: [{ diff --git a/plugins/console/spec/consolePassLogWarnings.js b/plugins/console/spec/consolePassLogWarnings.js index a6507ce15..84b6063f2 100644 --- a/plugins/console/spec/consolePassLogWarnings.js +++ b/plugins/console/spec/consolePassLogWarnings.js @@ -2,7 +2,7 @@ var env = require('../../../spec/environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: ['pass_spec.js'], baseUrl: env.baseUrl, plugins: [{ diff --git a/plugins/ngHint/spec/failureConfig.js b/plugins/ngHint/spec/failureConfig.js index 7f78a4b9a..dbe49f445 100644 --- a/plugins/ngHint/spec/failureConfig.js +++ b/plugins/ngHint/spec/failureConfig.js @@ -2,7 +2,7 @@ var env = require('../../../spec/environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: ['fail_spec.js'], baseUrl: env.baseUrl, plugins: [{ diff --git a/plugins/ngHint/spec/successConfig.js b/plugins/ngHint/spec/successConfig.js index c1d29cf08..dfd6d9d93 100644 --- a/plugins/ngHint/spec/successConfig.js +++ b/plugins/ngHint/spec/successConfig.js @@ -2,7 +2,7 @@ var env = require('../../../spec/environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: ['success_spec.js'], baseUrl: env.baseUrl, plugins: [{ diff --git a/scripts/test.js b/scripts/test.js index a1cdb0424..1027810c4 100755 --- a/scripts/test.js +++ b/scripts/test.js @@ -21,8 +21,7 @@ var passingTests = [ 'node lib/cli.js spec/suitesConf.js --suite okmany,okspec', 'node lib/cli.js spec/plugins/smokeConf.js', 'node lib/cli.js spec/plugins/multiPluginConf.js', - 'node lib/cli.js spec/plugins/jasmine1PostTestConf.js', - 'node lib/cli.js spec/plugins/jasmine2PostTestConf.js', + 'node lib/cli.js spec/plugins/jasminePostTestConf.js', 'node lib/cli.js spec/plugins/mochaPostTestConf.js', 'node lib/cli.js spec/plugins/cucumberPostTestConf.js', 'node lib/cli.js spec/plugins/browserGetSyncedConf.js', @@ -34,22 +33,18 @@ var passingTests = [ 'node lib/cli.js spec/getCapabilitiesConf.js', 'node lib/cli.js spec/controlLockConf.js', 'node lib/cli.js spec/customFramework.js', - 'node node_modules/.bin/jasmine JASMINE_CONFIG_PATH=scripts/unit_test.json', 'node scripts/interactive_tests/interactive_test.js', - 'node scripts/interactive_tests/with_base_url.js' + 'node scripts/interactive_tests/with_base_url.js', + // Unit tests + 'node node_modules/.bin/jasmine JASMINE_CONFIG_PATH=scripts/unit_test.json', + // Plugins + 'node lib/cli.js plugins/timeline/spec/conf.js', + 'node lib/cli.js plugins/ngHint/spec/successConfig.js', + 'node lib/cli.js plugins/accessibility/spec/successConfig.js', + 'node lib/cli.js plugins/console/spec/consolePassConfig.js', + 'node lib/cli.js plugins/console/spec/consolePassLogWarnings.js' ]; -// Plugins -passingTests.push('node node_modules/minijasminenode/bin/minijn ' + - 'plugins/timeline/spec/unit.js'); -passingTests.push( - 'node lib/cli.js plugins/timeline/spec/conf.js', - 'node lib/cli.js plugins/ngHint/spec/successConfig.js', - 'node lib/cli.js plugins/accessibility/spec/successConfig.js', - 'node lib/cli.js plugins/console/spec/consolePassConfig.js', - 'node lib/cli.js plugins/console/spec/consolePassLogWarnings.js' -); - var executor = new Executor(); passingTests.forEach(function(passing_test) { diff --git a/scripts/unit_test.json b/scripts/unit_test.json index aa5e7bacd..c3ff16f47 100644 --- a/scripts/unit_test.json +++ b/scripts/unit_test.json @@ -2,6 +2,7 @@ "spec_dir": "", "spec_files": [ "spec/unit/*.js", - "website/docgen/spec/*.js" + "website/docgen/spec/*.js", + "plugins/timeline/spec/unit.js" ] } diff --git a/spec/altRootConf.js b/spec/altRootConf.js index 21eb942fb..0d480d009 100644 --- a/spec/altRootConf.js +++ b/spec/altRootConf.js @@ -4,7 +4,7 @@ var env = require('./environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', // Spec patterns are relative to this config. specs: [ diff --git a/spec/angular2Conf.js b/spec/angular2Conf.js index f87aa3668..22200e94b 100644 --- a/spec/angular2Conf.js +++ b/spec/angular2Conf.js @@ -15,7 +15,7 @@ var env = require('./environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: [ 'ng2/async_spec.js' diff --git a/spec/basicConf.js b/spec/basicConf.js index 3509f76f7..5e0bdd275 100644 --- a/spec/basicConf.js +++ b/spec/basicConf.js @@ -4,7 +4,7 @@ var env = require('./environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', // Spec patterns are relative to this directory. specs: [ @@ -20,11 +20,6 @@ exports.config = { baseUrl: env.baseUrl, - jasmineNodeOpts: { - isVerbose: true, - realtimeFailure: true - }, - params: { login: { user: 'Jane', diff --git a/spec/ciFullConf.js b/spec/ciFullConf.js index 01b575eb3..417d526de 100644 --- a/spec/ciFullConf.js +++ b/spec/ciFullConf.js @@ -5,7 +5,7 @@ exports.config = { sauceUser: process.env.SAUCE_USERNAME, sauceKey: process.env.SAUCE_ACCESS_KEY, - framework: 'jasmine2', + framework: 'jasmine', // Spec patterns are relative to this directory. specs: [ @@ -38,7 +38,6 @@ exports.config = { baseUrl: env.baseUrl, jasmineNodeOpts: { - isVerbose: true, showTiming: true, defaultTimeoutInterval: 90000 }, diff --git a/spec/ciSmokeConf.js b/spec/ciSmokeConf.js index d107bb7ce..438de71ae 100644 --- a/spec/ciSmokeConf.js +++ b/spec/ciSmokeConf.js @@ -6,7 +6,7 @@ exports.config = { sauceUser: process.env.SAUCE_USERNAME, sauceKey: process.env.SAUCE_ACCESS_KEY, - framework: 'jasmine2', + framework: 'jasmine', specs: [ 'basic/locators_spec.js', @@ -74,7 +74,6 @@ exports.config = { getPageTimeout: 30000, jasmineNodeOpts: { - isVerbose: true, showTiming: true, defaultTimeoutInterval: 90000 }, diff --git a/spec/controlLockConf.js b/spec/controlLockConf.js index 6051b1887..9f8f7bf38 100644 --- a/spec/controlLockConf.js +++ b/spec/controlLockConf.js @@ -6,7 +6,7 @@ var webdriver = require('selenium-webdriver'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: [ 'control/spec.js' diff --git a/spec/directConnectConf.js b/spec/directConnectConf.js index de578f5e8..28e924e97 100644 --- a/spec/directConnectConf.js +++ b/spec/directConnectConf.js @@ -4,7 +4,7 @@ var env = require('./environment.js'); exports.config = { directConnect: true, - framework: 'jasmine2', + framework: 'jasmine', multiCapabilities: [{ 'browserName': 'chrome' diff --git a/spec/errorTest/afterLaunchChangesExitCodeConf.js b/spec/errorTest/afterLaunchChangesExitCodeConf.js index 7647398ee..107d5e30d 100644 --- a/spec/errorTest/afterLaunchChangesExitCodeConf.js +++ b/spec/errorTest/afterLaunchChangesExitCodeConf.js @@ -3,7 +3,7 @@ var env = require('../environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: [ 'baseCase/single_failure_spec1.js' @@ -16,8 +16,6 @@ exports.config = { baseUrl: env.baseUrl, jasmineNodeOpts: { - isVerbose: true, - showTiming: true, defaultTimeoutInterval: 90000 }, diff --git a/spec/errorTest/multiFailureConf.js b/spec/errorTest/multiFailureConf.js index 784c8c101..42ee68101 100644 --- a/spec/errorTest/multiFailureConf.js +++ b/spec/errorTest/multiFailureConf.js @@ -3,7 +3,7 @@ var env = require('../environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: [ 'baseCase/single_failure_spec1.js', @@ -17,8 +17,6 @@ exports.config = { baseUrl: env.baseUrl, jasmineNodeOpts: { - isVerbose: true, - showTiming: true, defaultTimeoutInterval: 90000 } diff --git a/spec/errorTest/pluginsFailingConf.js b/spec/errorTest/pluginsFailingConf.js index ba4e5b861..c159e912e 100644 --- a/spec/errorTest/pluginsFailingConf.js +++ b/spec/errorTest/pluginsFailingConf.js @@ -5,7 +5,7 @@ exports.config = { // seleniumAddress: env.seleniumAddress, mockSelenium: true, - framework: 'jasmine2', + framework: 'jasmine', // Spec patterns are relative to this directory. specs: [ @@ -16,11 +16,6 @@ exports.config = { baseUrl: env.baseUrl, - jasmineNodeOpts: { - isVerbose: true, - realtimeFailure: true - }, - // Plugin patterns are relative to this directory. plugins: [{ path: '../plugins/plugins/basic_plugin.js' diff --git a/spec/errorTest/shardedFailureConf.js b/spec/errorTest/shardedFailureConf.js index abb4e646c..1e9b687bf 100644 --- a/spec/errorTest/shardedFailureConf.js +++ b/spec/errorTest/shardedFailureConf.js @@ -3,7 +3,7 @@ var env = require('../environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: [ 'baseCase/single_failure_spec1.js', @@ -19,8 +19,6 @@ exports.config = { baseUrl: env.baseUrl, jasmineNodeOpts: { - isVerbose: true, - showTiming: true, defaultTimeoutInterval: 90000 } diff --git a/spec/errorTest/singleFailureConf.js b/spec/errorTest/singleFailureConf.js index 0432fee51..4da76b8cd 100644 --- a/spec/errorTest/singleFailureConf.js +++ b/spec/errorTest/singleFailureConf.js @@ -3,7 +3,7 @@ var env = require('../environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: [ 'baseCase/single_failure_spec1.js' @@ -16,8 +16,6 @@ exports.config = { baseUrl: env.baseUrl, jasmineNodeOpts: { - isVerbose: true, - showTiming: true, defaultTimeoutInterval: 90000 } diff --git a/spec/errorTest/slowHttpAndTimeoutConf.js b/spec/errorTest/slowHttpAndTimeoutConf.js index a0d7a76eb..22d5974ea 100644 --- a/spec/errorTest/slowHttpAndTimeoutConf.js +++ b/spec/errorTest/slowHttpAndTimeoutConf.js @@ -3,7 +3,7 @@ var env = require('../environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: [ 'baseCase/slow_http_and_timeout_spec.js' diff --git a/spec/errorTest/timeoutConf.js b/spec/errorTest/timeoutConf.js index 4bd1d9c01..25d7ba2ca 100644 --- a/spec/errorTest/timeoutConf.js +++ b/spec/errorTest/timeoutConf.js @@ -3,7 +3,7 @@ var env = require('../environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: [ 'baseCase/timeout_spec.js' @@ -16,8 +16,6 @@ exports.config = { baseUrl: env.baseUrl, jasmineNodeOpts: { - isVerbose: true, - showTiming: true, defaultTimeoutInterval: 90000 } diff --git a/spec/interactionConf.js b/spec/interactionConf.js index c63353d47..e4fbc49b7 100644 --- a/spec/interactionConf.js +++ b/spec/interactionConf.js @@ -4,7 +4,7 @@ var env = require('./environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', // Spec patterns are relative to this directory. specs: [ diff --git a/spec/multiConf.js b/spec/multiConf.js index 11bf5b8c3..a15775cec 100644 --- a/spec/multiConf.js +++ b/spec/multiConf.js @@ -4,7 +4,7 @@ var env = require('./environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', // Spec patterns are relative to this directory. specs: [ diff --git a/spec/onCleanUpAsyncReturnValueConf.js b/spec/onCleanUpAsyncReturnValueConf.js index 781a63911..d32dbe282 100644 --- a/spec/onCleanUpAsyncReturnValueConf.js +++ b/spec/onCleanUpAsyncReturnValueConf.js @@ -5,7 +5,7 @@ var q = require('q'); exports.config = { mockSelenium: true, - framework: 'jasmine2', + framework: 'jasmine', specs: [ 'onCleanUp/*_spec.js' diff --git a/spec/onCleanUpNoReturnValueConf.js b/spec/onCleanUpNoReturnValueConf.js index e4609fecc..f17585ca8 100644 --- a/spec/onCleanUpNoReturnValueConf.js +++ b/spec/onCleanUpNoReturnValueConf.js @@ -4,7 +4,7 @@ var env = require('./environment.js'); exports.config = { mockSelenium: true, - framework: 'jasmine2', + framework: 'jasmine', specs: [ 'onCleanUp/*_spec.js' diff --git a/spec/onCleanUpSyncReturnValueConf.js b/spec/onCleanUpSyncReturnValueConf.js index 5b3fe3bbc..600eb6ab3 100644 --- a/spec/onCleanUpSyncReturnValueConf.js +++ b/spec/onCleanUpSyncReturnValueConf.js @@ -4,7 +4,7 @@ var env = require('./environment.js'); exports.config = { mockSelenium: true, - framework: 'jasmine2', + framework: 'jasmine', specs: [ 'onCleanUp/*_spec.js' diff --git a/spec/onPrepareConf.js b/spec/onPrepareConf.js index cf41a6e6e..9dd9720c0 100644 --- a/spec/onPrepareConf.js +++ b/spec/onPrepareConf.js @@ -6,7 +6,7 @@ var env = require('./environment.js'); exports.config = { mockSelenium: true, - framework: 'jasmine2', + framework: 'jasmine', specs: [ 'onPrepare/*_spec.js' diff --git a/spec/onPrepareFileConf.js b/spec/onPrepareFileConf.js index f34110082..2f9c4ba24 100644 --- a/spec/onPrepareFileConf.js +++ b/spec/onPrepareFileConf.js @@ -5,7 +5,7 @@ var env = require('./environment.js'); exports.config = { mockSelenium: true, - framework: 'jasmine2', + framework: 'jasmine', // Spec patterns are relative to this directory. specs: [ diff --git a/spec/onPreparePromiseConf.js b/spec/onPreparePromiseConf.js index cd482ee73..719ddbdec 100644 --- a/spec/onPreparePromiseConf.js +++ b/spec/onPreparePromiseConf.js @@ -7,7 +7,7 @@ var q = require('q'); exports.config = { mockSelenium: true, - framework: 'jasmine2', + framework: 'jasmine', specs: [ 'onPrepare/*_spec.js' diff --git a/spec/onPreparePromiseFileConf.js b/spec/onPreparePromiseFileConf.js index f5339c3f5..57a708238 100644 --- a/spec/onPreparePromiseFileConf.js +++ b/spec/onPreparePromiseFileConf.js @@ -5,7 +5,7 @@ var env = require('./environment.js'); exports.config = { mockSelenium: true, - framework: 'jasmine2', + framework: 'jasmine', // Spec patterns are relative to this directory. specs: [ diff --git a/spec/plugins/browserGetSyncedConf.js b/spec/plugins/browserGetSyncedConf.js index 293a06949..6757c5725 100644 --- a/spec/plugins/browserGetSyncedConf.js +++ b/spec/plugins/browserGetSyncedConf.js @@ -5,7 +5,7 @@ var env = require('../environment.js'), exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', // Spec patterns are relative to this directory. specs: [ @@ -16,11 +16,6 @@ exports.config = { baseUrl: env.baseUrl, - jasmineNodeOpts: { - isVerbose: true, - realtimeFailure: true - }, - // Plugin patterns are relative to this directory. plugins: [{ inline: { diff --git a/spec/plugins/browserGetUnsyncedConf.js b/spec/plugins/browserGetUnsyncedConf.js index 15c9f4ebd..b677eed58 100644 --- a/spec/plugins/browserGetUnsyncedConf.js +++ b/spec/plugins/browserGetUnsyncedConf.js @@ -5,7 +5,7 @@ var env = require('../environment.js'), exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', // Spec patterns are relative to this directory. specs: [ @@ -16,11 +16,6 @@ exports.config = { baseUrl: env.baseUrl, - jasmineNodeOpts: { - isVerbose: true, - realtimeFailure: true - }, - // Plugin patterns are relative to this directory. plugins: [{ inline: { diff --git a/spec/plugins/jasmine2PostTestConf.js b/spec/plugins/jasmine2PostTestConf.js deleted file mode 100644 index bc152fc67..000000000 --- a/spec/plugins/jasmine2PostTestConf.js +++ /dev/null @@ -1 +0,0 @@ -exports.config = require('./postTestConfTemplate')('jasmine2'); diff --git a/spec/plugins/jasmine1PostTestConf.js b/spec/plugins/jasminePostTestConf.js similarity index 100% rename from spec/plugins/jasmine1PostTestConf.js rename to spec/plugins/jasminePostTestConf.js diff --git a/spec/plugins/multiPluginConf.js b/spec/plugins/multiPluginConf.js index 6b4b75b4b..1ed3f1ec4 100644 --- a/spec/plugins/multiPluginConf.js +++ b/spec/plugins/multiPluginConf.js @@ -4,7 +4,7 @@ var env = require('../environment.js'); exports.config = { mockSelenium: true, - framework: 'jasmine2', + framework: 'jasmine', // Spec patterns are relative to this directory. specs: [ @@ -15,11 +15,6 @@ exports.config = { baseUrl: env.baseUrl, - jasmineNodeOpts: { - isVerbose: true, - realtimeFailure: true - }, - // Plugin patterns are relative to this directory. plugins: [{ path: 'plugins/basic_plugin.js' diff --git a/spec/plugins/smokeConf.js b/spec/plugins/smokeConf.js index 1be56e485..f1145e24b 100644 --- a/spec/plugins/smokeConf.js +++ b/spec/plugins/smokeConf.js @@ -5,7 +5,7 @@ var env = require('../environment.js'); exports.config = { mockSelenium: true, - framework: 'jasmine2', + framework: 'jasmine', // Spec patterns are relative to this directory. specs: [ @@ -16,11 +16,6 @@ exports.config = { baseUrl: env.baseUrl, - jasmineNodeOpts: { - isVerbose: true, - realtimeFailure: true - }, - // Plugin patterns are relative to this directory. plugins: [{ path: 'plugins/basic_plugin.js' diff --git a/spec/plugins/waitForAngularConf.js b/spec/plugins/waitForAngularConf.js index 6e835ddf5..934c045dc 100644 --- a/spec/plugins/waitForAngularConf.js +++ b/spec/plugins/waitForAngularConf.js @@ -5,7 +5,7 @@ var env = require('../environment.js'), exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', // Spec patterns are relative to this directory. specs: [ @@ -16,11 +16,6 @@ exports.config = { baseUrl: env.baseUrl, - jasmineNodeOpts: { - isVerbose: true, - realtimeFailure: true - }, - // Plugin patterns are relative to this directory. plugins: [{ inline: { diff --git a/spec/restartBrowserBetweenTestsConf.js b/spec/restartBrowserBetweenTestsConf.js index 91e08a31c..f0ff5ec15 100644 --- a/spec/restartBrowserBetweenTestsConf.js +++ b/spec/restartBrowserBetweenTestsConf.js @@ -4,7 +4,7 @@ var env = require('./environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', // Spec patterns are relative to this directory. specs: [ @@ -15,10 +15,5 @@ exports.config = { baseUrl: env.baseUrl, - jasmineNodeOpts: { - isVerbose: true, - realtimeFailure: true - }, - restartBrowserBetweenTests: true }; diff --git a/spec/suitesConf.js b/spec/suitesConf.js index 7fb93566e..eb6e0113a 100644 --- a/spec/suitesConf.js +++ b/spec/suitesConf.js @@ -3,7 +3,7 @@ var env = require('./environment.js'); exports.config = { mockSelenium: true, - framework: 'jasmine2', + framework: 'jasmine', // Spec patterns are relative to this directory. suites: { diff --git a/spec/withLoginConf.js b/spec/withLoginConf.js index 3d80410e2..aee125cd1 100644 --- a/spec/withLoginConf.js +++ b/spec/withLoginConf.js @@ -5,7 +5,7 @@ var env = require('./environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, - framework: 'jasmine2', + framework: 'jasmine', specs: [ 'login/login_spec.js' diff --git a/stress/conf.js b/stress/conf.js index f7d8184c3..0bed4bc72 100644 --- a/stress/conf.js +++ b/stress/conf.js @@ -61,10 +61,5 @@ exports.config = { 'platform': 'Windows 7' }], - baseUrl: env.baseUrl, - - jasmineNodeOpts: { - isVerbose: true, - showTiming: true - } + baseUrl: env.baseUrl }; diff --git a/website/index.html b/website/index.html index 8f184c232..5e36f3644 100644 --- a/website/index.html +++ b/website/index.html @@ -75,7 +75,7 @@
  • Timeouts
  • The WebDriver Control Flow
  • How It Works
  • -
  • Upgrading to Jasmine 2.0
  • +
  • Upgrading to Jasmine 2.x
  • Mobile Setup
  • FAQ
  • diff --git a/website/package.json b/website/package.json index acab816d0..f5405c1d4 100644 --- a/website/package.json +++ b/website/package.json @@ -20,7 +20,7 @@ "karma-jasmine": "^0.1.5", "lodash": "^2.4.1", "marked": "^0.3.3", - "minijasminenode": "^1.1.1" + "jasmine": "2.3.2" }, "scripts": { "prepublish": "./node_modules/bower/bin/bower install", diff --git a/website/protractor.conf.js b/website/protractor.conf.js index e788185e8..048162f1b 100644 --- a/website/protractor.conf.js +++ b/website/protractor.conf.js @@ -22,10 +22,7 @@ exports.config = { baseUrl: 'http://localhost:8080', jasmineNodeOpts: { - onComplete: null, - isVerbose: false, showColors: true, - includeStackTrace: true, defaultTimeoutInterval: 10000 } }; diff --git a/website/run-tests.js b/website/run-tests.js index 6e005bd71..8e96399dc 100755 --- a/website/run-tests.js +++ b/website/run-tests.js @@ -7,8 +7,7 @@ var scripts = []; // Dgeni tests. scripts.push( - 'node node_modules/.bin/minijasminenode ' + - glob('docgen/spec/*.js').join(' ')); + 'node node_modules/.bin/jasmine JASMINE_CONFIG_PATH=unit_test.json'); // Karma tests. scripts.push('node_modules/karma/bin/karma start --singleRun true'); diff --git a/website/test/e2e/api_spec.js b/website/test/e2e/api_spec.js index 1a2f55a10..74ca4b34f 100644 --- a/website/test/e2e/api_spec.js +++ b/website/test/e2e/api_spec.js @@ -114,7 +114,7 @@ describe('Api', function() { // Then ensure the child functions are shown. expect(apiPage.getChildFunctionNames()).toEqual([ - 'getProcessedConfig', 'forkNewDriverInstance', + 'getProcessedConfig', 'forkNewDriverInstance', 'useAllAngular2AppRoots', 'waitForAngular', 'findElement', 'findElements', 'isElementPresent', 'addMockModule', 'clearMockModules', 'removeMockModule', 'getRegisteredMockModules', 'get', 'refresh', 'navigate', 'setLocation', diff --git a/website/test/e2e/navigation_spec.js b/website/test/e2e/navigation_spec.js index a5b74803b..7cfccb906 100644 --- a/website/test/e2e/navigation_spec.js +++ b/website/test/e2e/navigation_spec.js @@ -67,7 +67,7 @@ describe('Navigation', function() { 'Timeouts', 'The WebDriver Control Flow', 'How It Works', - 'Upgrading to Jasmine 2.0', + 'Upgrading to Jasmine 2.x', 'Mobile Setup', 'FAQ' ]); @@ -181,8 +181,8 @@ describe('Navigation', function() { expect($('h1').getText()).toBe('How It Works'); }); - it('should go to Upgrading to Jasmine 2.0', function() { - menu.dropdown('Reference').item('Upgrading to Jasmine 2.0'); + it('should go to Upgrading to Jasmine 2.x', function() { + menu.dropdown('Reference').item('Upgrading to Jasmine 2.x'); expect($('h1').getText()).toBe('Upgrading from Jasmine 1.3 to 2.x'); }); diff --git a/website/unit_test.json b/website/unit_test.json new file mode 100644 index 000000000..b4e8b8486 --- /dev/null +++ b/website/unit_test.json @@ -0,0 +1,6 @@ +{ + "spec_dir": "", + "spec_files": [ + "docgen/spec/*.js" + ] +} From 18e1f71a4dd868709f4e259e05a8a196921e22be Mon Sep 17 00:00:00 2001 From: Hank Duan Date: Tue, 3 Nov 2015 10:55:03 -0800 Subject: [PATCH 004/678] chore(webdriver): upgrade Protractor to webdriver 2.48.2 BREAKING CHANGE: 1) Users will no longer be able to use node versions <4. 2) There is significant changes to the control flow, and tests may need to be modified to be compliant with the new control flow. See https://github.com/SeleniumHQ/selenium/blob/master/javascript/node/selenium-webdriver/CHANGES.md --- .travis.yml | 7 ++----- config.json | 2 +- package.json | 2 +- spec/ciFullConf.js | 4 ++-- spec/ciSmokeConf.js | 8 ++++---- 5 files changed, 10 insertions(+), 13 deletions(-) diff --git a/.travis.yml b/.travis.yml index 8015495d5..8fa32e2c8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,8 @@ language: node_js sudo: false node_js: - - "0.10" - - "0.12" - "4" + - "5" env: global: @@ -20,9 +19,7 @@ matrix: - env: "JOB=smoke" exclude: - env: JOB=smoke - node_js: "0.12" - - env: JOB=smoke - node_js: "0.10" + node_js: "5" before_script: diff --git a/config.json b/config.json index cdc20d938..b02dff369 100644 --- a/config.json +++ b/config.json @@ -1,6 +1,6 @@ { "webdriverVersions": { - "selenium": "2.47.1", + "selenium": "2.48.2", "chromedriver": "2.19", "iedriver": "2.47.0" } diff --git a/package.json b/package.json index 309ca668b..ddb9a22c3 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "author": "Julie Ralph ", "dependencies": { "request": "~2.57.0", - "selenium-webdriver": "2.47.0", + "selenium-webdriver": "2.48.2", "jasminewd2": "0.0.6", "jasmine": "2.3.2", "saucelabs": "~1.0.1", diff --git a/spec/ciFullConf.js b/spec/ciFullConf.js index 417d526de..de363d079 100644 --- a/spec/ciFullConf.js +++ b/spec/ciFullConf.js @@ -23,7 +23,7 @@ exports.config = { 'build': process.env.TRAVIS_BUILD_NUMBER, 'name': 'Protractor suite tests', 'version': '45', - 'selenium-version': '2.47.1', + 'selenium-version': '2.48.2', 'chromedriver-version': '2.19', 'platform': 'OS X 10.9' }, { @@ -32,7 +32,7 @@ exports.config = { 'build': process.env.TRAVIS_BUILD_NUMBER, 'name': 'Protractor suite tests', 'version': '40', - 'selenium-version': '2.47.1' + 'selenium-version': '2.48.2' }], baseUrl: env.baseUrl, diff --git a/spec/ciSmokeConf.js b/spec/ciSmokeConf.js index 438de71ae..9ca49c89a 100644 --- a/spec/ciSmokeConf.js +++ b/spec/ciSmokeConf.js @@ -24,7 +24,7 @@ exports.config = { 'build': process.env.TRAVIS_BUILD_NUMBER, 'name': 'Protractor smoke tests', 'version': '44', - 'selenium-version': '2.47.1', + 'selenium-version': '2.48.2', 'chromedriver-version': '2.19', 'platform': 'OS X 10.9' }, { @@ -33,7 +33,7 @@ exports.config = { 'build': process.env.TRAVIS_BUILD_NUMBER, 'name': 'Protractor smoke tests', 'version': '39', - 'selenium-version': '2.47.1' + 'selenium-version': '2.48.2' }, { 'browserName': 'safari', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, @@ -55,7 +55,7 @@ exports.config = { 'build': process.env.TRAVIS_BUILD_NUMBER, 'name': 'Protractor smoke tests', 'version': '11', - 'selenium-version': '2.47.1', + 'selenium-version': '2.48.2', 'platform': 'Windows 7' }, { 'browserName': 'internet explorer', @@ -63,7 +63,7 @@ exports.config = { 'build': process.env.TRAVIS_BUILD_NUMBER, 'name': 'Protractor smoke tests', 'version': '10', - 'selenium-version': '2.47.1', + 'selenium-version': '2.48.2', 'platform': 'Windows 7' }], From 372263f93acf94334eee0547a4ad4152dd8a5842 Mon Sep 17 00:00:00 2001 From: Charlie Rudolph Date: Sat, 17 Oct 2015 10:15:04 -0600 Subject: [PATCH 005/678] chore(source-map-support): bump source-map-support version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index ddb9a22c3..ed2ed0665 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,7 @@ "optimist": "~0.6.0", "q": "1.0.0", "lodash": "~2.4.1", - "source-map-support": "~0.2.6", + "source-map-support": "~0.3.2", "html-entities": "~1.1.1", "accessibility-developer-tools": "~2.6.0" }, From 4924028c40b33821cc88d291328c6307859b5490 Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Tue, 3 Nov 2015 18:20:26 -0800 Subject: [PATCH 006/678] feat(runner): make source map support optional Closes #2603 --- docs/referenceConf.js | 9 ++++++++- lib/configParser.js | 3 ++- lib/runner.js | 6 ++++-- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/docs/referenceConf.js b/docs/referenceConf.js index 6f84036c7..b819d10bd 100644 --- a/docs/referenceConf.js +++ b/docs/referenceConf.js @@ -311,5 +311,12 @@ exports.config = { tags: '@dev', // How to format features (default: progress) format: 'summary' - } + }, + + // See docs/plugins.md + plugins: [], + + // Turns off source map support. Stops protractor from registering global + // variable `source-map-support`. Defaults to `false` + skipSourceMapSupport: false }; diff --git a/lib/configParser.js b/lib/configParser.js index 8f9798a7e..f03e1cd42 100644 --- a/lib/configParser.js +++ b/lib/configParser.js @@ -41,7 +41,8 @@ var ConfigParser = function() { }, chromeDriver: null, configDir: './', - plugins: [] + plugins: [], + skipSourceMapSupport: false }; }; diff --git a/lib/runner.js b/lib/runner.js index a7785a0dc..a8f76e696 100644 --- a/lib/runner.js +++ b/lib/runner.js @@ -158,8 +158,10 @@ Runner.prototype.setupGlobals_ = function(browser_) { global.element = browser_.element; global.by = global.By = protractor.By; - // Enable sourcemap support for stack traces. - require('source-map-support').install(); + if (!this.config_.skipSourceMapSupport) { + // Enable sourcemap support for stack traces. + require('source-map-support').install(); + } // Required by dart2js machinery. // https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/sdk/lib/js/dart2js/js_dart2js.dart?spec=svn32943&r=32943#487 global.DartObject = function(o) { this.o = o; }; From 93abf539fdef1b1d2baec9092081b69ea5194ab5 Mon Sep 17 00:00:00 2001 From: Karthik Viswanath Date: Wed, 30 Sep 2015 12:22:06 -0400 Subject: [PATCH 007/678] feat(cucumber): Support dryrun feature of cucumber --- docs/referenceConf.js | 1 + lib/frameworks/cucumber.js | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/docs/referenceConf.js b/docs/referenceConf.js index b819d10bd..1290d0d17 100644 --- a/docs/referenceConf.js +++ b/docs/referenceConf.js @@ -311,6 +311,7 @@ exports.config = { tags: '@dev', // How to format features (default: progress) format: 'summary' + // Other options include `coffee`, `noSnippets`, and `dryRun` }, // See docs/plugins.md diff --git a/lib/frameworks/cucumber.js b/lib/frameworks/cucumber.js index 7044763d4..f8dde2398 100644 --- a/lib/frameworks/cucumber.js +++ b/lib/frameworks/cucumber.js @@ -65,6 +65,11 @@ exports.run = function(runner, specs) { if (runner.getConfig().cucumberOpts.noSnippets) { execOptions.push('--no-snippets'); } + + // Process Cucumber 'dry-run' param + if (runner.getConfig().cucumberOpts.dryRun) { + execOptions.push('-d'); + } } global.cucumber = Cucumber.Cli(execOptions); From 4aa512717320609618ce009a9be41577d43dc028 Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Wed, 4 Nov 2015 11:56:17 -0800 Subject: [PATCH 008/678] chore(docs): improve docs for `$` and `$$` Closes #2662 --- lib/element.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/element.js b/lib/element.js index b1a49f570..d936e0b79 100644 --- a/lib/element.js +++ b/lib/element.js @@ -973,6 +973,8 @@ ElementFinder.prototype.allowAnimations = function(value) { /** * Shortcut for querying the document directly with css. + * `element(by.css('.abc'))` is equivalent to `$('.abc')` + * * * @alias $(cssSelector) * @view @@ -998,6 +1000,7 @@ exports.build$ = build$; /** * Shortcut for querying the document directly with css. + * `element.all(by.css('.abc'))` is equivalent to `$$('.abc')` * * @alias $$(cssSelector) * @view From 97e6703eb0e7a5dffc1017d0a44f0dfeeb91f327 Mon Sep 17 00:00:00 2001 From: avdd Date: Mon, 9 Nov 2015 11:08:05 -0800 Subject: [PATCH 009/678] feat(protractor): Add protractor.prototype.restart --- lib/protractor.js | 6 ++++++ lib/runner.js | 18 +++++++++++------- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/lib/protractor.js b/lib/protractor.js index 040e61e00..6f2769257 100644 --- a/lib/protractor.js +++ b/lib/protractor.js @@ -267,6 +267,12 @@ Protractor.prototype.getProcessedConfig = null; */ Protractor.prototype.forkNewDriverInstance = null; +/** + * Restart the browser instance. + * + * Set by the runner. + */ +Protractor.prototype.restart = null; /** * Instead of using a single root element, search through all angular apps diff --git a/lib/runner.js b/lib/runner.js index a8f76e696..bb457c092 100644 --- a/lib/runner.js +++ b/lib/runner.js @@ -223,6 +223,16 @@ Runner.prototype.createBrowser = function(plugins) { } return newBrowser; }; + + browser_.restart = function() { + // Note: because tests are not paused at this point, any async + // calls here are not guaranteed to complete before the tests resume. + self.driverprovider_.quitDriver(browser_.driver); + // Copy mock modules, but do not navigate to previous URL. + browser_ = browser_.forkNewDriverInstance(false, true); + self.setupGlobals_(browser_); + }; + return browser_; }; @@ -304,14 +314,8 @@ Runner.prototype.run = function() { if (self.config_.restartBrowserBetweenTests) { var restartDriver = function() { - // Note: because tests are not paused at this point, any async - // calls here are not guaranteed to complete before the tests resume. - self.driverprovider_.quitDriver(browser_.driver); - // Copy mock modules, but do not navigate to previous URL. - browser_ = browser_.forkNewDriverInstance(false, true); - self.setupGlobals_(browser_); + browser_.restart(); }; - self.on('testPass', restartDriver); self.on('testFail', restartDriver); } From 7cba4ecf0f3915dfec33dbc04decd42857744b37 Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Tue, 21 Jul 2015 23:31:35 -0700 Subject: [PATCH 010/678] fix(ng-repeat): properly detect the end of an ng-repeat-start block This bug was introduced when by.exactRepeater was Discovered while investigating issue #2365 --- lib/clientsidescripts.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/clientsidescripts.js b/lib/clientsidescripts.js index 593a703d9..092022888 100644 --- a/lib/clientsidescripts.js +++ b/lib/clientsidescripts.js @@ -190,7 +190,7 @@ function findRepeaterRows(repeater, exact, index, using) { var elem = repeatElems[i]; var row = []; while (elem.nodeType != 8 || - !repeaterMatch(elem.nodeValue, repeater, exact)) { + !repeaterMatch(elem.nodeValue, repeater)) { if (elem.nodeType == 1) { row.push(elem); } @@ -237,7 +237,7 @@ function findAllRepeaterRows(repeater, exact, using) { if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) { var elem = repeatElems[i]; while (elem.nodeType != 8 || - !repeaterMatch(elem.nodeValue, repeater, exact)) { + !repeaterMatch(elem.nodeValue, repeater)) { if (elem.nodeType == 1) { rows.push(elem); } @@ -291,7 +291,7 @@ function findRepeaterElement(repeater, exact, index, binding, using, rootSelecto var elem = repeatElems[i]; var row = []; while (elem.nodeType != 8 || (elem.nodeValue && - !repeaterMatch(elem.nodeValue, repeater, exact))) { + !repeaterMatch(elem.nodeValue, repeater))) { if (elem.nodeType == 1) { row.push(elem); } @@ -390,7 +390,7 @@ function findRepeaterColumn(repeater, exact, binding, using, rootSelector) { var elem = repeatElems[i]; var row = []; while (elem.nodeType != 8 || (elem.nodeValue && - !repeaterMatch(elem.nodeValue, repeater, exact))) { + !repeaterMatch(elem.nodeValue, repeater))) { if (elem.nodeType == 1) { row.push(elem); } From 2b025f674211879abba64cea69c11e139335b08a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philippe=20L=C3=A9ger?= Date: Mon, 9 Nov 2015 15:52:52 -0500 Subject: [PATCH 011/678] chore(docs): Add example command to run more than one suite of tests --- docs/page-objects.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/page-objects.md b/docs/page-objects.md index c1c5d8fee..4524b97a8 100644 --- a/docs/page-objects.md +++ b/docs/page-objects.md @@ -90,3 +90,7 @@ exports.config = { From the command line, you can then easily switch between running one or the other suite of tests. This command will run only the homepage section of the tests: protractor protractor.conf.js --suite homepage + +Additionaly, you can run specific suites of tests with the command: + + protractor protractor.conf.js --suite homepage,search From 1fa8f5bf1199f59e89164b687dec2c83c770403c Mon Sep 17 00:00:00 2001 From: Sergii Stotskyi Date: Fri, 25 Sep 2015 01:50:19 +0300 Subject: [PATCH 012/678] chore(cleanup): Replaced Array#forEach with more suitable method: some, map, reduce, filter, etc --- bin/webdriver-manager | 7 ++--- lib/cli.js | 6 ++-- lib/element.js | 69 ++++++++++++++++--------------------------- lib/launcher.js | 26 +++++++--------- 4 files changed, 39 insertions(+), 69 deletions(-) diff --git a/bin/webdriver-manager b/bin/webdriver-manager index 05af9691c..1a5dea1e6 100755 --- a/bin/webdriver-manager +++ b/bin/webdriver-manager @@ -251,11 +251,8 @@ for (name in binaries) { bin = binaries[name]; bin.cdn = argv.alternate_cdn || bin.cdn; var exists = fs.existsSync(path.join(argv.out_dir, bin.filename)); - var outOfDateExists = false; - existingFiles.forEach(function(file) { - if (file.indexOf(bin.prefix) != -1 && file != bin.filename) { - outOfDateExists = true; - } + var outOfDateExists = existingFiles.some(function(file) { + return file.indexOf(bin.prefix) !== -1 && file !== bin.filename; }); bin.exists = exists; bin.outOfDateExists = outOfDateExists; diff --git a/lib/cli.js b/lib/cli.js index 5a17c8754..05ee94f75 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -108,11 +108,9 @@ if (argv.capabilities) { * @param {Array} list */ var processFilePatterns_ = function(list) { - var patterns = list.split(','); - patterns.forEach(function(spec, index, arr) { - arr[index] = path.resolve(process.cwd(), spec); + return list.split(',').map(function(spec) { + return path.resolve(process.cwd(), spec); }); - return patterns; }; if (argv.specs) { diff --git a/lib/element.js b/lib/element.js index d936e0b79..58af9b0ae 100644 --- a/lib/element.js +++ b/lib/element.js @@ -140,27 +140,21 @@ ElementArrayFinder.prototype.all = function(locator) { }); } else { return self.getWebElements().then(function(parentWebElements) { - var childrenPromiseList = []; // For each parent web element, find their children and construct a // list of Promise> - parentWebElements.forEach(function(parentWebElement) { - var childrenPromise = locator.findElementsOverride ? - locator.findElementsOverride(ptor.driver, parentWebElement, ptor.rootEl) : - parentWebElement.findElements(locator); - childrenPromiseList.push(childrenPromise); + var childrenPromiseList = parentWebElements.map(function(parentWebElement) { + return locator.findElementsOverride ? + locator.findElementsOverride(ptor.driver, parentWebElement, ptor.rootEl) : + parentWebElement.findElements(locator); }); - // Resolve the list of Promise> and merge into // a single list - return webdriver.promise.all(childrenPromiseList).then( - function(resolved) { - var childrenList = []; - resolved.forEach(function(resolvedE) { - childrenList = childrenList.concat(resolvedE); - }); - return childrenList; - }); + return webdriver.promise.all(childrenPromiseList).then(function(resolved) { + return resolved.reduce(function(childrenList, resolvedE) { + return childrenList.concat(resolvedE); + }, []); + }); }); } }; @@ -202,21 +196,16 @@ ElementArrayFinder.prototype.filter = function(filterFn) { var self = this; var getWebElements = function() { return self.getWebElements().then(function(parentWebElements) { - var list = []; - parentWebElements.forEach(function(parentWebElement, index) { + var list = parentWebElements.map(function(parentWebElement, index) { var elementFinder = ElementFinder.fromWebElement_(self.ptor_, parentWebElement, self.locator_); - list.push(filterFn(elementFinder, index)); + return filterFn(elementFinder, index); }); return webdriver.promise.all(list).then(function(resolvedList) { - var filteredElementList = []; - resolvedList.forEach(function(result, index) { - if (result) { - filteredElementList.push(parentWebElements[index]); - } + return parentWebElements.filter(function(parentWebElement, index) { + return resolvedList[index]; }); - return filteredElementList; }); }); }; @@ -391,11 +380,7 @@ ElementArrayFinder.prototype.locator = function() { ElementArrayFinder.prototype.applyAction_ = function(actionFn) { var callerError = new Error(); var actionResults = this.getWebElements().then(function(arr) { - var list = []; - arr.forEach(function(webElem) { - list.push(actionFn(webElem)); - }); - return webdriver.promise.all(list); + return webdriver.promise.all(arr.map(actionFn)); }).then(null, function(e) { e.stack = e.stack + '\n' + callerError.stack; throw e; @@ -412,11 +397,9 @@ ElementArrayFinder.prototype.applyAction_ = function(actionFn) { ElementArrayFinder.prototype.asElementFinders_ = function() { var self = this; return this.getWebElements().then(function(arr) { - var list = []; - arr.forEach(function(webElem) { - list.push(ElementFinder.fromWebElement_(self.ptor_, webElem, self.locator_)); + return arr.map(function(webElem) { + return ElementFinder.fromWebElement_(self.ptor_, webElem, self.locator_); }); - return list; }); }; @@ -513,11 +496,10 @@ ElementArrayFinder.prototype.each = function(fn) { */ ElementArrayFinder.prototype.map = function(mapFn) { return this.asElementFinders_().then(function(arr) { - var list = []; - arr.forEach(function(elementFinder, index) { + var list = arr.map(function(elementFinder, index) { var mapResult = mapFn(elementFinder, index); // All nested arrays and objects will also be fully resolved. - list.push(webdriver.promise.fullyResolved(mapResult)); + return webdriver.promise.fullyResolved(mapResult); }); return webdriver.promise.all(list); }); @@ -557,12 +539,11 @@ ElementArrayFinder.prototype.map = function(mapFn) { ElementArrayFinder.prototype.reduce = function(reduceFn, initialValue) { var valuePromise = webdriver.promise.fulfilled(initialValue); return this.asElementFinders_().then(function(arr) { - arr.forEach(function(elementFinder, index) { - valuePromise = valuePromise.then(function(value) { + return arr.reduce(function(valuePromise, elementFinder, index) { + return valuePromise.then(function(value) { return reduceFn(value, elementFinder, index, arr); }); - }); - return valuePromise; + }, valuePromise); }); }; @@ -650,7 +631,7 @@ ElementArrayFinder.prototype.allowAnimations = function(value) { * expect(input.getAttribute('value')).toBe('Foo123'); * * @constructor - * @extends {webdriver.WebElement} + * @extends {webdriver.WebElement} * @param {Protractor} ptor * @param {ElementArrayFinder} elementArrayFinder The ElementArrayFinder * that this is branched from. @@ -930,7 +911,7 @@ ElementFinder.prototype.isPresent = function() { /** * Same as ElementFinder.isPresent(), except this checks whether the element - * identified by the subLocator is present, rather than the current element + * identified by the subLocator is present, rather than the current element * finder. i.e. `element(by.css('#abc')).element(by.css('#def')).isPresent()` is * identical to `element(by.css('#abc')).isElementPresent(by.css('#def'))`. * @@ -942,8 +923,8 @@ ElementFinder.prototype.isPresent = function() { */ ElementFinder.prototype.isElementPresent = function(subLocator) { if (!subLocator) { - throw new Error('SubLocator is not supplied as a parameter to ' + - '`isElementPresent(subLocator)`. You are probably looking for the ' + + throw new Error('SubLocator is not supplied as a parameter to ' + + '`isElementPresent(subLocator)`. You are probably looking for the ' + 'function `isPresent()`.'); } return this.element(subLocator).isPresent(); diff --git a/lib/launcher.js b/lib/launcher.js index 9b5c42378..dfb4b723e 100644 --- a/lib/launcher.js +++ b/lib/launcher.js @@ -37,28 +37,21 @@ var taskResults_ = { }, totalSpecFailures: function() { - var specFailures = 0; - this.results_.forEach(function(result) { - specFailures += result.failedCount; - }); - return specFailures; + return this.results_.reduce(function(specFailures, result) { + return specFailures + result.failedCount; + }, 0); }, totalProcessFailures: function() { - var processFailures = 0; - this.results_.forEach(function(result) { - if (!result.failedCount && result.exitCode !== 0) { - processFailures += 1; - } - }); - return processFailures; + return this.results_.reduce(function(processFailures, result) { + return !result.failedCount && result.exitCode !== 0 ? processFailures + 1 : processFailures; + }, 0); }, saveResults: function(filepath) { - var jsonOutput = []; - this.results_.forEach(function(result) { - jsonOutput = jsonOutput.concat(result.specResults); - }); + var jsonOutput = this.results_.reduce(function(jsonOutput, result) { + return jsonOutput.concat(result.specResults); + }, []); var json = JSON.stringify(jsonOutput, null, ' '); var fs = require('fs'); @@ -267,3 +260,4 @@ var init = function(configFile, additionalConfig) { }; exports.init = init; + From 3bd582858ba17003486b4354e75cc27de8bd8ee1 Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Wed, 4 Nov 2015 17:19:54 -0800 Subject: [PATCH 013/678] chore(website): make version of testapp available at protractortest.org/testapp --- testapp/async/async.js | 10 +++++----- testapp/interaction/interaction.js | 6 +++--- testapp/lib/angular_version.js | 1 + testapp/scripts/web-server.js | 3 ++- website/gulpfile.js | 18 ++++++++++++++++++ website/testapp/chat | 0 website/testapp/fastTemplateUrl | 1 + website/testapp/fastcall | 1 + website/testapp/slowTemplateUrl | 1 + website/testapp/slowcall | 1 + 10 files changed, 33 insertions(+), 9 deletions(-) create mode 100644 testapp/lib/angular_version.js create mode 100644 website/testapp/chat create mode 100644 website/testapp/fastTemplateUrl create mode 100644 website/testapp/fastcall create mode 100644 website/testapp/slowTemplateUrl create mode 100644 website/testapp/slowcall diff --git a/testapp/async/async.js b/testapp/async/async.js index d35f933b8..2dc7ea5c1 100644 --- a/testapp/async/async.js +++ b/testapp/async/async.js @@ -6,11 +6,11 @@ function AsyncCtrl($scope, $http, $timeout, $location) { $scope.slowAngularTimeoutPromiseStatus = 'not started'; $scope.slowHttpPromiseStatus = 'not started'; $scope.routingChangeStatus = 'not started'; - $scope.templateUrl = '/fastTemplateUrl'; + $scope.templateUrl = 'fastTemplateUrl'; $scope.slowHttp = function() { $scope.slowHttpStatus = 'pending...'; - $http({method: 'GET', url: '/slowcall'}).success(function() { + $http({method: 'GET', url: 'slowcall'}).success(function() { $scope.slowHttpStatus = 'done'; }); }; @@ -50,7 +50,7 @@ function AsyncCtrl($scope, $http, $timeout, $location) { $scope.slowHttpPromise = function() { $scope.slowHttpPromiseStatus = 'pending...'; - $http({method: 'GET', url: '/slowcall'}).success(function() { + $http({method: 'GET', url: 'slowcall'}).success(function() { // intentionally empty }).then(function() { $scope.slowHttpPromiseStatus = 'done'; @@ -59,11 +59,11 @@ function AsyncCtrl($scope, $http, $timeout, $location) { $scope.routingChange = function() { $scope.routingChangeStatus = 'pending...'; - $location.url('/slowloader'); + $location.url('slowloader'); }; $scope.changeTemplateUrl = function() { - $scope.templateUrl = '/slowTemplateUrl'; + $scope.templateUrl = 'slowTemplateUrl'; }; } diff --git a/testapp/interaction/interaction.js b/testapp/interaction/interaction.js index 8bcf00d32..53870f74e 100644 --- a/testapp/interaction/interaction.js +++ b/testapp/interaction/interaction.js @@ -10,7 +10,7 @@ function InteractionCtrl($scope, $interval, $http) { }; var loadMessages = function() { - $http.get('/chat?q=chatMessages'). + $http.get('chat?q=chatMessages'). success(function(data) { $scope.messages = data ? data : []; }). @@ -28,7 +28,7 @@ function InteractionCtrl($scope, $interval, $http) { key: 'newChatMessage', value: msg }; - $http.post('/chat', data); + $http.post('chat', data); }; $scope.clearMessages = function() { @@ -37,7 +37,7 @@ function InteractionCtrl($scope, $interval, $http) { var data = { key: 'clearChatMessages' }; - $http.post('/chat', data); + $http.post('chat', data); }; $interval(function() { diff --git a/testapp/lib/angular_version.js b/testapp/lib/angular_version.js new file mode 100644 index 000000000..747185cb3 --- /dev/null +++ b/testapp/lib/angular_version.js @@ -0,0 +1 @@ +module.exports = '1.3.13'; diff --git a/testapp/scripts/web-server.js b/testapp/scripts/web-server.js index 0b47793f7..a05f912f0 100755 --- a/testapp/scripts/web-server.js +++ b/testapp/scripts/web-server.js @@ -9,11 +9,12 @@ var env = require('../../spec/environment.js'); var testApp = express(); var DEFAULT_PORT = process.env.HTTP_PORT || env.webServerDefaultPort; var testAppDir = path.resolve(__dirname, '..'); +var defaultAngular = require(path.join(testAppDir, 'lib/angular_version.js')); var argv = optimist.describe('port', 'port'). default('port', DEFAULT_PORT). describe('ngversion', 'version of AngularJS to use'). - default('ngversion', '1.3.13'). + default('ngversion', defaultAngular). argv; var angularDir = path.join(testAppDir, 'lib/angular_v' + argv.ngversion); diff --git a/website/gulpfile.js b/website/gulpfile.js index b7783e74a..2c1a3ca4f 100644 --- a/website/gulpfile.js +++ b/website/gulpfile.js @@ -125,6 +125,22 @@ gulp.task('markdown', function() { .pipe(gulp.dest('./build/partials')); }); +// Make version of testapp for github page +gulp.task('testapp', function() { + var stream = gulp.src('../testapp/**/*'). + pipe(gulp.dest('build/testapp')); + gulp.src('testapp/*'). + pipe(gulp.dest('build/testapp')); + var angular_version = require('../testapp/lib/angular_version.js'); + gulp.src('../testapp/lib/angular_v' + angular_version + '/**/*'). + pipe(gulp.dest('build/testapp/lib/angular')); + return stream; +}); + +gulp.task('cleanup_testapp', ['testapp'], function() { + del('build/testapp/lib/angular_v*'); +}); + // Start a server and watch for changes. gulp.task('liveReload', [ 'default', @@ -133,6 +149,8 @@ gulp.task('liveReload', [ ]); gulp.task('default', [ + 'testapp', + 'cleanup_testapp', 'dgeni', 'less', 'markdown', diff --git a/website/testapp/chat b/website/testapp/chat new file mode 100644 index 000000000..e69de29bb diff --git a/website/testapp/fastTemplateUrl b/website/testapp/fastTemplateUrl new file mode 100644 index 000000000..a6d60b593 --- /dev/null +++ b/website/testapp/fastTemplateUrl @@ -0,0 +1 @@ +fast template contents diff --git a/website/testapp/fastcall b/website/testapp/fastcall new file mode 100644 index 000000000..19f86f493 --- /dev/null +++ b/website/testapp/fastcall @@ -0,0 +1 @@ +done diff --git a/website/testapp/slowTemplateUrl b/website/testapp/slowTemplateUrl new file mode 100644 index 000000000..3e5cdd63c --- /dev/null +++ b/website/testapp/slowTemplateUrl @@ -0,0 +1 @@ +slow template contents diff --git a/website/testapp/slowcall b/website/testapp/slowcall new file mode 100644 index 000000000..a6cdeb69e --- /dev/null +++ b/website/testapp/slowcall @@ -0,0 +1 @@ +finally done From deba67dc0328ee0070915b24341ff5a2ba6d1bb6 Mon Sep 17 00:00:00 2001 From: Sergii Stotskyi Date: Fri, 2 Oct 2015 20:17:12 +0300 Subject: [PATCH 014/678] chore(element.js): Moved webdriver element specific methods into prototype --- lib/element.js | 38 +++++++++++++++++--------------------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/lib/element.js b/lib/element.js index 58af9b0ae..e2666403e 100644 --- a/lib/element.js +++ b/lib/element.js @@ -65,21 +65,20 @@ var ElementArrayFinder = function(ptor, getWebElements, locator, opt_actionResul this.getWebElements = getWebElements || null; this.actionResults_ = opt_actionResults; this.locator_ = locator; - - var self = this; - WEB_ELEMENT_FUNCTIONS.forEach(function(fnName) { - self[fnName] = function() { - var args = arguments; - var actionFn = function(webElem) { - return webElem[fnName].apply(webElem, args); - }; - return self.applyAction_(actionFn); - }; - }); }; exports.ElementArrayFinder = ElementArrayFinder; +WEB_ELEMENT_FUNCTIONS.forEach(function(fnName) { + ElementArrayFinder.prototype[fnName] = function() { + var args = arguments; + var actionFn = function(webElem) { + return webElem[fnName].apply(webElem, args); + }; + return this.applyAction_(actionFn); + }; +}); + /** * Create a shallow copy of ElementArrayFinder. * @@ -692,16 +691,6 @@ var ElementFinder = function(ptor, elementArrayFinder) { this.elementArrayFinder_ = new ElementArrayFinder( this.ptor_, getWebElements, elementArrayFinder.locator_, elementArrayFinder.actionResults_); - - // Decorate ElementFinder with webdriver functions. Simply calls the - // underlying elementArrayFinder to perform these functions. - var self = this; - WEB_ELEMENT_FUNCTIONS.forEach(function(fnName) { - self[fnName] = function() { - return self.elementArrayFinder_[fnName]. - apply(self.elementArrayFinder_, arguments).toElementFinder_(); - }; - }); }; exports.ElementFinder = ElementFinder; @@ -714,6 +703,13 @@ ElementFinder.fromWebElement_ = function(ptor, webElem, locator) { toElementFinder_(); }; +WEB_ELEMENT_FUNCTIONS.forEach(function(fnName) { + ElementFinder.prototype[fnName] = function() { + return this.elementArrayFinder_[fnName]. + apply(this.elementArrayFinder_, arguments).toElementFinder_(); + }; +}); + /** * Create a shallow copy of ElementFinder. * From a40a4ba2a509bc762f1f5937454fdbf074405f07 Mon Sep 17 00:00:00 2001 From: Sergii Stotskyi Date: Wed, 4 Nov 2015 18:28:15 +0200 Subject: [PATCH 015/678] feat(ElementArrayFinder#get): Implemented ability to pass promise as index to ElementArrayFinder#get --- lib/element.js | 8 +++++--- scripts/test.js | 6 +++--- spec/basic/elements_spec.js | 13 ++++++++++--- 3 files changed, 18 insertions(+), 9 deletions(-) diff --git a/lib/element.js b/lib/element.js index e2666403e..4716ed9ad 100644 --- a/lib/element.js +++ b/lib/element.js @@ -229,14 +229,16 @@ ElementArrayFinder.prototype.filter = function(filterFn) { * expect(list.get(0).getText()).toBe('First'); * expect(list.get(1).getText()).toBe('Second'); * - * @param {number} index Element index. + * @param {number|webdriver.promise.Promise} index Element index. * @return {ElementFinder} finder representing element at the given index. */ ElementArrayFinder.prototype.get = function(index) { var self = this; var getWebElements = function() { - return self.getWebElements().then(function(parentWebElements) { - var i = index; + return webdriver.promise.all([ index, self.getWebElements() ]).then(function(results) { + var i = results[0]; + var parentWebElements = results[1]; + if (i < 0) { // wrap negative indices i = parentWebElements.length + i; diff --git a/scripts/test.js b/scripts/test.js index 1027810c4..d056ac8ce 100755 --- a/scripts/test.js +++ b/scripts/test.js @@ -119,9 +119,9 @@ executor.addCommandlineTest('node lib/cli.js spec/errorTest/slowHttpAndTimeoutCo .expectExitCode(1) .expectErrors([ {message: 'The following tasks were pending[\\s\\S]*\\$http: \/slowcall'}, - {message: 'The following tasks were pending[\\s\\S]*' + - '\\$timeout: function \\(\\) {[\\s\\S]*' + - '\\$scope\\.slowAngularTimeoutStatus = \'done\';[\\s\\S]' + + {message: 'The following tasks were pending[\\s\\S]*' + + '\\$timeout: function \\(\\) {[\\s\\S]*' + + '\\$scope\\.slowAngularTimeoutStatus = \'done\';[\\s\\S]' + '*}'} ]); diff --git a/spec/basic/elements_spec.js b/spec/basic/elements_spec.js index b5cce45fe..6ac9c823d 100644 --- a/spec/basic/elements_spec.js +++ b/spec/basic/elements_spec.js @@ -1,5 +1,3 @@ -var util = require('util'); - describe('ElementFinder', function() { beforeEach(function() { // Clear everything between each test. @@ -346,7 +344,7 @@ describe('ElementArrayFinder', function() { expect(element.all(by.binding('doesnotexist')).count()).toEqual(0); }); - it('should return not present when an element disappears within an array', + it('should return not present when an element disappears within an array', function() { browser.get('index.html#/form'); element.all(by.model('color')).then(function(elements) { @@ -367,6 +365,15 @@ describe('ElementArrayFinder', function() { expect(colorList.get(2).getAttribute('value')).toEqual('red'); }); + it('should get an element from an array by promise index', function() { + var colorList = element.all(by.model('color')); + var index = protractor.promise.fulfilled(1); + + browser.get('index.html#/form'); + + expect(colorList.get(index).getAttribute('value')).toEqual('green'); + }); + it('should get an element from an array using negative indices', function() { var colorList = element.all(by.model('color')); From 586d634bcd306a3226fd4c55bef43155294bad4e Mon Sep 17 00:00:00 2001 From: Julie Ralph Date: Thu, 9 Apr 2015 16:52:08 -0700 Subject: [PATCH 016/678] tests(element): add test for grabbing subelements within each --- spec/basic/elements_spec.js | 15 +++++++++++++++ testapp/form/form.html | 14 ++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/spec/basic/elements_spec.js b/spec/basic/elements_spec.js index 6ac9c823d..c433cac16 100644 --- a/spec/basic/elements_spec.js +++ b/spec/basic/elements_spec.js @@ -407,6 +407,21 @@ describe('ElementArrayFinder', function() { }); }); + it('should allow accessing subelements from within each', function() { + browser.get('index.html#/form'); + var rows = element.all(by.css('.rowlike')); + + rows.each(function(row) { + var input = row.element(by.css('.input')); + expect(input.getAttribute('value')).toEqual('10'); + }); + + rows.each(function(row) { + var input = row.element(by.css('input')); + expect(input.getAttribute('value')).toEqual('10'); + }); + }); + it('should keep a reference to the array original locator', function() { var byCss = by.css('#animals ul li'); var byModel = by.model('color'); diff --git a/testapp/form/form.html b/testapp/form/form.html index 376c797a9..0be23c437 100644 --- a/testapp/form/form.html +++ b/testapp/form/form.html @@ -86,6 +86,20 @@

    Inner text

    +
    +

    Inputs

    + + + + + + + + + +
    +
    +

    Transformed text

    Uppercase
    From 827554148d2af8e3dc1fdeb4481bfb906a98d116 Mon Sep 17 00:00:00 2001 From: Konrad Garus Date: Thu, 15 Oct 2015 20:43:21 +0200 Subject: [PATCH 017/678] docs(onPrepare): onPrepare can return a promise --- docs/referenceConf.js | 7 ++++++- docs/system-setup.md | 6 +++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/referenceConf.js b/docs/referenceConf.js index 1290d0d17..75e1a54f5 100644 --- a/docs/referenceConf.js +++ b/docs/referenceConf.js @@ -197,6 +197,11 @@ exports.config = { // capability. // You can specify a file containing code to run by setting onPrepare to // the filename string. + // onPrepare can optionally return a promise, which Protractor will wait for + // before continuing execution. This can be used if the preparation involves + // any asynchronous calls, e.g. interacting with the browser. Otherwise + // Protractor cannot guarantee order of execution and may start the tests + // before preparation finishes. onPrepare: function() { // At this point, global variable 'protractor' object will be set up, and // globals from the test framework will be available. For example, if you @@ -206,7 +211,7 @@ exports.config = { // // If you need access back to the current configuration object, // use a pattern like the following: - // browser.getProcessedConfig().then(function(config) { + // return browser.getProcessedConfig().then(function(config) { // // config.capabilities is the CURRENT capability being run, if // // you are using multiCapabilities. // console.log('Executing capability', config.capabilities); diff --git a/docs/system-setup.md b/docs/system-setup.md index 93f4da6ea..4e565bf78 100644 --- a/docs/system-setup.md +++ b/docs/system-setup.md @@ -8,4 +8,8 @@ There are a couple of things to watch out for! **If your page uses `$timeout` for polling** Protractor will not be able to tell when your page is ready. Consider using `$interval` instead of `$timeout`. -If you need to do global preparation for your tests (for example, logging in), you can put this into the config in the `onPrepare` property. This property can be either a function or a filename. If a filename, Protractor will load that file with Node.js and run its contents. See the [login tests](https://github.com/angular/protractor/blob/master/spec/withLoginConf.js) for an example. +**If you need to do global preparation for your tests** (for example, logging in), you can put this into the config in the `onPrepare` property. This property can be either a function or a filename. If a filename, Protractor will load that file with Node.js and run its contents. + +`onPrepare` can optionally return a promise, which Protractor will wait for before continuing execution. This can be used if the preparation involves any asynchronous calls, e.g. interacting with the browser. Otherwise Protractor cannot guarantee order of execution and may start the tests before preparation finishes. + +See the [login tests](https://github.com/angular/protractor/blob/master/spec/withLoginConf.js) for an example. From f0e2195f4dda463943b23e56f03b208b2f6a4ad1 Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Sun, 8 Nov 2015 22:51:02 -0800 Subject: [PATCH 018/678] chore(npm/github): update ignore files --- .gitignore | 3 +-- .npmignore | 10 ++++++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index 64b04c8f6..a1b39709a 100644 --- a/.gitignore +++ b/.gitignore @@ -7,8 +7,7 @@ website/docgen/build/ chromedriver.log libpeerconnection.log -changes.sh xmloutput* npm-debug.log -*.swp \ No newline at end of file +*.swp diff --git a/.npmignore b/.npmignore index e2d829d86..93e651f1f 100644 --- a/.npmignore +++ b/.npmignore @@ -1,17 +1,19 @@ debugging/ +docs/ +scripts/ spec/ stress/ selenium/ -debugging/ -testapp/inbrowsertest/ +testapp/ website/ +.gitattributes +.gitignore +.jshintrc .npmignore .travis.yml -changes.sh chromedriver.log libpeerconnection.log npm-debug.log -new.txt xmloutput* release.md From 91053684144563eb24d85a637d0b7977adb146ea Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Fri, 25 Sep 2015 05:31:28 -0700 Subject: [PATCH 019/678] chore(website): Fix parsing of summaries in function list and return descriptions Closing #2486 and #2672 --- website/js/api-controller.js | 42 +++++++++++------------- website/js/directives.js | 5 +++ website/js/shared.js | 25 ++++++++++++++ website/partials/api.html | 2 +- website/partials/ptor-function-list.html | 2 +- website/test/unit/api-controller-spec.js | 20 +++++++++-- 6 files changed, 70 insertions(+), 26 deletions(-) create mode 100644 website/js/shared.js diff --git a/website/js/api-controller.js b/website/js/api-controller.js index befefa233..761d80417 100644 --- a/website/js/api-controller.js +++ b/website/js/api-controller.js @@ -62,25 +62,8 @@ $anchorScroll(); }; - /** - * Use the $sce service to trust the html rendered in the view. - * @param html - */ $scope.trust = function(html) { - if (!html) { - return; - } - - // Does it come with a type? Types come escaped as [description](theType). - var match; - while (match = html.match(/(\[(.*?)\]\((.*?)\))/)) { - var link = '' + match[2] + ''; - html = html.replace(match[1], link); - } - - return $sce.trustAsHtml(html); + return trustHTML($sce, html); }; }; @@ -153,8 +136,25 @@ // Add short description. if (item.description) { - item.shortDescription = - item.description.substring(0., item.description.indexOf('.') + 1); + // Find the correct portion of the description + + // The following parsing is OK most of the time + var sentenceEnd = item.description.search(/\.\s|\.$/) + 1 || Infinity; + var paragraphEnd = item.description.indexOf('

    ') + 4; + if (paragraphEnd == 3) { + paragraphEnd = Infinity + } + var shortDescription = item.description.substring(0, Math.min( + item.description.length, sentenceEnd, paragraphEnd)).trim(); + + // Remove

    tags + if (shortDescription.substr(0,3) == '

    ') { + shortDescription = shortDescription.substr(3); + if (shortDescription.substr(-4) == '

    ') { + shortDescription = shortDescription.substr(0, shortDescription.length - 4); + } + } + item.shortDescription = shortDescription; } }); @@ -201,7 +201,6 @@ var addItemToList = function(item, depth) { if (item.inList) { - console.log(item.name); return; } item.treeClasses = 'depth-' + depth; @@ -217,7 +216,6 @@ }); } if (item.extends) { - console.log(item.base.name); var parent = self.itemsByName[item.base.name]; if (parent != null) { addItemToList(parent, depth + 1); diff --git a/website/js/directives.js b/website/js/directives.js index 2f282c173..d20f8e8c0 100644 --- a/website/js/directives.js +++ b/website/js/directives.js @@ -56,6 +56,11 @@ scope: { list: '=ptorFunctionList' }, + controller: function($scope, $sce) { + $scope.trust = function(html) { + return trustHTML($sce, html); + }; + }, templateUrl: 'partials/ptor-function-list.html' }; }); diff --git a/website/js/shared.js b/website/js/shared.js new file mode 100644 index 000000000..750df7be0 --- /dev/null +++ b/website/js/shared.js @@ -0,0 +1,25 @@ +/* + * Use the $sce service to trust the html rendered in the view. + * Also parse links + * + * @param $sce The $sce service from Angular + * @param {String} html The HTML to trust + * @return {*} An object that can be passed to $sce.getTrustedHtml(value) to + * obtain the original value + */ +function trustHTML($sce, html) { + if (!html) { + return; + } + + // Does it come with a type? Types come escaped as [description](theType). + var match; + while (match = html.match(/(\[(.*?)\]\((.*?)\))/)) { + var link = '' + match[2] + ''; + html = html.replace(match[1], link); + } + + return $sce.trustAsHtml(html); +} diff --git a/website/partials/api.html b/website/partials/api.html index 0608348c1..a8414aabd 100644 --- a/website/partials/api.html +++ b/website/partials/api.html @@ -149,7 +149,7 @@

    Returns

    - {{currentItem.returns.description}} + diff --git a/website/partials/ptor-function-list.html b/website/partials/ptor-function-list.html index 61399ab90..d5223f80b 100644 --- a/website/partials/ptor-function-list.html +++ b/website/partials/ptor-function-list.html @@ -14,7 +14,7 @@ ng-bind="item.displayName"> - + diff --git a/website/test/unit/api-controller-spec.js b/website/test/unit/api-controller-spec.js index 6b6e35fc3..f81dd1a39 100644 --- a/website/test/unit/api-controller-spec.js +++ b/website/test/unit/api-controller-spec.js @@ -1,15 +1,16 @@ 'use strict'; describe('ApiCtrl', function() { - var $controller_, $httpBackend, $location, $rootScope_, ctrl, scope; + var $controller_, $httpBackend, $location, $sce, $rootScope_, ctrl, scope; beforeEach(module('protractorApp')); beforeEach(inject( - function($controller, $rootScope, _$httpBackend_, _$location_) { + function($controller, $rootScope, _$httpBackend_, _$location_, _$sce_) { $controller_ = $controller; $httpBackend = _$httpBackend_; $location = _$location_; + $sce = _$sce_; $rootScope_ = $rootScope; })); @@ -205,4 +206,19 @@ describe('ApiCtrl', function() { expect(item.base.items.length).toBe(1); }); }); + + describe('trustHTML', function() { + it('should reject falsy html', function() { + expect(trustHTML($sce, false)).toBe(undefined); + }); + + it('should run truster', function() { + expect($sce.getTrustedHtml(trustHTML($sce, 'html'))).toBe('html'); + }); + + it('should expand links', function() { + expect($sce.getTrustedHtml(trustHTML($sce, '[description](type)'))).toBe( + 'description'); + }); + }); }); From 000f11935918a7c8f805e7f37a88df14e3f38a76 Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Fri, 2 Oct 2015 13:04:25 -0700 Subject: [PATCH 020/678] chore(website): fix links to github files Closes #2545 --- website/gulpfile.js | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/website/gulpfile.js b/website/gulpfile.js index 2c1a3ca4f..18b793250 100644 --- a/website/gulpfile.js +++ b/website/gulpfile.js @@ -97,21 +97,27 @@ gulp.task('markdown', function() { gulp.src(['../docs/*.md', '!../docs/api.md']) // Parse markdown. .pipe(markdown()) - // Fix in-page hash paths. - .pipe(replace(/"#([^ ]*?)"/g, '#{{path}}#$1')) - // Fix md urls. - .pipe(replace(/"(?:\/docs\/)?([\w\-]+)\.md/g, '"#/$1')) - // Fix png urls. - .pipe(replace(/"(?:\/docs\/)?([\w\-]+\.png)"/g, '"img/$1"')) - // Fix urls to reference js & feature files. + // Fix urls which reference files only on github. .pipe(replace( - /"(?:\/([\-\.\w\/]+)\/)?(\w+\.(?:js|feature)(?:#\w*)?)"/g, + /"(?:\/([\-\.\w\/]+)\/)?(\w+\.\w+(?:#.*)?)"/g, function(match, path, file) { + var ext = file.match(/\w+\.(\w+)(?:#.*)?/)[1]; + // Don't process .md and .png files which are on the website + if (((ext == 'md') || (ext == 'png')) && + !(path && ((path.substr(0,2) == '..') || (path[0] == '/')))) { + return match; + } path = path || 'docs'; return '"https://github.com/angular/protractor/blob/master/' + path + '/' + file + '"'; } )) + // Fix in-page hash paths. + .pipe(replace(/"#([^ ]*?)"/g, '#{{path}}#$1')) + // Fix md urls. + .pipe(replace(/"(?:\/docs\/)?([\w\-]+)\.md/g, '"#/$1')) + // Fix png urls. + .pipe(replace(/"(?:\/docs\/)?([\w\-]+\.png)"/g, '"img/$1"')) // Add anchor links .pipe(replace(/

    (.*?)<\/h2>/g, '

    ')) From 7015010188dfb70c1e49e4f2eae19d5ba1126b34 Mon Sep 17 00:00:00 2001 From: Harish Ved Date: Fri, 9 Oct 2015 15:24:30 +0530 Subject: [PATCH 021/678] feat(driver providers): Add BrowserStack support. Also added BrowserStack to CI Closes #1013 --- .travis.yml | 11 +++- docs/referenceConf.js | 20 +++++-- docs/server-setup.md | 20 +++++-- lib/driverProviders/browserstack.js | 91 +++++++++++++++++++++++++++++ lib/runner.js | 2 + scripts/browserstack_local_setup.sh | 3 + scripts/test_on_travis.sh | 12 ++++ scripts/testonsauce.sh | 9 --- scripts/travis_setup.sh | 6 ++ spec/ciBStackConf.js | 36 ++++++++++++ 10 files changed, 190 insertions(+), 20 deletions(-) create mode 100644 lib/driverProviders/browserstack.js create mode 100755 scripts/browserstack_local_setup.sh create mode 100755 scripts/test_on_travis.sh delete mode 100755 scripts/testonsauce.sh create mode 100755 scripts/travis_setup.sh create mode 100644 spec/ciBStackConf.js diff --git a/.travis.yml b/.travis.yml index 8fa32e2c8..abd7a1aa0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,29 +8,34 @@ env: global: - SAUCE_USERNAME=angular-ci - SAUCE_ACCESS_KEY=9b988f434ff8-fbca-8aa4-4ae3-35442987 + - BROWSER_STACK_USERNAME=angularteam1 + - BROWSER_STACK_ACCESS_KEY=BWCd4SynLzdDcv8xtzsB - LOGS_DIR=/tmp/protractor-build/logs - BROWSER_PROVIDER_READY_FILE=/tmp/sauce-connect-ready matrix: - JOB=full - JOB=smoke + - JOB=bstack matrix: allow_failures: - env: "JOB=smoke" + - env: "JOB=bstack" exclude: - env: JOB=smoke node_js: "5" + - env: JOB=bstack + node_js: "5" before_script: - npm run pretest - mkdir -p $LOGS_DIR - - ./scripts/sauce_connect_setup.sh - - ./scripts/wait_for_browser_provider.sh + - ./scripts/travis_setup.sh script: - ./scripts/testserver.sh - - ./scripts/testonsauce.sh + - ./scripts/test_on_travis.sh after_script: - ./scripts/print_logs.sh diff --git a/docs/referenceConf.js b/docs/referenceConf.js index 75e1a54f5..64d130846 100644 --- a/docs/referenceConf.js +++ b/docs/referenceConf.js @@ -14,13 +14,14 @@ exports.config = { // // Protractor needs to know how to connect to Drivers for the browsers // it is testing on. This is usually done through a Selenium Server. - // There are four options - specify one of the following: + // There are five options - specify one of the following: // // 1. seleniumServerJar - to start a standalone Selenium Server locally. // 2. seleniumAddress - to connect to a Selenium Server which is already // running. // 3. sauceUser/sauceKey - to use remote Selenium Servers via Sauce Labs. - // 4. directConnect - to connect directly to the browser Drivers. + // 4. browserstackUser/browserstackKey - to use remote Selenium Servers via BrowserStack. + // 5. directConnect - to connect directly to the browser Drivers. // This option is only available for Firefox and Chrome. // ---- 1. To start a standalone Selenium Server locally --------------------- @@ -63,7 +64,13 @@ exports.config = { // ondemand.saucelabs.com:80/wd/hub sauceSeleniumAddress: null, - // ---- 4. To connect directly to Drivers ------------------------------------ + // ---- 4. To use remote browsers via BrowserStack --------------------------- + // If browserstackUser and browserstackKey are specified, seleniumServerJar will be ignored. + // The tests will be run remotely using BrowserStack. + browserstackUser: null, + browserstackKey: null, + + // ---- 5. To connect directly to Drivers ------------------------------------ // Boolean. If true, Protractor will connect directly to the browser Drivers // at the locations specified by chromeDriver and firefoxPath. Only Chrome // and Firefox are supported for direct connect. @@ -110,7 +117,7 @@ exports.config = { // Name of the process executing this capability. Not used directly by // protractor or the browser, but instead pass directly to third parties - // like SauceLabs as the name of the job running this test + // like BrowserStack and SauceLabs as the name of the job running this test name: 'Unnamed Job', // User defined name for the capability that will display in the results log @@ -139,6 +146,11 @@ exports.config = { // Optional: override global seleniumAddress on this capability only. seleniumAddress: null + + // Optional: Additional third-party specific capabilities can be + // specified here. + // For a list of BrowserStack specific capabilities, visit + // https://www.browserstack.com/automate/capabilities }, // If you would like to run more than one instance of WebDriver on the same diff --git a/docs/server-setup.md b/docs/server-setup.md index 84cd6bf06..ffac30823 100644 --- a/docs/server-setup.md +++ b/docs/server-setup.md @@ -55,21 +55,33 @@ To connect to a running instance of a standalone Selenium Server, set this optio - `seleniumAddress` - Connect to a running instance of a standalone Selenium Server. The address will be a URL. -Please note that if you set seleniumAddress, the settings for `seleniumServerJar`, `seleniumPort`, `seleniumArgs`, `sauceUser` and `sauceKey` will be ignored. +Please note that if you set seleniumAddress, the settings for `seleniumServerJar`, `seleniumPort`, `seleniumArgs`, `browserstackUser`, `browserstackKey`, `sauceUser` and `sauceKey` will be ignored. Remote Selenium Server ---------------------- -To run your tests against a remote Selenium Server, you will need an account with a service that hosts the server (and the browser drivers). Protractor has built in support for [Sauce Labs](http://www.saucelabs.com). +To run your tests against a remote Selenium Server, you will need an account with a service that hosts the server (and the browser drivers). Protractor has built in support for [BrowserStack](https://www.browserstack.com) and [Sauce Labs](http://www.saucelabs.com). + +**Using BrowserStack as remote Selenium Server** + +In your config file, set these options: + - `browserstackUser` - The username for your BrowserStack account. + - `browserstackKey` - The key for your BrowserStack account. + +Please note that if you set `browserstackUser` and `browserstackKey`, the settings for `seleniumServerJar`, `seleniumPort`, `seleniumArgs`, `sauceUser` and `sauceKey` will be ignored. + +You can optionally set the [`name` property](referenceConf.js#L121) in a capability in order to give the jobs a name on the server. Otherwise they will just be allotted a random hash. + +**Using Sauce Labs as remote Selenium Server** In your config file, set these options: - `sauceUser` - The username for your Sauce Labs account. - `sauceKey` - The key for your Sauce Labs account. -Please note that if you set `sauceUser` and `sauceKey`, the settings for `seleniumServerJar`, `seleniumPort` and `seleniumArgs` will be ignored. +Please note that if you set `sauceUser` and `sauceKey`, the settings for `seleniumServerJar`, `seleniumPort`, `seleniumArgs`, `browserstackUser` and `browserstackKey` will be ignored. -You can optionally set the [`name` property](referenceConf.js#L113) in a capability in order to give the jobs a name on the server. Otherwise they will just be called `Unnamed Job`. +You can optionally set the [`name` property](referenceConf.js#L121) in a capability in order to give the jobs a name on the server. Otherwise they will just be called `Unnamed Job`. Connecting Directly to Browser Drivers diff --git a/lib/driverProviders/browserstack.js b/lib/driverProviders/browserstack.js new file mode 100644 index 000000000..1cfc70d46 --- /dev/null +++ b/lib/driverProviders/browserstack.js @@ -0,0 +1,91 @@ +/* + * This is an implementation of the Browserstack Driver Provider. + * It is responsible for setting up the account object, tearing + * it down, and setting up the driver correctly. + */ + +var util = require('util'), + log = require('../logger.js'), + request = require('request'), + q = require('q'), + DriverProvider = require('./driverProvider'); + + +var BrowserStackDriverProvider = function(config) { + DriverProvider.call(this, config); +}; +util.inherits(BrowserStackDriverProvider, DriverProvider); + + +/** + * Hook to update the BrowserStack job status. + * @public + * @param {Object} update + * @return {q.promise} A promise that will resolve when the update is complete. + */ +BrowserStackDriverProvider.prototype.updateJob = function(update) { + + var self = this; + var deferredArray = this.drivers_.map(function(driver) { + var deferred = q.defer(); + driver.getSession().then(function(session) { + var jobStatus = update.passed ? 'completed' : 'error'; + log.puts('BrowserStack results available at ' + + 'https://www.browserstack.com/automate'); + request({ + url: 'https://www.browserstack.com/automate/sessions/' + + session.getId() + '.json', + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'Basic ' + new Buffer(self.config_.browserstackUser + + ':' + self.config_.browserstackKey).toString('base64') + }, + method: 'PUT', + form: { + 'status': jobStatus + } + }, function(error){ + if (error) { + throw new Error( + 'Error updating BrowserStack pass/fail status: ' + + util.inspect(error) + ); + } + }); + deferred.resolve(); + }); + return deferred.promise; + }); + return q.all(deferredArray); +}; + +/** + * Configure and launch (if applicable) the object's environment. + * @public + * @return {q.promise} A promise which will resolve when the environment is + * ready to test. + */ +BrowserStackDriverProvider.prototype.setupEnv = function() { + var deferred = q.defer(); + this.config_.capabilities['browserstack.user'] = + this.config_.browserstackUser; + this.config_.capabilities['browserstack.key'] = this.config_.browserstackKey; + this.config_.seleniumAddress = 'http://hub.browserstack.com/wd/hub'; + + // Append filename to capabilities.name so that it's easier to identify tests. + if (this.config_.capabilities.name && + this.config_.capabilities.shardTestFiles) { + this.config_.capabilities.name += ( + ':' + this.config_.specs.toString().replace(/^.*[\\\/]/, '')); + } + + log.puts('Using BrowserStack selenium server at ' + + this.config_.seleniumAddress); + deferred.resolve(); + return deferred.promise; +}; + +// new instance w/ each include +module.exports = function(config) { + return new BrowserStackDriverProvider(config); +}; diff --git a/lib/runner.js b/lib/runner.js index bb457c092..0965689f0 100644 --- a/lib/runner.js +++ b/lib/runner.js @@ -94,6 +94,8 @@ Runner.prototype.loadDriverProvider_ = function() { runnerPath = './driverProviders/direct'; } else if (this.config_.seleniumAddress) { runnerPath = './driverProviders/hosted'; + } else if (this.config_.browserstackUser && this.config_.browserstackKey) { + runnerPath = './driverProviders/browserstack'; } else if (this.config_.sauceUser && this.config_.sauceKey) { runnerPath = './driverProviders/sauce'; } else if (this.config_.seleniumServerJar) { diff --git a/scripts/browserstack_local_setup.sh b/scripts/browserstack_local_setup.sh new file mode 100755 index 000000000..205ca29d2 --- /dev/null +++ b/scripts/browserstack_local_setup.sh @@ -0,0 +1,3 @@ +curl -sO https://www.browserstack.com/browserstack-local/BrowserStackLocal-linux-x64.zip +unzip BrowserStackLocal-linux-x64.zip -d local +./local/BrowserStackLocal ` echo $BROWSER_STACK_ACCESS_KEY | rev ` & diff --git a/scripts/test_on_travis.sh b/scripts/test_on_travis.sh new file mode 100755 index 000000000..c5e0cc51e --- /dev/null +++ b/scripts/test_on_travis.sh @@ -0,0 +1,12 @@ +SAUCE_ACCESS_KEY=`echo $SAUCE_ACCESS_KEY | rev` +BROWSER_STACK_ACCESS_KEY=`echo $BROWSER_STACK_ACCESS_KEY | rev` + +if [ $JOB = "smoke" ]; then + node bin/protractor spec/ciSmokeConf.js +elif [ $JOB = "full" ]; then + node bin/protractor spec/ciFullConf.js +elif [ $JOB = "bstack" ]; then + node bin/protractor spec/ciBStackConf.js +else + echo "Unknown job type. Please set JOB=smoke, JOB=full, or JOB=bstack" +fi diff --git a/scripts/testonsauce.sh b/scripts/testonsauce.sh deleted file mode 100755 index 026a8ca45..000000000 --- a/scripts/testonsauce.sh +++ /dev/null @@ -1,9 +0,0 @@ -SAUCE_ACCESS_KEY=`echo $SAUCE_ACCESS_KEY | rev` - -if [ $JOB = "smoke" ]; then - node bin/protractor spec/ciSmokeConf.js -elif [ $JOB = "full" ]; then - node bin/protractor spec/ciFullConf.js -else - echo "Unknown job type. Please set JOB=smoke or JOB=full" -fi diff --git a/scripts/travis_setup.sh b/scripts/travis_setup.sh new file mode 100755 index 000000000..9a97b97d6 --- /dev/null +++ b/scripts/travis_setup.sh @@ -0,0 +1,6 @@ +if [ $JOB == "bstack" ]; then + ./scripts/browserstack_local_setup.sh +else + ./scripts/sauce_connect_setup.sh + ./scripts/wait_for_browser_provider.sh +fi diff --git a/spec/ciBStackConf.js b/spec/ciBStackConf.js new file mode 100644 index 000000000..407fbbe56 --- /dev/null +++ b/spec/ciBStackConf.js @@ -0,0 +1,36 @@ +var env = require('./environment.js'); + +// The main suite of Protractor tests. +exports.config = { + browserstackUser: process.env.BROWSER_STACK_USERNAME, + browserstackKey: process.env.BROWSER_STACK_ACCESS_KEY, + + framework: 'jasmine', + + // Spec patterns are relative to this directory. + specs: [ + 'basic/*_spec.js' + ], + + // Exclude patterns are relative to this directory. + exclude: [ + 'basic/exclude*.js' + ], + + capabilities: env.capabilities, + + baseUrl: env.baseUrl, + + jasmineNodeOpts: { + isVerbose: true, + realtimeFailure: true + }, + + params: { + login: { + user: 'Jane', + password: '1234' + } + } +}; +exports.config.capabilities['browserstack.local'] = true; From ac1e21e7e09a773de981bf9e70b0fcd489d17a83 Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Sun, 8 Nov 2015 15:49:19 -0800 Subject: [PATCH 022/678] chore(plugins): Split first party plugins into seperate repos --- docs/plugins.md | 166 +- plugins/README.md | 1 - plugins/accessibility/index.js | 232 -- plugins/accessibility/spec/fail_spec.js | 5 - plugins/accessibility/spec/failureConfig.js | 21 - plugins/accessibility/spec/successConfig.js | 19 - plugins/accessibility/spec/success_spec.js | 9 - plugins/console/index.js | 117 - plugins/console/spec/consoleFailConfig.js | 13 - .../console/spec/consoleFailErrorConfig.js | 13 - .../console/spec/consoleFailFilterConfig.js | 17 - .../console/spec/consoleFailLogWarnings.js | 14 - .../console/spec/consoleFailWarningConfig.js | 13 - plugins/console/spec/consolePassConfig.js | 13 - .../console/spec/consolePassLogWarnings.js | 14 - plugins/console/spec/fail_error_spec.js | 15 - plugins/console/spec/fail_spec.js | 21 - plugins/console/spec/fail_warning_spec.js | 15 - plugins/console/spec/pass_spec.js | 21 - plugins/ngHint/index.js | 199 -- plugins/ngHint/spec/fail_spec.js | 7 - plugins/ngHint/spec/failureConfig.js | 11 - plugins/ngHint/spec/successConfig.js | 11 - plugins/ngHint/spec/success_spec.js | 5 - plugins/timeline/index.js | 340 --- plugins/timeline/indextemplate.html | 56 - plugins/timeline/spec/chromelog.txt | 284 --- plugins/timeline/spec/conf.js | 12 - plugins/timeline/spec/e2e.js | 14 - plugins/timeline/spec/standalonelog.txt | 261 -- plugins/timeline/spec/unit.js | 124 - scripts/test.js | 75 - scripts/unit_test.json | 3 +- testapp/accessibility/badMarkup.html | 22 - testapp/accessibility/index.html | 23 - testapp/console/index.html | 35 - testapp/ngHint/index.html | 21 - testapp/ngHint/ngHint.js | 2180 ----------------- testapp/ngHint/noNgHint.html | 20 - testapp/ngHint/noTag.html | 21 - testapp/ngHint/unused.html | 21 - 41 files changed, 34 insertions(+), 4450 deletions(-) delete mode 100644 plugins/README.md delete mode 100644 plugins/accessibility/index.js delete mode 100644 plugins/accessibility/spec/fail_spec.js delete mode 100644 plugins/accessibility/spec/failureConfig.js delete mode 100644 plugins/accessibility/spec/successConfig.js delete mode 100644 plugins/accessibility/spec/success_spec.js delete mode 100644 plugins/console/index.js delete mode 100644 plugins/console/spec/consoleFailConfig.js delete mode 100644 plugins/console/spec/consoleFailErrorConfig.js delete mode 100644 plugins/console/spec/consoleFailFilterConfig.js delete mode 100644 plugins/console/spec/consoleFailLogWarnings.js delete mode 100644 plugins/console/spec/consoleFailWarningConfig.js delete mode 100644 plugins/console/spec/consolePassConfig.js delete mode 100644 plugins/console/spec/consolePassLogWarnings.js delete mode 100644 plugins/console/spec/fail_error_spec.js delete mode 100644 plugins/console/spec/fail_spec.js delete mode 100644 plugins/console/spec/fail_warning_spec.js delete mode 100644 plugins/console/spec/pass_spec.js delete mode 100644 plugins/ngHint/index.js delete mode 100644 plugins/ngHint/spec/fail_spec.js delete mode 100644 plugins/ngHint/spec/failureConfig.js delete mode 100644 plugins/ngHint/spec/successConfig.js delete mode 100644 plugins/ngHint/spec/success_spec.js delete mode 100644 plugins/timeline/index.js delete mode 100644 plugins/timeline/indextemplate.html delete mode 100644 plugins/timeline/spec/chromelog.txt delete mode 100644 plugins/timeline/spec/conf.js delete mode 100644 plugins/timeline/spec/e2e.js delete mode 100644 plugins/timeline/spec/standalonelog.txt delete mode 100644 plugins/timeline/spec/unit.js delete mode 100644 testapp/accessibility/badMarkup.html delete mode 100644 testapp/accessibility/index.html delete mode 100644 testapp/console/index.html delete mode 100644 testapp/ngHint/index.html delete mode 100644 testapp/ngHint/ngHint.js delete mode 100644 testapp/ngHint/noNgHint.html delete mode 100644 testapp/ngHint/noTag.html delete mode 100644 testapp/ngHint/unused.html diff --git a/docs/plugins.md b/docs/plugins.md index e38851a40..e05d5c734 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -12,11 +12,7 @@ The `plugins` folder contains default plugins for Protractor. ##In this document: * [Using Plugins](/docs/plugins.md#using-plugins) * [Writing Plugins](/docs/plugins.md#writing-plugins) -* Default Plugins - * [Accessibility Plugin](/docs/plugins.md#accessibility-plugin) - * [ngHint Plugin](/docs/plugins.md#nghint-plugin) - * [Timeline Plugin](/docs/plugins.md#timeline-plugin) - * [Console Plugin](/docs/plugins.md#console-plugin-chrome-only) +* [First Party Plugins](/docs/plugins.md#first-party-plugins) * [Community Plugins](/docs/plugins.md#community-plugins) Using Plugins @@ -290,145 +286,49 @@ exports.addWarning(message, options); If you specify any of these properties in your plugin file, they will be overwritten. -Accessibility Plugin --------------------- -Protractor comes with support for two accessibility testing options: - * Accessibility Developer Tools - * Tenon.io - -Protractor will run each set of audits (depending on your configuration) on your existing end-to-end -tests to ensure your site is free of obvious errors. In this kind of testing, there is no concept of -"warnings"–only pass or fail. In your configuration, you can decide whether warnings should -pass or fail your build. - -To understand how each of these tools can be used, see this support matrix: - -| Testing Library | Pricing | API Key | External Request | No. of Tests | Info | -|--------------------------------------|-------------------------------------------|---------|------------------|--------------|-------------------------------------------------------------------------| -| Chrome Accessibility Developer Tools | Free | No | No | 14 | [Github](https://github.com/GoogleChrome/accessibility-developer-tools) | -| Tenon.io | Free limited accounts, paid subscriptions | Yes | Yes | 63 | [Tenon.io](http://tenon.io/) | - -Protractor now supports the [Accessibility Developer Tools](https://github.com/GoogleChrome/accessibility-developer-tools), the same audit library used by the [Chrome browser extension](https://chrome.google.com/webstore/detail/accessibility-developer-t/fpkknkljclfencbdbgkenhalefipecmb?hl=en). Protractor -[runs an audit](https://github.com/GoogleChrome/accessibility-developer-tools/wiki/Audit-Rules) -locally by injecting the Dev Tools script into WebDriver pages, and it can diagnose issues including -missing labels, incorrect ARIA attributes and color contrast. This is a great starting point if -you can't send source code over the wire through an API. - -[Tenon.io](http://www.tenon.io) has a more robust set of tests to help you find -accessibility issues, but it requires [registering](http://tenon.io/register.php) for an API key -and making an external request for each test, which may not work for everyone. Some people use -Tenon with introspection services like ngrok or localtunnel to securely -test local web servers. Protractor takes the [options you provide](http://tenon.io/documentation/understanding-request-parameters.php) in the plugin configuration and sends them -with the page source to the Tenon API. One limitation of this approach is that all scripts must be reachable from the page source as a string, for example, by using a CDN. -For projects with an MIT license, Tenon is free but with a limited -daily API limit. Paid subscriptions are available for enterprise and commercial projects. - -Enable this plugin in your config file: -```js - // Chrome Accessibility Dev Tools only: - exports.config = { - ... - plugins: [{ - chromeA11YDevTools: { - treatWarningsAsFailures: true - }, - path: 'node_modules/protractor/plugins/accessibility' - }] - } -``` -```js - // Tenon.io only: - exports.config = { - ... - plugins: [{ - tenonIO: { - options: { - // See http://tenon.io/documentation/understanding-request-parameters.php - // options.src will be added by the test. - }, - printAll: false, // whether the plugin should log API response - }, - chromeA11YDevTools: true, - path: 'node_modules/protractor/plugins/accessibility' - }] - } -``` - -ngHint Plugin -------------- -ngHint adds run-time hinting to AngularJS projects. This plugin bubbles those hints up to the -command line so they can be used in automated testing. - -You enable this plugin in your config file: - ```js -exports.config = { - plugins: [{ - path: 'node_modules/protractor/plugins/ngHint', - - asTests: {Boolean}, - excludeURLs: {(String|RegExp)[]} - }] -}; -``` -`asTests` specifies if the plugin should generate passed/failed test results -based on the ngHint output or instead log the results to the console. -Defaults to true. - -`excludeURLs` specifies a list of URLs for which ngHint results should be -ignored. Defaults to [] - -Timeline Plugin ---------------- -This plugin gathers test timeline information from the protractor test process, the selenium -client logs (if available), and sauce labs (if available), and presents the output visually. -This improves understanding of where latency issues are in tests. +First Party Plugins +------------------- -To enable the Timeline plugin, set it up in your config file: -```js -exports.config = { - plugins: [{ - path: 'node_modules/protractor/plugins/timeline/index.js', +* Accessibility Plugin - // Output json and html will go in this folder. - outdir: 'timelines', + The accessibility plugin runs a set of accessibility audits on your webapp. + It is published at the npm module [`protractor-accessibility-plugin`] + (https://www.npmjs.com/package/protractor-accessibility-plugin) and stored at + the github repo [angular/protractor-accessibility-plugin] + (https://github.com/angular/protractor-accessibility-plugin). - // Optional - if sauceUser and sauceKey are specified, logs from - // SauceLabs will also be parsed after test invocation. - sauceUser: 'Jane', - sauceKey: 'abcdefg' - }], - // other configuration settings -}; -``` +* Timeline Plugin + The timeline plugin gathers test timeline information from various sources and + presents the output visually. This improves understanding of where latency + issues are in tests. It is published at the npm module + [`protractor-timeline-plugin`] + (https://www.npmjs.com/package/protractor-timeline-plugin) and stored at the + github repo [angular/protractor-timeline-plugin] + (https://github.com/angular/protractor-timeline-plugin). -Console Plugin (Chrome only) ----------------------------- +* ngHint Plugin -This plugin checks the browser log after each test for warnings and errors. It -can be configured to fail a test if either is detected. There is also an -optional exclude parameter which accepts both regex and strings. Any log -matching the exclude parameter will not fail the test or be logged to the -console. A false setting to logWarnings also overrides the failOnWarning setting. + The ngHint plugin uses [Angular Hint](https://github.com/angular/angular-hint) + to generate run-time hinting and then turns these hints into Protractor tests. + It is published at the npm module [`protractor-ng-hint-plugin`] + (https://www.npmjs.com/package/protractor-ng-hint-plugin) and stored at the + github repo [angular/protractor-ng-hint-plugin] + (https://github.com/angular/protractor-ng-hint-plugin). -```js -exports.config = { - plugins: [{ - path: 'node_modules/protractor/plugins/console', - failOnWarning: {Boolean} (Default - false), - failOnError: {Boolean} (Default - true), - logWarnings: {Boolean} (Default - true), - exclude: {Array of strings and regex} (Default - []) - }] -}; -``` +* Console Plugin (Chrome Only) -Note that this plugin's behavior is undefined on browsers other than Chrome. -Firefox users have reported flaky results. + The console plugin checks the browser log after each test for warnings and + errors. It is published at the npm module [`protractor-console-plugin`] + (https://www.npmjs.com/package/protractor-console-plugin) and stored at the + github repo [angular/protractor-console-plugin] + (https://github.com/angular/protractor-console-plugin). Community Plugins ----------------- -This list is here for reference and the plugins included are not developed or mantained by protractor's team by any means. If you find any issues with this plugins please report them to the corresponding plugin developer. +This list is here for reference and the plugins included are not developed or +mantained by protractor's team by any means. If you find any issues with this +plugins please report them to the corresponding plugin developer. * [Protractor testability plugin](https://github.com/alfonso-presa/protractor-testability-plugin): this plugins enables synchronous testing with protractor for features that are not developed using the services provided by AngularJS, preventing the need of additional waits coded in the tests. This happens for example if you have WebSockets communication with the server or for web applications built with frameworks different than AngularJS. diff --git a/plugins/README.md b/plugins/README.md deleted file mode 100644 index 496e32fc7..000000000 --- a/plugins/README.md +++ /dev/null @@ -1 +0,0 @@ -Please see [the plugin documentation](../docs/plugins.md) diff --git a/plugins/accessibility/index.js b/plugins/accessibility/index.js deleted file mode 100644 index 00ef4ca6d..000000000 --- a/plugins/accessibility/index.js +++ /dev/null @@ -1,232 +0,0 @@ -var q = require('q'), - fs = require('fs'), - path = require('path'), - _ = require('lodash'); - request = require('request'), - Entities = require('html-entities').XmlEntities; - -/** - * You can audit your website against the Chrome Accessibility Developer Tools, - * Tenon.io, or both by enabling this plugin in your config file: - * - * // Chrome Accessibility Developer Tools: - * exports.config = { - * ... - * plugins: [{ - * chromeA11YDevTools: { - * treatWarningsAsFailures: true - * }, - * path: 'node_modules/protractor.plugins/accessiblity' - * }] - * } - * - * // Tenon.io: - * - * // Read about the Tenon.io settings and API requirements: - * // -http://tenon.io/documentation/overview.php - * - * exports.config = { - * ... - * plugins: [{ - * tenonIO: { - * options: { - * // See http://tenon.io/documentation/understanding-request-parameters.php - * // options.src will be added by the test. - * }, - * printAll: false, // whether the plugin should log API response - * }, - * chromeA11YDevTools: false, - * path: 'node_modules/protractor/plugins/accessiblity' - * }] - * } - * - */ - -var AUDIT_FILE = require.resolve('accessibility-developer-tools/dist/js/axs_testing.js'); -var TENON_URL = 'http://www.tenon.io/api/'; - -/** - * Checks the information returned by the accessibility audit(s) and - * displays passed/failed results as console output. - * - * @this {Object} The plugin context object - * @return {q.Promise} A promise which resolves when all audits are finished - * @public - */ -function teardown() { - - var audits = []; - - if (this.config.chromeA11YDevTools) { - audits.push(runChromeDevTools(this)); - } - // check for Tenon config and an actual API key, not the placeholder - if (this.config.tenonIO && /[A-Za-z][0-9]/.test( - this.config.tenonIO.options.key)) { - audits.push(runTenonIO(this)); - } - return q.all(audits); -} - -var entities = new Entities(); - -/** - * Audits page source against the Tenon API, if configured. Requires an API key: - * more information about licensing and configuration available at - * http://tenon.io/documentation/overview.php. - * - * @param {Object} context The plugin context object - * @return {q.Promise} A promise which resolves when the audit is finished - * @private - */ -function runTenonIO(context) { - - return browser.driver.getPageSource().then(function(source) { - - var options = _.assign(context.config.tenonIO.options, {src: source}); - - // setup response as a deferred promise - var deferred = q.defer(); - request.post({ - url: TENON_URL, - form: options - }, - function(err, httpResponse, body) { - if (err) { return resolve.reject(new Error(err)); } - else { return deferred.resolve(JSON.parse(body)); } - }); - - return deferred.promise.then(function(response) { - return processTenonResults(response); - }); - }); - - function processTenonResults(response) { - - var testHeader = 'Tenon.io - '; - - if (!response.resultSet) { - if (response.code === 'daily_limit_reached') { - console.log(testHeader, 'Daily limit reached'); - console.log(response.moreInfo); - } - else { - console.log('Tenon.io error'); - } - return; - } - - var numResults = response.resultSet.length; - - if (numResults === 0) { - context.addSuccess(); - return; - } - - if (context.config.tenonIO.printAll) { - console.log('\x1b[32m', testHeader + 'API response', '\x1b[39m'); - console.log(response); - } - - return response.resultSet.forEach(function(result) { - var ref = (result.ref === null) ? '' : result.ref; - - context.addFailure(result.errorDescription + '\n\n' + - '\t\t' +entities.decode(result.errorSnippet) + - '\n\n\t\t' + ref, {specName: testHeader + result.errorTitle}); - }); - } -} - -/** - * Audits page source against the Chrome Accessibility Developer Tools, if configured. - * - * @param {Object} context The plugin context object - * @return {q.Promise} A promise which resolves when the audit is finished - * @private - */ -function runChromeDevTools(context) { - - var data = fs.readFileSync(AUDIT_FILE, 'utf-8'); - data = data + ' return axs.Audit.run();'; - - var elementPromises = [], - elementStringLength = 200; - - function trimText(text) { - if (text.length > elementStringLength) { - return text.substring(0, elementStringLength / 2) + ' ... ' - + text.substring(text.length - elementStringLength / 2); - } else { - return text; - } - } - - var testHeader = 'Chrome A11Y - '; - - return browser.executeScript_(data, 'a11y developer tool rules').then(function(results) { - - var audit = results.map(function(result) { - var DOMElements = result.elements; - if (DOMElements !== undefined) { - - DOMElements.forEach(function(elem) { - // get elements from WebDriver, add to promises array - elementPromises.push( - elem.getOuterHtml().then(function(text) { - return { - code: result.rule.code, - list: trimText(text) - }; - }, - function(reason){ - return { - code: result.rule.code, - list: reason - }; - }) - ); - }); - result.elementCount = DOMElements.length; - } - return result; - }); - - // Wait for element names to be fetched - return q.all(elementPromises).then(function(elementFailures) { - - return audit.forEach(function(result, index) { - if (result.result === 'FAIL') { - var label = result.elementCount === 1 ? ' element ' : ' elements '; - if (result.rule.severity !== 'Warning' - || context.config.chromeA11YDevTools.treatWarningsAsFailures) { - result.warning = false; - } else { - result.warning = true; - result.rule.heading = '\x1b[33m(WARNING) ' - + result.rule.heading + ' (' + result.elementCount - + label + 'failed)'; - } - result.output = '\n\t\t' + result.elementCount + label + 'failed:'; - - // match elements returned via promises - // by their failure codes - elementFailures.forEach(function(element, index) { - if (element.code === result.rule.code) { - result.output += '\n\t\t' + elementFailures[index].list; - } - }); - result.output += '\n\n\t\t' + result.rule.url; - (result.warning ? context.addWarning : context.addFailure)( - result.output, {specName: testHeader + result.rule.heading}); - } - else { - context.addSuccess({specName: testHeader + result.rule.heading}); - } - }); - }); - }); -} - -// Export -exports.teardown = teardown; diff --git a/plugins/accessibility/spec/fail_spec.js b/plugins/accessibility/spec/fail_spec.js deleted file mode 100644 index 2933c3f17..000000000 --- a/plugins/accessibility/spec/fail_spec.js +++ /dev/null @@ -1,5 +0,0 @@ -describe('check if accessibility plugin works on bad apps', function() { - it('should have accessibility problems on markup', function() { - browser.get('accessibility/badMarkup.html'); - }); -}); diff --git a/plugins/accessibility/spec/failureConfig.js b/plugins/accessibility/spec/failureConfig.js deleted file mode 100644 index 4ec69fb15..000000000 --- a/plugins/accessibility/spec/failureConfig.js +++ /dev/null @@ -1,21 +0,0 @@ -var env = require('../../../spec/environment.js'); - -exports.config = { - seleniumAddress: env.seleniumAddress, - framework: 'jasmine', - specs: ['fail_spec.js'], - baseUrl: env.baseUrl, - plugins: [{ - tenonIO: { - options: { - key: 'YOUR_API_KEY', // ADD YOUR API KEY HERE - level: 'AA' // WCAG AA OR AAA - }, - printAll: false - }, - chromeA11YDevTools: { - treatWarningsAsFailures: true - }, - path: '../index.js' - }] -}; diff --git a/plugins/accessibility/spec/successConfig.js b/plugins/accessibility/spec/successConfig.js deleted file mode 100644 index fa2757690..000000000 --- a/plugins/accessibility/spec/successConfig.js +++ /dev/null @@ -1,19 +0,0 @@ -var env = require('../../../spec/environment.js'); - -exports.config = { - seleniumAddress: env.seleniumAddress, - framework: 'jasmine', - specs: ['success_spec.js'], - baseUrl: env.baseUrl, - plugins: [{ - tenonIO: { - options: { - key: 'YOUR_API_KEY', // ADD YOUR API KEY HERE - level: 'AA' // WCAG AA OR AAA - }, - printAll: false - }, - chromeA11YDevTools: true, - path: "../index.js" - }] -}; diff --git a/plugins/accessibility/spec/success_spec.js b/plugins/accessibility/spec/success_spec.js deleted file mode 100644 index 0b20f15aa..000000000 --- a/plugins/accessibility/spec/success_spec.js +++ /dev/null @@ -1,9 +0,0 @@ -describe('accessibility', function() { - it('should get a file to test', function() { - browser.get('accessibility/index.html'); - - element.all(by.css('input')).then(function(inputs) { - expect(inputs.length).toEqual(2); - }); - }); -}); diff --git a/plugins/console/index.js b/plugins/console/index.js deleted file mode 100644 index 4e600326d..000000000 --- a/plugins/console/index.js +++ /dev/null @@ -1,117 +0,0 @@ -var q = require('q'); - -/** - * This plugin checks the browser log after each test for warnings and errors. - * It can be configured to fail a test if either is detected. There is also an - * optional exclude parameter which accepts both regex and strings. Any log - * matching the exclude parameter will not fail the test or be logged to the - * console. A false setting to logWarnings also overrides the failOnWarning setting. - * - * exports.config = { - * plugins: [{ - * path: 'node_modules/protractor/plugins/console', - * failOnWarning: {Boolean} (Default - false), - * failOnError: {Boolean} (Default - true), - * logWarnings: {Boolean} (Default - true), - * exclude: {Array of strings and regex} (Default - []) - * }] - * }; - */ -var ConsolePlugin = function() { -}; - -/** - * Gets the browser log. - * - * @return {webdriver.promise.Promise.>} - */ -ConsolePlugin.getBrowserLog = function() { - return browser.manage().logs().get('browser'); -}; - -/** - * Logs messages to the test outputl - * - * @param {Object} warnings The list of warnings detected by the browser log. - * @param {Object} errors The list of errors detected by the browser log. - * @param {boolean} failOnWarning Tests fail if a warning was detected - * @param {boolean} failOnError Tests fail if an error was detected - * @param {Object} context The plugin context object - */ -ConsolePlugin.logMessages = function(warnings, errors, - failOnWarning, failOnError, context) { - warnings.map(function(warning) { - (failOnWarning ? context.addFailure : context.addWarning)( - warning.level.name + ': ' + warning.message); - }); - errors.map(function(error) { - (failOnError ? context.addFailure : context.addWarning)( - error.level.name + ': ' + error.message); - }); -}; - -/** - * Determines if a log message is filtered out or not. This can be set at the - * config stage using the exclude parameter. The parameter accepts both strings - * and regex. - * - * @param {string} logMessage Current log message. - * @return {boolean} true iff the log should be included in the output - */ -ConsolePlugin.includeLog = function(logMessage) { - return ConsolePlugin.exclude.filter(function(e) { - return (e instanceof RegExp) ? logMessage.match(e) : - logMessage.indexOf(e) > -1; - }).length === 0; -}; - -/** - * Parses the log and decides whether to throw an error or not. - * - * @param {Object} context The plugin context object - * @return {!webdriver.promise.Promise.} A promise which resolves when the - * logs have been gathered - */ -ConsolePlugin.parseLog = function(context) { - var failOnWarning = (context.config.failOnWarning === undefined) ? false : - context.config.failOnWarning; - var failOnError = (context.config.failOnError === undefined) ? true : - context.config.failOnError; - var logWarnings = (context.config.logWarnings === undefined) ? true : - context.config.logWarnings; - ConsolePlugin.exclude = context.config.exclude || []; - - return ConsolePlugin.getBrowserLog().then(function(log) { - var warnings = []; - if (logWarnings) { - warnings = log.filter(function(node) { - return (node.level || {}).name === 'WARNING' && - ConsolePlugin.includeLog(node.message); - }); - } - - var errors = log.filter(function(node) { - return (node.level || {}).name === 'SEVERE' && - ConsolePlugin.includeLog(node.message); - }); - - ConsolePlugin.logMessages(warnings, errors, failOnWarning, failOnError, - context); - }); - -}; - -/** - * Gather the console logs and output them as test results. See the - * documentation of the teardown function in the protractor plugin API. - * - * @return {!webdriver.promise.Promise.} A promise which resolves to the - * test results generated by the console logs - */ -ConsolePlugin.prototype.teardown = function() { - return ConsolePlugin.parseLog(this); -}; - -var consolePlugin = new ConsolePlugin(); - -module.exports = consolePlugin; diff --git a/plugins/console/spec/consoleFailConfig.js b/plugins/console/spec/consoleFailConfig.js deleted file mode 100644 index 0787b841f..000000000 --- a/plugins/console/spec/consoleFailConfig.js +++ /dev/null @@ -1,13 +0,0 @@ -var env = require('../../../spec/environment.js'); - -exports.config = { - seleniumAddress: env.seleniumAddress, - framework: 'jasmine', - specs: ['fail_spec.js'], - baseUrl: env.baseUrl, - plugins: [{ - path: '../index.js', - failOnWarning: true, - failOnError: true - }] -}; diff --git a/plugins/console/spec/consoleFailErrorConfig.js b/plugins/console/spec/consoleFailErrorConfig.js deleted file mode 100644 index 42ec16798..000000000 --- a/plugins/console/spec/consoleFailErrorConfig.js +++ /dev/null @@ -1,13 +0,0 @@ -var env = require('../../../spec/environment.js'); - -exports.config = { - seleniumAddress: env.seleniumAddress, - framework: 'jasmine', - specs: ['fail_error_spec.js'], - baseUrl: env.baseUrl, - plugins: [{ - path: '../index.js', - failOnWarning: false, - failOnError: true - }] -}; diff --git a/plugins/console/spec/consoleFailFilterConfig.js b/plugins/console/spec/consoleFailFilterConfig.js deleted file mode 100644 index f5a6ed239..000000000 --- a/plugins/console/spec/consoleFailFilterConfig.js +++ /dev/null @@ -1,17 +0,0 @@ -var env = require('../../../spec/environment.js'); - -exports.config = { - seleniumAddress: env.seleniumAddress, - framework: 'jasmine', - specs: ['fail_error_spec.js'], - baseUrl: env.baseUrl, - plugins: [{ - path: '../index.js', - failOnWarning: true, - failOnError: true, - exclude: [ - 'string', - /regex/ - ] - }] -}; diff --git a/plugins/console/spec/consoleFailLogWarnings.js b/plugins/console/spec/consoleFailLogWarnings.js deleted file mode 100644 index d531866a0..000000000 --- a/plugins/console/spec/consoleFailLogWarnings.js +++ /dev/null @@ -1,14 +0,0 @@ -var env = require('../../../spec/environment.js'); - -exports.config = { - seleniumAddress: env.seleniumAddress, - framework: 'jasmine', - specs: ['fail_warning_spec.js'], - baseUrl: env.baseUrl, - plugins: [{ - path: '../index.js', - failOnWarning: true, - logWarnings: true, - failOnError: false - }] -}; diff --git a/plugins/console/spec/consoleFailWarningConfig.js b/plugins/console/spec/consoleFailWarningConfig.js deleted file mode 100644 index cbb39425a..000000000 --- a/plugins/console/spec/consoleFailWarningConfig.js +++ /dev/null @@ -1,13 +0,0 @@ -var env = require('../../../spec/environment.js'); - -exports.config = { - seleniumAddress: env.seleniumAddress, - framework: 'jasmine', - specs: ['fail_warning_spec.js'], - baseUrl: env.baseUrl, - plugins: [{ - path: '../index.js', - failOnWarning: true, - failOnError: false - }] -}; diff --git a/plugins/console/spec/consolePassConfig.js b/plugins/console/spec/consolePassConfig.js deleted file mode 100644 index 4cfddee76..000000000 --- a/plugins/console/spec/consolePassConfig.js +++ /dev/null @@ -1,13 +0,0 @@ -var env = require('../../../spec/environment.js'); - -exports.config = { - seleniumAddress: env.seleniumAddress, - framework: 'jasmine', - specs: ['pass_spec.js'], - baseUrl: env.baseUrl, - plugins: [{ - path: '../index.js', - failOnWarning: false, - failOnError: false - }] -}; diff --git a/plugins/console/spec/consolePassLogWarnings.js b/plugins/console/spec/consolePassLogWarnings.js deleted file mode 100644 index 84b6063f2..000000000 --- a/plugins/console/spec/consolePassLogWarnings.js +++ /dev/null @@ -1,14 +0,0 @@ -var env = require('../../../spec/environment.js'); - -exports.config = { - seleniumAddress: env.seleniumAddress, - framework: 'jasmine', - specs: ['pass_spec.js'], - baseUrl: env.baseUrl, - plugins: [{ - path: '../index.js', - failOnWarning: true, - logWarnings: false, - failOnError: false - }] -}; diff --git a/plugins/console/spec/fail_error_spec.js b/plugins/console/spec/fail_error_spec.js deleted file mode 100644 index bb2099b69..000000000 --- a/plugins/console/spec/fail_error_spec.js +++ /dev/null @@ -1,15 +0,0 @@ -describe('console plugin', function() { - - var logMessageButton = element(by.id('log-message')); - var deleteMessageButton = element(by.id('simulate-error')); - - it('should fail on error message', function() { - browser.get('console/index.html'); - deleteMessageButton.click(); - }); - - it('should not fail on log and debug messages', function() { - browser.get('console/index.html'); - logMessageButton.click(); - }); -}); diff --git a/plugins/console/spec/fail_spec.js b/plugins/console/spec/fail_spec.js deleted file mode 100644 index d9b993bc2..000000000 --- a/plugins/console/spec/fail_spec.js +++ /dev/null @@ -1,21 +0,0 @@ -describe('console plugin', function() { - - var logMessageButton = element(by.id('log-message')); - var warningMessageButton = element(by.id('simulate-warning')); - var deleteMessageButton = element(by.id('simulate-error')); - - it('should fail on warning message', function() { - browser.get('console/index.html'); - warningMessageButton.click(); - }); - - it('should fail on error message', function() { - browser.get('console/index.html'); - deleteMessageButton.click(); - }); - - it('should not fail on log and debug messages', function() { - browser.get('console/index.html'); - logMessageButton.click(); - }); -}); diff --git a/plugins/console/spec/fail_warning_spec.js b/plugins/console/spec/fail_warning_spec.js deleted file mode 100644 index 11e2c3dce..000000000 --- a/plugins/console/spec/fail_warning_spec.js +++ /dev/null @@ -1,15 +0,0 @@ -describe('console plugin', function() { - - var logMessageButton = element(by.id('log-message')); - var warningMessageButton = element(by.id('simulate-warning')); - - it('should fail on warning message', function() { - browser.get('console/index.html'); - warningMessageButton.click(); - }); - - it('should not fail on log and debug messages', function() { - browser.get('console/index.html'); - logMessageButton.click(); - }); -}); diff --git a/plugins/console/spec/pass_spec.js b/plugins/console/spec/pass_spec.js deleted file mode 100644 index 6868e3b56..000000000 --- a/plugins/console/spec/pass_spec.js +++ /dev/null @@ -1,21 +0,0 @@ -describe('console plugin', function() { - - var logMessageButton = element(by.id('log-message')); - var warningMessageButton = element(by.id('simulate-warning')); - var deleteMessageButton = element(by.id('simulate-error')); - - it('should not fail on log and debug messages', function() { - browser.get('console/index.html'); - logMessageButton.click(); - }); - - it('should not fail on warning message', function() { - browser.get('console/index.html'); - warningMessageButton.click(); - }); - - it('should not fail on error message', function() { - browser.get('console/index.html'); - deleteMessageButton.click(); - }); -}); diff --git a/plugins/ngHint/index.js b/plugins/ngHint/index.js deleted file mode 100644 index 65451f6e6..000000000 --- a/plugins/ngHint/index.js +++ /dev/null @@ -1,199 +0,0 @@ -var q = require('q'), - fs = require('fs'), - _ = require('lodash'), - ngHintNames = { - ngHintControllers: 'Controllers', - ngHintDirectives: 'Directives', - ngHintDom: 'DOM', - ngHintEvents: 'Events', - ngHintInterpolation: 'Interpolation', - ngHintModules: 'Modules', - ngHintScopes: 'Scopes', - ngHintGeneral: 'General' - }; - -/** - * You enable this plugin in your config file: - * - * exports.config = { - * plugins: [{ - * path: 'node_modules/protractor/plugins/ngHint', - * - * asTests: {Boolean}, - * excludeURLs: {(String|RegExp)[]} - * }] - * }; - * - * asTests specifies if the plugin should generate passed/failed test results - * based on the ngHint output or instead log the results to the console. - * Defaults to true. - * - * excludeURLs specifies a list of URLs for which ngHint results should be - * ignored. Defaults to [] - */ - -/* - * The strategy for this plugin is as follows: - * - * During setup, install the ngHint code and listeners to capture its output. - * Store the output in the following format: - * {page URL} -> {module} -> {message} -> {message type} - * - * So, for instance, you might have: - * { - * 'google.com': { - * 'Controllers': { - * {'It is against Angular best practices to...': warning} - * }, - * 'Modules: { - * {'Module "Search" was loaded but does not exist': error} - * } - * } - * } - * - * We store the messages as keys in objects in order to avoid duplicates. - */ - -/** - * Configures the plugin to grab the output of ngHint - * - * @see docs/plugins.md - * @public - */ -function setup() { - // Intercept ngHint output - browser.addMockModule('protractorNgHintCaptureModule_', function() { - angular.module('protractorNgHintCaptureModule_', []); - var hintInstalled = true; - if (!angular.hint) { - hintInstalled = false; - angular.hint = {}; - } - /** override */ - angular.hint.onMessage = function(module, message, type) { - var ngHintLog = JSON.parse(localStorage.getItem( - 'ngHintLog_protractor') || '{}'); - var pageLog = ngHintLog[location] || {}; - var moduleLog = pageLog[module] || {}; - moduleLog[message] = type; - pageLog[module] = moduleLog; - ngHintLog[location] = pageLog; - localStorage.setItem('ngHintLog_protractor', - JSON.stringify(ngHintLog)); - }; - if (!hintInstalled) { - angular.hint.onMessage('General', 'ngHint plugin cannot be run as ' + - 'ngHint code was never included into the page', 'warning'); - } - }); -} - -/** - * Checks if a URL should not be examined by the ngHint plugin - * - * @param {String} url The URL to check for exclusion - * @param {Object} config The configuration file for the ngHint plugin - * @return {Boolean} true if the URL should not be examined by the ngHint plugin - * @private - */ -function isExcluded(url, config) { - var excludeURLs = config.excludeURLs || []; - for (var i = 0; i < excludeURLs.length; i++) { - if (typeof excludeURLs[i] == typeof '') { - if (url == excludeURLs[i]) { - return true; - } - } else { - if (excludeURLs[i].test(url)) { - return true; - } - } - } - return false; -} - -/** - * Checks if a warning message should be ignored by the ngHint plugin - * - * @param {String} message The message to check - * @return {Boolean} true if the message should be ignored - * @private - */ -function isMessageToIgnore(message) { - if (message == 'It is against Angular best practices to instantiate a ' + - 'controller on the window. This behavior is deprecated in Angular ' + - '1.3.0') { - return true; // An ngHint bug, see http://git.io/S3yySQ - } - - var module = /^Module "(\w*)" was created but never loaded\.$/.exec( - message); - if (module != null) { - module = module[1]; - if (ngHintNames[module] != null) { - return true; // An ngHint module - } - if ((module == 'protractorBaseModule_') || (module == - 'protractorNgHintCaptureModule_')) { - return true; // A protractor module - } - } - - return false; -} - -/** - * Checks the information which has been stored by the ngHint plugin and - * generates passed/failed tests and/or console output - * - * @see docs/plugins.md - * @return {q.Promise} A promise which resolves to the results of any passed or - * failed tests - * @public - */ -function teardown() { - var self = this; - // Get logged data - return browser.executeScript_(function() { - return localStorage.getItem('ngHintLog_protractor') || '{}'; - }, 'get ngHintLog').then(function(ngHintLog) { - ngHintLog = JSON.parse(ngHintLog); - - // Get a list of all the modules we tested against - var modulesUsed = _.union.apply(_, [_.values(ngHintNames)].concat( - _.values(ngHintLog).map(Object.keys))); - - // Check log - var testOut = {failedCount: 0, specResults: []}; - for (url in ngHintLog) { - if (!isExcluded(url, self.config)) { - for (var i = 0; i < modulesUsed.length; i++) { - var resultInfo = {specName: 'Angular Hint Test: ' + modulesUsed[i] + - ' (' + url + ')'}; - var passed = true; - - // Fill in the test details - var messages = ngHintLog[url][modulesUsed[i]]; - if (messages) { - for (var message in messages) { - if (!isMessageToIgnore(message)) { - (self.config.asTests !== false ? self.addFailure : - self.addWarning)(messages[message] + ' -- ' + message, - resultInfo); - passed = false; - } - } - } - - if (passed) { - self.addSuccess(resultInfo); - } - } - } - } - }); -} - -// Export -exports.setup = setup; -exports.teardown = teardown; diff --git a/plugins/ngHint/spec/fail_spec.js b/plugins/ngHint/spec/fail_spec.js deleted file mode 100644 index ca950c88d..000000000 --- a/plugins/ngHint/spec/fail_spec.js +++ /dev/null @@ -1,7 +0,0 @@ -describe('check if ngHint plugin works on bad apps', function() { - it('should have ngHint problems on bad apps', function() { - browser.get('ngHint/noNgHint.html'); - browser.get('ngHint/noTag.html'); - browser.get('ngHint/unused.html'); - }); -}); diff --git a/plugins/ngHint/spec/failureConfig.js b/plugins/ngHint/spec/failureConfig.js deleted file mode 100644 index dbe49f445..000000000 --- a/plugins/ngHint/spec/failureConfig.js +++ /dev/null @@ -1,11 +0,0 @@ -var env = require('../../../spec/environment.js'); - -exports.config = { - seleniumAddress: env.seleniumAddress, - framework: 'jasmine', - specs: ['fail_spec.js'], - baseUrl: env.baseUrl, - plugins: [{ - path: '../index.js' - }] -}; diff --git a/plugins/ngHint/spec/successConfig.js b/plugins/ngHint/spec/successConfig.js deleted file mode 100644 index dfd6d9d93..000000000 --- a/plugins/ngHint/spec/successConfig.js +++ /dev/null @@ -1,11 +0,0 @@ -var env = require('../../../spec/environment.js'); - -exports.config = { - seleniumAddress: env.seleniumAddress, - framework: 'jasmine', - specs: ['success_spec.js'], - baseUrl: env.baseUrl, - plugins: [{ - path: '../index.js' - }] -}; diff --git a/plugins/ngHint/spec/success_spec.js b/plugins/ngHint/spec/success_spec.js deleted file mode 100644 index 336bc1e8e..000000000 --- a/plugins/ngHint/spec/success_spec.js +++ /dev/null @@ -1,5 +0,0 @@ -describe('check if ngHint plugin works on good apps', function() { - it('should not have ngHint problems on a good app', function() { - browser.get('ngHint/index.html'); - }); -}); diff --git a/plugins/timeline/index.js b/plugins/timeline/index.js deleted file mode 100644 index d462f16a2..000000000 --- a/plugins/timeline/index.js +++ /dev/null @@ -1,340 +0,0 @@ -var q = require('q'), - fs = require('fs'), - path = require('path'), - SauceLabs = require('saucelabs'), - https = require('https'); - -var SAUCE_LOGS_WAIT = 5000; - -/** - * Outputs information about where your Protractor test is spending its time - * to the specified folder. A JSON data file and small index.html to view - * it will be created. The page uses Google Charts to show the timeline. - * - * You enable this plugin in your config file: - * - * exports.config = { - * plugins: [{ - * path: 'node_modules/protractor/plugins/timeline', - * - * // Output json and html will go in this folder. Relative - * // to current working directory of the process. - * // TODO - it would make more sense for this to be relative - * // to the config file - reconsider this setup - * outdir: 'timelines', - * - * // Optional - if sauceUser and sauceKey are specified, logs from - * // SauceLabs will also be parsed after test invocation. - * sauceUser: 'Jane', - * sauceKey: 'abcdefg' - * }] - * }; - * - * The plugin will create timeline entries from - * - The Protractor test process itself. - * - The WebDriver Selenium Server (these logs are unavailable for Internet - * Explorer and for Chrome test run over Sauce Labs). - * - Sauce Labs job logs, if sauceUser and sauceKey are specified. - * - * @constructor - */ -var TimelinePlugin = function() { - // Timelines are of the format: - // Array<{ - // source: string, - // id: number, - // command: string, - // start: number, - // end: number - // }> - this.timeline = []; - - this.clientLogAvailable = false; - this.outdir; - this.sessionId; - this.testProcessSetTimeoutTimestamp = 0; -}; - -/** - * Parse a selenium log in array form. For example, the logs returned - * from the selenium standalone server are returned as arrays. - * - * @param {Array} logArr The selenium server logs. - * @param {string} sourceName Descripton of source. - * @param {number} referenceStart Date in millis. - */ -TimelinePlugin.parseArrayLog = function(logArr, sourceName, referenceStart) { - return TimelinePlugin.parseLog(logArr, sourceName, { - isEventStart: function(event) { - return /Executing:/.test(event.message); - }, - isEventEnd: function(event) { - return /Done:/.test(event.message); - }, - extractCommand: function(event) { - // Messages from the Selenium Standalone server are of the form - // org...DriverServlet Executing: [command: details [params]] at URL /url/ - return /Executing: \[([^:^\]]*)/.exec(event.message)[1]; - }, - extractTimestamp: function(event) { - return event.timestamp; - } - }, referenceStart); -}; - -/** - * Parse a selenium log from a string. For example, the logs returned from - * Sauce Labs are available only as plain text. - * - * @param {string} text The text logs. - * @param {string} sourceName Descripton of source. - * @param {number} referenceStart Date in millis. - */ -TimelinePlugin.parseTextLog = function(text, sourceName, referenceStart) { - var logLines = text.split('\n'); - var actions; - - // Look for 'standalone server' in the first couple lines of the log. - if (/standalone server/.test(logLines.slice(0, 3).join(' '))) { - // This is a Selenium Standalone Server log. - actions = { - isEventStart: function(event) { - return /INFO - Executing:/.test(event); - }, - isEventEnd: function(event) { - return /INFO - Done:/.test(event); - }, - extractCommand: function(event) { - // Messages are of the form - // timestamp INFO - Executing: [command: details; [params]] - return /Executing: \[([^:^\]]*)/.exec(event)[1]; - }, - extractTimestamp: function(event) { - // Timestamps begin the line and are formatted as - // HH:MM:SS.SSS - // We don't care about the date so just set it to 0. - return Date.parse('01 Jan 1970 ' + event.slice(0, 12)); - } - }; - } else { - // This is a ChromeDriver log. - actions = { - isEventStart: function(event) { - return /: COMMAND/.test(event); - }, - isEventEnd: function(event) { - return /: RESPONSE/.test(event); - }, - extractCommand: function(event) { - return /: COMMAND ([^\s]*)/.exec(event)[1]; - }, - extractTimestamp: function(event) { - return parseFloat(/^\[?([^\]]*)/.exec(event)[1]) * 1000; - } - }; - } - - return TimelinePlugin.parseLog(logLines, sourceName, actions, referenceStart); -}; - - -/** - * Parse a selenium log. - * - * @param {Array} entries The list of entries. - * @param {string} sourceName Descripton of source. - * @param {isEventStart: function, - isEventEnd: function, - extractCommand: function, - extractTimestamp: function} actions Methods to interpret entries. - * @param {number} referenceStart Date in millis. - */ -TimelinePlugin.parseLog = - function(entries, sourceName, actions, referenceStart) { - var parsedTimeline = []; - var currentEvent = {}; - var index = 0; - var relativeStartTime = 0; - for (var j = 0; j < entries.length; ++j) { - var event = entries[j]; - if (actions.isEventStart(event)) { - currentEvent = { - source: sourceName, - id: index++, - command: actions.extractCommand(event), - start: actions.extractTimestamp(event) - }; - if (!relativeStartTime && - currentEvent.command.toString() == 'setScriptTimeout' || - currentEvent.command.toString() == 'set script timeout' || - // [sic], the timeoutt typo is present in the logs - currentEvent.command.toString() == 'set script timeoutt' || - currentEvent.command.toString() == 'SetScriptTimeout') { - relativeStartTime = currentEvent.start; - } - } else if (actions.isEventEnd(event)) { - currentEvent.end = actions.extractTimestamp(event); - currentEvent.duration = currentEvent.end - currentEvent.start; - parsedTimeline.push(currentEvent); - } - } - - // Make all the times relative to the first time log types is fetched. - for (var k = 0; k < parsedTimeline.length; ++k) { - parsedTimeline[k].start += (referenceStart - relativeStartTime); - parsedTimeline[k].end += (referenceStart - relativeStartTime); - } - - return parsedTimeline; -}; - -TimelinePlugin.prototype.outputResults = function(done) { - try { - fs.mkdirSync(this.outdir); - } catch (e) { - if (e.code != 'EEXIST') throw e; - } - var stream = fs.createReadStream( - path.join(__dirname, 'indextemplate.html')); - var outfile = path.join(this.outdir, 'timeline.json'); - fs.writeFileSync(outfile, JSON.stringify(this.timeline)); - stream.pipe(fs.createWriteStream(path.join(this.outdir, 'index.html'))); - stream.on('end', done); -}; - -/** - * @see docs/plugins.md - */ -TimelinePlugin.prototype.setup = function() { - var self = this; - var deferred = q.defer(); - self.outdir = path.resolve(process.cwd(), this.config.outdir); - var counter = 0; - - // Override executor so that we get information about commands starting - // and stopping. - var originalExecute = browser.driver.executor_.execute; - browser.driver.executor_.execute = function(command, callback) { - var timelineEvent = { - source: 'Test Process', - id: counter++, - command: command, - start: new Date().getTime(), - end: null - }; - if (!self.testProcessSetTimeoutTimestamp && - timelineEvent.command.name_ == 'setScriptTimeout') { - self.testProcessSetTimeoutTimestamp = timelineEvent.start; - } - self.timeline.push(timelineEvent); - var wrappedCallback = function(var_args) { - timelineEvent.end = new Date().getTime(); - callback.apply(this, arguments); - }; - originalExecute.apply(browser.driver.executor_, [command, wrappedCallback]); - }; - - // Clear the logs here. - browser.manage().logs().getAvailableLogTypes().then(function(result) { - // The Selenium standalone server stores its logs in the 'client' channel. - if (result.indexOf('client') !== -1) { - self.clientLogAvailable = true; - deferred.resolve(); - // browser.manage().logs().get('client').then(function() { - // deferred.resolve(); - // }); - } else { - deferred.resolve(); - } - }, function(error) { - // No logs are available - this will happen for Internet Explorer, which - // does not implement webdriver logs. See - // https://code.google.com/p/selenium/issues/detail?id=4925 - deferred.resolve(); - }); - return deferred.promise; -}; - -/** - * @see docs/plugins.md - */ -TimelinePlugin.prototype.teardown = function() { - var self = this; - var deferred = q.defer(); - // This will be needed later for grabbing data from Sauce Labs. - browser.getSession().then(function(session) { - self.sessionId = session.getId(); - }); - - // If running with a Selenium Standalone server, get the client logs. - if (self.clientLogAvailable) { - browser.manage().logs().get('client').then(function(result) { - var serverTimeline = TimelinePlugin.parseArrayLog( - result, 'Selenium Client', self.testProcessSetTimeoutTimestamp); - self.timeline = self.timeline.concat(serverTimeline); - deferred.resolve(); - }); - } else { - deferred.resolve(); - } - return deferred.promise; -}; - -/** - * @see docs/plugins.md - */ -TimelinePlugin.prototype.postResults = function() { - var self = this; - var deferred = q.defer(); - // We can't get Chrome or IE logs from Sauce Labs via the webdriver logs API - // because it does not expose them. - // TODO - if the feature request at - // https://support.saucelabs.com/entries/60070884-Enable-grabbing-server-logs-from-the-wire-protocol - // gets implemented, remove this hack. - if (this.config.sauceUser && this.config.sauceKey) { - // WARNING, HACK: we have a timeout to deal with the fact that there's a - // delay before Sauce Labs updates logs. - setTimeout(function() { - var sauceServer = new SauceLabs({ - username: this.config.sauceUser, - password: this.config.sauceKey - }); - - sauceServer.showJob(self.sessionId, function(err, job) { - var sauceLog = ''; - if (!job.log_url) { - console.log('WARNING - no Sauce Labs log url found'); - deferred.resolve(); - return; - } - https.get(job.log_url, function(res) { - res.on('data', function(data) { - sauceLog += data; - }); - - res.on('end', function() { - var sauceTimeline = - TimelinePlugin.parseTextLog( - sauceLog, - 'SauceLabs Server', - self.testProcessSetTimeoutTimestamp); - self.timeline = self.timeline.concat(sauceTimeline); - self.outputResults(deferred.resolve); - }); - - }).on('error', function(e) { - console.error(e); - }); - }); - }, SAUCE_LOGS_WAIT); - } else { - self.outputResults(deferred.resolve); - } - return deferred.promise; -}; - - -// Export - -module.exports = new TimelinePlugin(); -module.exports.TimelinePlugin = TimelinePlugin; diff --git a/plugins/timeline/indextemplate.html b/plugins/timeline/indextemplate.html deleted file mode 100644 index 76b23b44e..000000000 --- a/plugins/timeline/indextemplate.html +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - -
    - - \ No newline at end of file diff --git a/plugins/timeline/spec/chromelog.txt b/plugins/timeline/spec/chromelog.txt deleted file mode 100644 index 5b28ca2e4..000000000 --- a/plugins/timeline/spec/chromelog.txt +++ /dev/null @@ -1,284 +0,0 @@ -[2.465][INFO]: COMMAND InitSession { - "desiredCapabilities": { - "browserName": "chrome", - "chromeOptions": { - "args": [ "start-maximized", "disable-webgl", "blacklist-webgl", "blacklist-accelerated-compositing", "disable-accelerated-2d-canvas", "disable-accelerated-compositing", "disable-accelerated-layers", "disable-accelerated-plugins", "disable-accelerated-video", "disable-accelerated-video-decode", "disable-gpu", "test-type", "disable-threaded-compositing" ], - "binary": "/Volumes/Sauce/Chrome/Chrome 35.app/Contents/MacOS/Google Chrome" - }, - "count": 1, - "debuggerAddress": "127.0.0.1:9222", - "proxy": { - "proxyAutoconfigUrl": "http://127.0.0.1:19876/proxy.pac", - "proxyType": "PAC" - }, - "webdriver.remote.quietExceptions": true - } -} -[2.466][INFO]: Populating Preferences file: { - "alternate_error_pages": { - "enabled": false - }, - "autofill": { - "enabled": false - }, - "browser": { - "check_default_browser": false - }, - "distribution": { - "import_bookmarks": false, - "import_history": false, - "import_search_engine": false, - "make_chrome_default_for_user": false, - "show_welcome_page": false, - "skip_first_run_ui": true - }, - "dns_prefetching": { - "enabled": false - }, - "profile": { - "content_settings": { - "pattern_pairs": { - "https://*,*": { - "media-stream": { - "audio": "Default", - "video": "Default" - } - } - } - }, - "default_content_settings": { - "geolocation": 1, - "mouselock": 1, - "notifications": 1, - "popups": 1, - "ppapi-broker": 1 - }, - "password_manager_enabled": false - }, - "safebrowsing": { - "enabled": false - }, - "search": { - "suggest_enabled": false - }, - "translate": { - "enabled": false - } -} -[2.467][INFO]: Populating Local State file: { - "background_mode": { - "enabled": false - }, - "ssl": { - "rev_checking": { - "enabled": false - } - } -} -[2.469][INFO]: Launching chrome: /Volumes/Sauce/Chrome/Chrome 35.app/Contents/MacOS/Google Chrome --blacklist-accelerated-compositing --blacklist-webgl --disable-accelerated-2d-canvas --disable-accelerated-compositing --disable-accelerated-layers --disable-accelerated-plugins --disable-accelerated-video --disable-accelerated-video-decode --disable-background-networking --disable-client-side-phishing-detection --disable-component-update --disable-default-apps --disable-gpu --disable-hang-monitor --disable-prompt-on-repost --disable-sync --disable-threaded-compositing --disable-web-resources --disable-webgl --enable-logging --ignore-certificate-errors --load-extension=/var/folders/bl/1800rz_j7blcqx8pthyrq59h0000gn/T/.org.chromium.Chromium.BZB35o/internal --logging-level=1 --metrics-recording-only --no-first-run --password-store=basic --proxy-pac-url=http://127.0.0.1:19876/proxy.pac --remote-debugging-port=12382 --safebrowsing-disable-auto-update --safebrowsing-disable-download-protection --start-maximized --test-type --use-mock-keychain --user-data-dir=/var/folders/bl/1800rz_j7blcqx8pthyrq59h0000gn/T/.org.chromium.Chromium.E1jTrM data:, -[4.246][INFO]: RESPONSE InitSession { - "acceptSslCerts": true, - "applicationCacheEnabled": false, - "browserConnectionEnabled": false, - "browserName": "chrome", - "chrome": { - "userDataDir": "/var/folders/bl/1800rz_j7blcqx8pthyrq59h0000gn/T/.org.chromium.Chromium.E1jTrM" - }, - "cssSelectorsEnabled": true, - "databaseEnabled": false, - "handlesAlerts": true, - "javascriptEnabled": true, - "locationContextEnabled": true, - "nativeEvents": true, - "platform": "Mac OS X", - "rotatable": false, - "takesHeapSnapshot": true, - "takesScreenshot": true, - "version": "35.0.1916.114", - "webStorageEnabled": true -} -[4.512][INFO]: COMMAND ExecuteScript { - "args": [ ], - "script": "return screen.width" -} -[4.746][INFO]: Waiting for pending navigations... -[4.763][INFO]: Done waiting for pending navigations -[4.812][INFO]: Waiting for pending navigations... -[4.812][INFO]: Done waiting for pending navigations -[4.812][INFO]: RESPONSE ExecuteScript 1280 -[4.815][INFO]: COMMAND ExecuteScript { - "args": [ ], - "script": "return screen.height" -} -[4.815][INFO]: Waiting for pending navigations... -[4.815][INFO]: Done waiting for pending navigations -[4.824][INFO]: Waiting for pending navigations... -[4.824][INFO]: Done waiting for pending navigations -[4.824][INFO]: RESPONSE ExecuteScript 800 -[4.827][INFO]: COMMAND SetWindowPosition { - "windowHandle": "current", - "x": 0, - "y": 0 -} -[4.832][INFO]: Waiting for pending navigations... -[4.843][INFO]: Done waiting for pending navigations -[5.001][INFO]: RESPONSE SetWindowPosition -[5.003][INFO]: COMMAND SetWindowSize { - "height": 800, - "width": 1280, - "windowHandle": "current" -} -[5.198][INFO]: RESPONSE SetWindowSize -[5.201][INFO]: COMMAND MaximizeWindow { - "windowHandle": "current" -} -[5.307][INFO]: RESPONSE MaximizeWindow -[5.310][INFO]: COMMAND GetWindows { - -} -[5.311][INFO]: RESPONSE GetWindows [ "CDwindow-64D838A1-3314-CD60-A5AB-D64369F3D241" ] -[5.397][INFO]: COMMAND SetScriptTimeout { - "ms": 11000 -} -[5.397][INFO]: RESPONSE SetScriptTimeout -[5.456][INFO]: COMMAND GetLogTypes { - -} -[5.456][INFO]: RESPONSE GetLogTypes [ "browser", "driver" ] -[5.598][INFO]: COMMAND Navigate { - "url": "data:text/html,\u003Chtml>\u003C/html>" -} -[5.598][INFO]: Waiting for pending navigations... -[5.598][INFO]: Done waiting for pending navigations -[5.667][INFO]: Waiting for pending navigations... -[5.667][INFO]: Done waiting for pending navigations -[5.667][INFO]: RESPONSE Navigate -[5.850][INFO]: COMMAND ExecuteScript { - "args": [ ], - "script": "window.name = \"NG_DEFER_BOOTSTRAP!\" + window.name;window.location.replace(\"http://localhost:8081/index.html#/async\");" -} -[5.850][INFO]: Waiting for pending navigations... -[5.850][INFO]: Done waiting for pending navigations -[5.859][INFO]: Waiting for pending navigations... -[6.112][INFO]: Done waiting for pending navigations -[6.112][INFO]: RESPONSE ExecuteScript null -[6.293][INFO]: COMMAND ExecuteScript { - "args": [ ], - "script": "return window.location.href;" -} -[6.293][INFO]: Waiting for pending navigations... -[6.293][INFO]: Done waiting for pending navigations -[6.296][INFO]: Waiting for pending navigations... -[6.296][INFO]: Done waiting for pending navigations -[6.296][INFO]: RESPONSE ExecuteScript "http://localhost:8081/index.html#/async" -[6.474][INFO]: COMMAND ExecuteAsyncScript { - "args": [ 10 ], - "script": "try { return (function (attempts, asyncCallback) {\n var callback = function(args) {\n setTimeout(function() {\n asyncCallback(args);\n }, 0);\n };\n var check = function(n) {\n try {\n ..." -} -[6.474][INFO]: Waiting for pending navigations... -[6.474][INFO]: Done waiting for pending navigations -[6.585][INFO]: Waiting for pending navigations... -[6.585][INFO]: Done waiting for pending navigations -[6.585][INFO]: RESPONSE ExecuteAsyncScript [ true, null ] -[6.658][INFO]: COMMAND ExecuteScript { - "args": [ ], - "script": "return (function () {\n angular.module('protractorBaseModule_', []).\n config(['$compileProvider', function($compileProvider) {\n if ($compileProvider.debugInfoEnabled) {\n ..." -} -[6.658][INFO]: Waiting for pending navigations... -[6.658][INFO]: Done waiting for pending navigations -[6.660][INFO]: Waiting for pending navigations... -[6.660][INFO]: Done waiting for pending navigations -[6.661][INFO]: RESPONSE ExecuteScript null -[6.824][INFO]: COMMAND ExecuteScript { - "args": [ [ "protractorBaseModule_" ] ], - "script": "angular.resumeBootstrap(arguments[0]);" -} -[6.824][INFO]: Waiting for pending navigations... -[6.824][INFO]: Done waiting for pending navigations -[6.868][INFO]: Waiting for pending navigations... -[6.868][INFO]: Done waiting for pending navigations -[6.868][INFO]: RESPONSE ExecuteScript null -[7.103][INFO]: COMMAND ExecuteAsyncScript { - "args": [ "body" ], - "script": "try { return (function (rootSelector, callback) {\n var el = document.querySelector(rootSelector);\n\n try {\n if (!window.angular) {\n throw new Error('angular could not be found on the windo..." -} -[7.103][INFO]: Waiting for pending navigations... -[7.103][INFO]: Done waiting for pending navigations -[7.312][INFO]: Waiting for pending navigations... -[7.312][INFO]: Done waiting for pending navigations -[7.312][INFO]: RESPONSE ExecuteAsyncScript null -[7.402][INFO]: COMMAND ExecuteScript { - "args": [ "slowHttpStatus", false, null, "body" ], - "script": "try { return (function (binding, exactMatch, using, rootSelector) {\n var root = document.querySelector(rootSelector || 'body');\n using = using || document;\n if (angular.getTestability) {\n ret..." -} -[7.402][INFO]: Waiting for pending navigations... -[7.402][INFO]: Done waiting for pending navigations -[7.405][INFO]: Waiting for pending navigations... -[7.405][INFO]: Done waiting for pending navigations -[7.405][INFO]: RESPONSE ExecuteScript [ { - "ELEMENT": "0.5319263362325728-1" -} ] -[7.610][INFO]: COMMAND GetElementText { - "id": "0.5319263362325728-1" -} -[7.610][INFO]: Waiting for pending navigations... -[7.610][INFO]: Done waiting for pending navigations -[7.626][INFO]: Waiting for pending navigations... -[7.626][INFO]: Done waiting for pending navigations -[7.626][INFO]: RESPONSE GetElementText "not started" -[7.731][INFO]: COMMAND ExecuteAsyncScript { - "args": [ "body" ], - "script": "try { return (function (rootSelector, callback) {\n var el = document.querySelector(rootSelector);\n\n try {\n if (!window.angular) {\n throw new Error('angular could not be found on the windo..." -} -[7.731][INFO]: Waiting for pending navigations... -[7.731][INFO]: Done waiting for pending navigations -[7.734][INFO]: Waiting for pending navigations... -[7.734][INFO]: Done waiting for pending navigations -[7.734][INFO]: RESPONSE ExecuteAsyncScript null -[7.793][INFO]: COMMAND FindElements { - "using": "css selector", - "value": "[ng-click=\"slowHttp()\"]" -} -[7.793][INFO]: Waiting for pending navigations... -[7.793][INFO]: Done waiting for pending navigations -[7.805][INFO]: Waiting for pending navigations... -[7.805][INFO]: Done waiting for pending navigations -[7.805][INFO]: RESPONSE FindElements [ { - "ELEMENT": "0.5319263362325728-2" -} ] -[7.888][INFO]: COMMAND ClickElement { - "id": "0.5319263362325728-2" -} -[7.888][INFO]: Waiting for pending navigations... -[7.888][INFO]: Done waiting for pending navigations -[7.932][INFO]: Waiting for pending navigations... -[7.932][INFO]: Done waiting for pending navigations -[7.932][INFO]: RESPONSE ClickElement -[8.138][INFO]: COMMAND ExecuteAsyncScript { - "args": [ "body" ], - "script": "try { return (function (rootSelector, callback) {\n var el = document.querySelector(rootSelector);\n\n try {\n if (!window.angular) {\n throw new Error('angular could not be found on the windo..." -} -[8.138][INFO]: Waiting for pending navigations... -[8.138][INFO]: Done waiting for pending navigations -[13.026][INFO]: Waiting for pending navigations... -[13.026][INFO]: Done waiting for pending navigations -[13.026][INFO]: RESPONSE ExecuteAsyncScript null -[13.100][INFO]: COMMAND ExecuteScript { - "args": [ "slowHttpStatus", false, null, "body" ], - "script": "try { return (function (binding, exactMatch, using, rootSelector) {\n var root = document.querySelector(rootSelector || 'body');\n using = using || document;\n if (angular.getTestability) {\n ret..." -} -[13.100][INFO]: Waiting for pending navigations... -[13.100][INFO]: Done waiting for pending navigations -[13.102][INFO]: Waiting for pending navigations... -[13.102][INFO]: Done waiting for pending navigations -[13.102][INFO]: RESPONSE ExecuteScript [ { - "ELEMENT": "0.5319263362325728-1" -} ] -[13.296][INFO]: COMMAND GetElementText { - "id": "0.5319263362325728-1" -} -[13.296][INFO]: Waiting for pending navigations... -[13.296][INFO]: Done waiting for pending navigations -[13.301][INFO]: Waiting for pending navigations... -[13.301][INFO]: Done waiting for pending navigations -[13.301][INFO]: RESPONSE GetElementText "done" \ No newline at end of file diff --git a/plugins/timeline/spec/conf.js b/plugins/timeline/spec/conf.js deleted file mode 100644 index c34cee8c2..000000000 --- a/plugins/timeline/spec/conf.js +++ /dev/null @@ -1,12 +0,0 @@ -var env = require('../../../spec/environment.js'); -var os = require('os'); - -exports.config = { - seleniumAddress: env.seleniumAddress, - specs: ['e2e.js'], - baseUrl: env.baseUrl, - plugins: [{ - path: '../index.js', - outdir: os.tmpdir() - }] -}; diff --git a/plugins/timeline/spec/e2e.js b/plugins/timeline/spec/e2e.js deleted file mode 100644 index 2a61b1748..000000000 --- a/plugins/timeline/spec/e2e.js +++ /dev/null @@ -1,14 +0,0 @@ -describe('timeline plugin', function() { - it('should do a couple basic commands', function() { - var usernameInput = element(by.model('username')); - var name = element(by.binding('username')); - - browser.get('index.html#/form'); - - expect(name.getText()).toEqual('Anon'); - - usernameInput.clear(); - usernameInput.sendKeys('Jane'); - expect(name.getText()).toEqual('Jane'); - }); -}); diff --git a/plugins/timeline/spec/standalonelog.txt b/plugins/timeline/spec/standalonelog.txt deleted file mode 100644 index 9ceaaad13..000000000 --- a/plugins/timeline/spec/standalonelog.txt +++ /dev/null @@ -1,261 +0,0 @@ -Dec 23, 2014 7:59:17 PM org.openqa.grid.selenium.GridLauncher main -INFO: Launching a standalone server -Setting system property webdriver.ie.driver to D:\selenium\IEDriverServer.exe -Setting system property webdriver.ie.driver.logfile to c:\log\iedriver.log -Setting system property webdriver.ie.driver.loglevel to DEBUG -Setting system property http.proxyHost to maki77193.miso -Setting system property http.proxyPort to 33128 -Setting system property http.nonProxyHosts to "localhost|127.0.0.1" -Setting system property https.proxyHost to maki77193.miso -Setting system property https.proxyPort to 33128 -Setting system property https.nonProxyHosts to "localhost|127.0.0.1" -19:59:17.466 INFO - Java: Oracle Corporation 24.60-b09 -19:59:17.472 INFO - OS: Windows Server 2008 R2 6.1 x86 -19:59:17.504 INFO - v2.40.0, with Core v2.40.0. Built from revision fbe29a9 -19:59:18.069 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:4443/wd/hub -19:59:18.075 INFO - Version Jetty/5.1.x -19:59:18.079 INFO - Started HttpContext[/selenium-server/driver,/selenium-server/driver] -19:59:18.080 INFO - Started HttpContext[/selenium-server,/selenium-server] -19:59:18.080 INFO - Started HttpContext[/,/] -19:59:18.210 INFO - Started org.openqa.jetty.jetty.servlet.ServletHandler@149959a -19:59:18.210 INFO - Started HttpContext[/wd,/wd] -19:59:18.220 INFO - Started SocketListener on 0.0.0.0:4443 -19:59:18.220 INFO - Started org.openqa.jetty.jetty.Server@150f0a7 -19:59:20.171 INFO - Executing: [new session: Capabilities [{count=1, browserName=internet explorer, webdriver.remote.quietExceptions=true}]] at URL: /session) -19:59:20.216 INFO - Creating a new session for Capabilities [{count=1, browserName=internet explorer, webdriver.remote.quietExceptions=true}] -Started InternetExplorerDriver server (32-bit) -2.42.0.0 -Listening on port 28134 -Log level is set to DEBUG -Log file is set to c:\log\iedriver.log -19:59:23.420 INFO - I/O exception (java.net.SocketException) caught when processing request: Software caused connection abort: recv failed -19:59:23.420 INFO - Retrying request -19:59:23.595 INFO - Done: /session -19:59:23.768 INFO - Executing: [execute script: return screen.width, []] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute) -19:59:23.855 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute -19:59:23.863 INFO - Executing: [execute script: return screen.height, []] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute) -19:59:23.907 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute -19:59:23.913 INFO - Executing: [set window position] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/window/current/position) -19:59:23.940 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/window/current/position -19:59:23.949 INFO - Executing: [set window size] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/window/current/size) -19:59:23.999 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/window/current/size -19:59:24.006 INFO - Executing: [maximise window] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/window/current/maximize) -19:59:24.049 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/window/current/maximize -19:59:24.056 INFO - Executing: [get window handles] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/window_handles) -19:59:24.060 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/window_handles -19:59:24.163 INFO - Executing: [set script timeoutt: 11000] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/timeouts/async_script) -19:59:24.209 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/timeouts/async_script -19:59:24.326 INFO - Executing: [fetching available log types] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/log/types) -19:59:24.345 WARN - Exception thrown -org.openqa.selenium.WebDriverException: Command not found: GET /session/6944190b-14c8-4d68-9822-85718b9425ea/log/types -Command duration or timeout: 6 milliseconds -Build info: version: '2.40.0', revision: 'fbe29a9', time: '2014-02-19 20:54:28' -System info: host: 'WIN-8LIIH1BGM1D', ip: '172.20.33.134', os.name: 'Windows Server 2008 R2', os.arch: 'x86', os.version: '6.1', java.version: '1.7.0_60' -Session ID: 6944190b-14c8-4d68-9822-85718b9425ea -Driver info: org.openqa.selenium.ie.InternetExplorerDriver -Capabilities [{platform=WINDOWS, javascriptEnabled=true, elementScrollBehavior=0, ignoreZoomSetting=false, enablePersistentHover=true, ie.ensureCleanSession=false, browserName=internet explorer, enableElementCacheCleanup=true, unexpectedAlertBehaviour=dismiss, version=11, ie.usePerProcessProxy=false, cssSelectorsEnabled=true, ignoreProtectedModeSettings=false, requireWindowFocus=false, handlesAlerts=true, initialBrowserUrl=http://localhost:28134/, ie.forceCreateProcessApi=false, nativeEvents=true, browserAttachTimeout=0, ie.browserCommandLineSwitches=, takesScreenshot=true}] - at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) - at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) - at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) - at java.lang.reflect.Constructor.newInstance(Unknown Source) - at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:193) - at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145) - at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:573) - at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:588) - at org.openqa.selenium.remote.RemoteExecuteMethod.execute(RemoteExecuteMethod.java:32) - at org.openqa.selenium.remote.RemoteLogs.getAvailableLogTypes(RemoteLogs.java:87) - at org.openqa.selenium.remote.server.handler.GetAvailableLogTypesHandler.call(GetAvailableLogTypesHandler.java:35) - at org.openqa.selenium.remote.server.handler.GetAvailableLogTypesHandler.call(GetAvailableLogTypesHandler.java:1) - at java.util.concurrent.FutureTask.run(Unknown Source) - at org.openqa.selenium.remote.server.DefaultSession$1.run(DefaultSession.java:170) - at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) -19:59:24.354 WARN - Exception: Command not found: GET /session/6944190b-14c8-4d68-9822-85718b9425ea/log/types -Command duration or timeout: 6 milliseconds -Build info: version: '2.40.0', revision: 'fbe29a9', time: '2014-02-19 20:54:28' -System info: host: 'WIN-8LIIH1BGM1D', ip: '172.20.33.134', os.name: 'Windows Server 2008 R2', os.arch: 'x86', os.version: '6.1', java.version: '1.7.0_60' -Session ID: 6944190b-14c8-4d68-9822-85718b9425ea -Driver info: org.openqa.selenium.ie.InternetExplorerDriver -Capabilities [{platform=WINDOWS, javascriptEnabled=true, elementScrollBehavior=0, ignoreZoomSetting=false, enablePersistentHover=true, ie.ensureCleanSession=false, browserName=internet explorer, enableElementCacheCleanup=true, unexpectedAlertBehaviour=dismiss, version=11, ie.usePerProcessProxy=false, cssSelectorsEnabled=true, ignoreProtectedModeSettings=false, requireWindowFocus=false, handlesAlerts=true, initialBrowserUrl=http://localhost:28134/, ie.forceCreateProcessApi=false, nativeEvents=true, browserAttachTimeout=0, ie.browserCommandLineSwitches=, takesScreenshot=true}] -19:59:24.599 INFO - Executing: [get: about:blank] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/url) -19:59:24.832 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/url -19:59:25.027 INFO - Executing: [execute script: window.name = "NG_DEFER_BOOTSTRAP!" + window.name;window.location.replace("http://localhost:8081/index.html#/async");, []] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute) -19:59:25.073 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute -19:59:25.288 INFO - Executing: [execute script: return window.location.href;, []] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute) -19:59:25.327 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute -19:59:25.541 INFO - Executing: [execute async script: try { return (function (attempts, asyncCallback) { - var callback = function(args) { - setTimeout(function() { - asyncCallback(args); - }, 0); - }; - var check = function(n) { - try { - if (window.angular && window.angular.resumeBootstrap) { - callback([true, null]); - } else if (n < 1) { - if (window.angular) { - callback([false, 'angular never provided resumeBootstrap']); - } else { - callback([false, 'retries looking for angular exceeded']); - } - } else { - window.setTimeout(function() {check(n - 1);}, 1000); - } - } catch (e) { - callback([false, e]); - } - }; - check(attempts); -}).apply(this, arguments); } -catch(e) { throw (e instanceof Error) ? e : new Error(e); }, [10]] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute_async) -19:59:25.613 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute_async -19:59:25.717 INFO - Executing: [execute script: return (function () { - angular.module('protractorBaseModule_', []). - config(['$compileProvider', function($compileProvider) { - if ($compileProvider.debugInfoEnabled) { - $compileProvider.debugInfoEnabled(true); - } - }]); - }).apply(null, arguments);, []] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute) -19:59:25.751 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute -19:59:25.954 INFO - Executing: [execute script: angular.resumeBootstrap(arguments[0]);, [[protractorBaseModule_]]] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute) -19:59:26.064 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute -19:59:26.560 INFO - Executing: [execute async script: try { return (function (rootSelector, callback) { - var el = document.querySelector(rootSelector); - - try { - if (!window.angular) { - throw new Error('angular could not be found on the window'); - } - if (angular.getTestability) { - angular.getTestability(el).whenStable(callback); - } else { - if (!angular.element(el).injector()) { - throw new Error('root element (' + rootSelector + ') has no injector.' + - ' this may mean it is not inside ng-app.'); - } - angular.element(el).injector().get('$browser'). - notifyWhenNoOutstandingRequests(callback); - } - } catch (err) { - callback(err.message); - } -}).apply(this, arguments); } -catch(e) { throw (e instanceof Error) ? e : new Error(e); }, [body]] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute_async) -19:59:26.614 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute_async -19:59:26.734 INFO - Executing: [execute script: try { return (function (binding, exactMatch, using, rootSelector) { - var root = document.querySelector(rootSelector || 'body'); - using = using || document; - if (angular.getTestability) { - return angular.getTestability(root). - findBindings(using, binding, exactMatch); - } - var bindings = using.getElementsByClassName('ng-binding'); - var matches = []; - for (var i = 0; i < bindings.length; ++i) { - var dataBinding = angular.element(bindings[i]).data('$binding'); - if(dataBinding) { - var bindingName = dataBinding.exp || dataBinding[0].exp || dataBinding; - if (exactMatch) { - var matcher = new RegExp('({|\\s|^|\\|)' + binding + '(}|\\s|$|\\|)'); - if (matcher.test(bindingName)) { - matches.push(bindings[i]); - } - } else { - if (bindingName.indexOf(binding) != -1) { - matches.push(bindings[i]); - } - } - - } - } - return matches; /* Return the whole array for webdriver.findElements. */ -}).apply(this, arguments); } -catch(e) { throw (e instanceof Error) ? e : new Error(e); }, [slowHttpStatus, false, null, body]] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute) -19:59:26.780 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute -19:59:26.987 INFO - Executing: [get text: 0 [org.openqa.selenium.remote.RemoteWebElement@55c8cc3e -> unknown locator]] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/element/0/text) -19:59:27.047 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/element/0/text -19:59:27.207 INFO - Executing: [execute async script: try { return (function (rootSelector, callback) { - var el = document.querySelector(rootSelector); - - try { - if (!window.angular) { - throw new Error('angular could not be found on the window'); - } - if (angular.getTestability) { - angular.getTestability(el).whenStable(callback); - } else { - if (!angular.element(el).injector()) { - throw new Error('root element (' + rootSelector + ') has no injector.' + - ' this may mean it is not inside ng-app.'); - } - angular.element(el).injector().get('$browser'). - notifyWhenNoOutstandingRequests(callback); - } - } catch (err) { - callback(err.message); - } -}).apply(this, arguments); } -catch(e) { throw (e instanceof Error) ? e : new Error(e); }, [body]] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute_async) -19:59:27.263 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute_async -19:59:27.382 INFO - Executing: [find elements: By.selector: [ng-click="slowHttp()"]] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/elements) -19:59:27.475 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/elements -19:59:27.588 INFO - Executing: [click: 1 [[InternetExplorerDriver: internet explorer on WINDOWS (6944190b-14c8-4d68-9822-85718b9425ea)] -> css selector: [ng-click="slowHttp()"]]] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/element/1/click) -19:59:27.842 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/element/1/click -19:59:28.110 INFO - Executing: [execute async script: try { return (function (rootSelector, callback) { - var el = document.querySelector(rootSelector); - - try { - if (!window.angular) { - throw new Error('angular could not be found on the window'); - } - if (angular.getTestability) { - angular.getTestability(el).whenStable(callback); - } else { - if (!angular.element(el).injector()) { - throw new Error('root element (' + rootSelector + ') has no injector.' + - ' this may mean it is not inside ng-app.'); - } - angular.element(el).injector().get('$browser'). - notifyWhenNoOutstandingRequests(callback); - } - } catch (err) { - callback(err.message); - } -}).apply(this, arguments); } -catch(e) { throw (e instanceof Error) ? e : new Error(e); }, [body]] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute_async) -19:59:32.842 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute_async -19:59:32.997 INFO - Executing: [execute script: try { return (function (binding, exactMatch, using, rootSelector) { - var root = document.querySelector(rootSelector || 'body'); - using = using || document; - if (angular.getTestability) { - return angular.getTestability(root). - findBindings(using, binding, exactMatch); - } - var bindings = using.getElementsByClassName('ng-binding'); - var matches = []; - for (var i = 0; i < bindings.length; ++i) { - var dataBinding = angular.element(bindings[i]).data('$binding'); - if(dataBinding) { - var bindingName = dataBinding.exp || dataBinding[0].exp || dataBinding; - if (exactMatch) { - var matcher = new RegExp('({|\\s|^|\\|)' + binding + '(}|\\s|$|\\|)'); - if (matcher.test(bindingName)) { - matches.push(bindings[i]); - } - } else { - if (bindingName.indexOf(binding) != -1) { - matches.push(bindings[i]); - } - } - - } - } - return matches; /* Return the whole array for webdriver.findElements. */ -}).apply(this, arguments); } -catch(e) { throw (e instanceof Error) ? e : new Error(e); }, [slowHttpStatus, false, null, body]] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute) -19:59:33.035 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/execute -19:59:33.265 INFO - Executing: [get text: 0 [org.openqa.selenium.remote.RemoteWebElement@55c8cc3e -> unknown locator]] at URL: /session/c163949d-96b2-44e0-9d06-653a863a4a90/element/0/text) -19:59:33.354 INFO - Done: /session/c163949d-96b2-44e0-9d06-653a863a4a90/element/0/text \ No newline at end of file diff --git a/plugins/timeline/spec/unit.js b/plugins/timeline/spec/unit.js deleted file mode 100644 index d1d42f8fc..000000000 --- a/plugins/timeline/spec/unit.js +++ /dev/null @@ -1,124 +0,0 @@ -var fs = require('fs'); -var path = require('path'); -var TimelinePlugin = require('../index.js').TimelinePlugin; - -describe('timeline plugin', function() { - it('should parse an example selenium standalone log', function() { - var timeline = TimelinePlugin.parseTextLog( - fs.readFileSync(path.join(__dirname, 'standalonelog.txt')).toString()); - - expect(timeline.length).toEqual(23); - expect(timeline[0].command).toEqual('new session'); - expect(timeline[0].duration).toEqual(3424); - }); - - it('should parse an example chromedriver log', function() { - var timeline = TimelinePlugin.parseTextLog( - fs.readFileSync(path.join(__dirname, 'chromelog.txt')).toString()); - - expect(timeline.length).toEqual(24); - expect(timeline[0].command).toEqual('InitSession'); - expect(timeline[0].duration).toEqual(1781); - }); - - it('should parse example selenium client logs', function() { - var clientLog = [{ - level: { value: 800, name: 'INFO' }, - message: 'org.openqa.selenium.remote.server.DriverServlet org.openqa.selenium.remote.server.rest.ResultConfig.handle Executing: [click: 1 [[SafariDriver: safari on MAC (null)] -> css selector: [ng-click="slowHttp()"]]] at URL: /session/b057191b-6328-4c7b-bdd2-170ba79280af/element/1/click)', - timestamp: 1419031697443, - type: '' - }, { level: { value: 800, name: 'INFO' }, - message: 'org.openqa.selenium.remote.server.DriverServlet org.openqa.selenium.remote.server.rest.ResultConfig.handle Done: /session/b057191b-6328-4c7b-bdd2-170ba79280af/element/1/click', - timestamp: 1419031697470, - type: '' - }, { level: { value: 800, name: 'INFO' }, - message: 'org.openqa.selenium.remote.server.DriverServlet org.openqa.selenium.remote.server.rest.ResultConfig.handle Executing: [execute async script: try { return (function (rootSelector, callback) {\n var el = document.querySelector(rootSelector);\n\n try {\n if (!window.angular) {\n throw new Error(\'angular could not be found on the window\');\n }\n if (angular.getTestability) {\n angular.getTestability(el).whenStable(callback);\n } else {\n if (!angular.element(el).injector()) {\n throw new Error(\'root element (\' + rootSelector + \') has no injector.\' +\n \' this may mean it is not inside ng-app.\');\n }\n angular.element(el).injector().get(\'$browser\').\n notifyWhenNoOutstandingRequests(callback);\n }\n } catch (err) {\n callback(err.message);\n }\n}).apply(this, arguments); }\ncatch(e) { throw (e instanceof Error) ? e : new Error(e); }, [body]] at URL: /session/b057191b-6328-4c7b-bdd2-170ba79280af/execute_async)', - timestamp: 1419031697672, - type: '' - }, { level: { value: 800, name: 'INFO' }, - message: 'org.openqa.selenium.remote.server.DriverServlet org.openqa.selenium.remote.server.rest.ResultConfig.handle Done: /session/b057191b-6328-4c7b-bdd2-170ba79280af/execute_async', - timestamp: 1419031702495, - type: '' - }, { level: { value: 800, name: 'INFO' }, - message: 'org.openqa.selenium.remote.server.DriverServlet org.openqa.selenium.remote.server.rest.ResultConfig.handle Executing: [execute script: try { return (function (binding, exactMatch, using, rootSelector) {\n var root = document.querySelector(rootSelector || \'body\');\n using = using || document;\n if (angular.getTestability) {\n return angular.getTestability(root).\n findBindings(using, binding, exactMatch);\n }\n var bindings = using.getElementsByClassName(\'ng-binding\');\n var matches = [];\n for (var i = 0; i < bindings.length; ++i) {\n var dataBinding = angular.element(bindings[i]).data(\'$binding\');\n if(dataBinding) {\n var bindingName = dataBinding.exp || dataBinding[0].exp || dataBinding;\n if (exactMatch) {\n var matcher = new RegExp(\'({|\\\\s|^|\\\\|)\' + binding + \'(}|\\\\s|$|\\\\|)\');\n if (matcher.test(bindingName)) {\n matches.push(bindings[i]);\n }\n } else {\n if (bindingName.indexOf(binding) != -1) {\n matches.push(bindings[i]);\n }\n }\n \n }\n }\n return matches; /* Return the whole array for webdriver.findElements. */\n}).apply(this, arguments); }\ncatch(e) { throw (e instanceof Error) ? e : new Error(e); }, [slowHttpStatus, false, null, body]] at URL: /session/b057191b-6328-4c7b-bdd2-170ba79280af/execute)', - timestamp: 1419031702585, - type: '' - }, { level: { value: 800, name: 'INFO' }, - message: 'org.openqa.selenium.remote.server.DriverServlet org.openqa.selenium.remote.server.rest.ResultConfig.handle Done: /session/b057191b-6328-4c7b-bdd2-170ba79280af/execute', - timestamp: 1419031702608, - type: '' - }, { level: { value: 800, name: 'INFO' }, - message: 'org.openqa.selenium.remote.server.DriverServlet org.openqa.selenium.remote.server.rest.ResultConfig.handle Executing: [get text: 0 [org.openqa.selenium.remote.RemoteWebElement@2a868887 -> unknown locator]] at URL: /session/b057191b-6328-4c7b-bdd2-170ba79280af/element/0/text)', - timestamp: 1419031702795, - type: '' - }, { level: { value: 800, name: 'INFO' }, - message: 'org.openqa.selenium.remote.server.DriverServlet org.openqa.selenium.remote.server.rest.ResultConfig.handle Done: /session/b057191b-6328-4c7b-bdd2-170ba79280af/element/0/text', - timestamp: 1419031702812, - type: '' - }]; - var timeline = TimelinePlugin.parseArrayLog(clientLog); - - expect(timeline.length).toEqual(4); - expect(timeline[0].command).toEqual('click'); - expect(timeline[0].duration).toEqual(1419031697470 - 1419031697443); - }); - - it('should align chrome logs', function() { - var chromeLog = - '[1.000][INFO]: COMMAND SetScriptTimeout {\n' + - ' "ms": 11000\n' + - '}\n' + - '[1.000][INFO]: RESPONSE SetScriptTimeout\n' + - '[4.000][INFO]: COMMAND GetElementText {\n' + - ' "id": "0.5319263362325728-1"\n' + - '}\n' + - '[5.000][INFO]: RESPONSE GetElementText "not started"\n'; - var timeline = TimelinePlugin.parseTextLog(chromeLog, 'chrome logs', 90000); - expect(timeline.length).toEqual(2); - expect(timeline[1].source).toEqual('chrome logs'); - expect(timeline[1].start).toEqual(93000); - expect(timeline[1].end).toEqual(94000); - }); - - it('should align selenium standalone logs', function() { - var clientLog = - 'INFO: Launching a standalone server\n' + - '01:40:01.0000 INFO - Executing: [set script timeoutt: 5] at URL: /abc)\n' + - '01:40:02.0000 INFO - Done: /abc\n' + - '01:40:04.0000 INFO - Executing: [get text: 0 [elem -> unknown locator]] at URL: /abc)\n' + - '01:40:05.0000 INFO - Done: /abc\n'; - - var timeline = TimelinePlugin.parseTextLog(clientLog, 'standalone log', 90000); - expect(timeline.length).toEqual(2); - expect(timeline[1].source).toEqual('standalone log'); - expect(timeline[1].start).toEqual(93000); - expect(timeline[1].end).toEqual(94000); - }); - - it('should align selenium client logs', function() { - var clientLog = [{ - level: { value: 800, name: 'INFO' }, - message: 'foo.bar Executing: [set script timeout: 1]', - timestamp: 111000, - type: '' - }, { level: { value: 800, name: 'INFO' }, - message: 'foo.bar Done: [set script timeout: 1]', - timestamp: 112000, - type: '' - }, { level: { value: 800, name: 'INFO' }, - message: 'foo.bar Executing: [get text: 0 [elemid -> unknown locator]]', - timestamp: 114000, - type: '' - }, { level: { value: 800, name: 'INFO' }, - message: 'foo.bar Done: [get text: 0 [elemid -> unknown locator]]', - timestamp: 115000, - type: '' - }]; - var timeline = TimelinePlugin.parseArrayLog(clientLog, 'client log', 90000); - - expect(timeline.length).toEqual(2); - expect(timeline[1].source).toEqual('client log'); - expect(timeline[1].start).toEqual(93000); - expect(timeline[1].end).toEqual(94000); - }); -}); diff --git a/scripts/test.js b/scripts/test.js index d056ac8ce..3ae550d6b 100755 --- a/scripts/test.js +++ b/scripts/test.js @@ -37,12 +37,6 @@ var passingTests = [ 'node scripts/interactive_tests/with_base_url.js', // Unit tests 'node node_modules/.bin/jasmine JASMINE_CONFIG_PATH=scripts/unit_test.json', - // Plugins - 'node lib/cli.js plugins/timeline/spec/conf.js', - 'node lib/cli.js plugins/ngHint/spec/successConfig.js', - 'node lib/cli.js plugins/accessibility/spec/successConfig.js', - 'node lib/cli.js plugins/console/spec/consolePassConfig.js', - 'node lib/cli.js plugins/console/spec/consolePassLogWarnings.js' ]; var executor = new Executor(); @@ -133,73 +127,4 @@ executor.addCommandlineTest('node lib/cli.js spec/errorTest/slowHttpAndTimeoutCo {message: '^((?!The following tasks were pending).)*$'} ]); -// Check ngHint plugin - -executor.addCommandlineTest( - 'node lib/cli.js plugins/ngHint/spec/failureConfig.js') - .expectExitCode(1) - .expectErrors([{ - message: 'warning -- ngHint plugin cannot be run as ngHint code was ' + - 'never included into the page' - }, { - message: 'warning -- ngHint is included on the page, but is not active ' + - 'because there is no `ng-hint` attribute present' - }, { - message: 'warning -- Module "xApp" was created but never loaded.' - }]); - -// Check accessibility plugin - -executor.addCommandlineTest( - 'node lib/cli.js plugins/accessibility/spec/failureConfig.js') - .expectExitCode(1) - .expectErrors([{ - message: '3 elements failed:' - }, - { - message: '1 element failed:' - }]); - -// Check console plugin - -executor.addCommandlineTest( - 'node lib/cli.js plugins/console/spec/consoleFailConfig.js') - .expectExitCode(1) - .expectErrors([ - {message: 'This is a test warning'}, - {message: 'This is a test error'}, - {message: 'This should be filtered out by string'}, - {message: 'This should be filtered out by regex'} - ]); - -executor.addCommandlineTest( - 'node lib/cli.js plugins/console/spec/consoleFailErrorConfig.js') - .expectExitCode(1) - .expectErrors([ - {message: 'This is a test error'}, - {message: 'This should be filtered out by string'}, - {message: 'This should be filtered out by regex'} - ]); - -executor.addCommandlineTest( - 'node lib/cli.js plugins/console/spec/consoleFailWarningConfig.js') - .expectExitCode(1) - .expectErrors([ - {message: 'This is a test warning'} - ]); - -executor.addCommandlineTest( - 'node lib/cli.js plugins/console/spec/consoleFailFilterConfig.js') - .expectExitCode(1) - .expectErrors([ - {message: 'This is a test error'} - ]); - -executor.addCommandlineTest( - 'node lib/cli.js plugins/console/spec/consoleFailLogWarnings.js') - .expectExitCode(1) - .expectErrors([ - {message: 'This is a test warning'} - ]); - executor.execute(); diff --git a/scripts/unit_test.json b/scripts/unit_test.json index c3ff16f47..aa5e7bacd 100644 --- a/scripts/unit_test.json +++ b/scripts/unit_test.json @@ -2,7 +2,6 @@ "spec_dir": "", "spec_files": [ "spec/unit/*.js", - "website/docgen/spec/*.js", - "plugins/timeline/spec/unit.js" + "website/docgen/spec/*.js" ] } diff --git a/testapp/accessibility/badMarkup.html b/testapp/accessibility/badMarkup.html deleted file mode 100644 index b3df2808b..000000000 --- a/testapp/accessibility/badMarkup.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - Angular.js Example - - - - - - First name: -
    - Last name: -
    - Hello {{firstName}} {{lastName}} - - - - diff --git a/testapp/accessibility/index.html b/testapp/accessibility/index.html deleted file mode 100644 index 57fc37f03..000000000 --- a/testapp/accessibility/index.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - Angular.js Example - - - - - - - -
    - - -
    - Hello {{firstName}} {{lastName}} - Firstname Lastname - - diff --git a/testapp/console/index.html b/testapp/console/index.html deleted file mode 100644 index b5b71ef58..000000000 --- a/testapp/console/index.html +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - Angular.js Example - - - - - - - - - - diff --git a/testapp/ngHint/index.html b/testapp/ngHint/index.html deleted file mode 100644 index 4a4d02260..000000000 --- a/testapp/ngHint/index.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - Angular.js Example - - - - - - - First name: -
    - Last name: -
    - Hello {{firstName}} {{lastName}} - - diff --git a/testapp/ngHint/ngHint.js b/testapp/ngHint/ngHint.js deleted file mode 100644 index 0bc080a40..000000000 --- a/testapp/ngHint/ngHint.js +++ /dev/null @@ -1,2180 +0,0 @@ -(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.logMessage('General', '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' -]; - -function flush() { - var log = angular.hint.flush(), - groups = Object.keys(log); - - groups.forEach(function (groupName) { - var group = log[groupName]; - var header = 'Angular Hint: ' + groupName; - - console.groupCollapsed ? - console.groupCollapsed(header) : - console.log(header); - - LEVELS.forEach(function (level) { - group[level] && logGroup(group[level], title(level)); - }); - console.groupEnd && console.groupEnd(); - }); -} - -setInterval(flush, 2) - -angular.hint.onMessage = function () { - setTimeout(flush, 2); -}; - -function logGroup(group, type) { - console.group ? console.group(type) : console.log(type); - for(var i = 0, ii = group.length; i < ii; i++) { - console.log(group[i]); - } - console.group && console.groupEnd(); -} - -},{"angular-hint-controllers":2,"angular-hint-directives":3,"angular-hint-events":38,"angular-hint-log":47,"angular-hint-modules":48,"angular-hint-scopes":66}],2:[function(require,module,exports){ -'use strict'; - -var nameToControllerMatch = {}, - controllers = {}, - hintLog = angular.hint = require('angular-hint-log'), - MODULE_NAME = 'Controllers', - SEVERITY_ERROR = 1, - SEVERITY_WARNING = 2; - -/** -* Decorates $controller with a patching function to -* log a message if the controller is instantiated on the window -*/ -angular.module('ngHintControllers', []). - config(function ($provide) { - $provide.decorator('$controller', function($delegate) { - return function(ctrl, locals) { - //If the controller name is passed, find the controller than matches it - if(typeof ctrl === 'string') { - if(nameToControllerMatch[ctrl]) { - ctrl = nameToControllerMatch[ctrl]; - } else { - //If the controller function cannot be found, check for it on the window - checkUppercaseName(ctrl); - checkControllerInName(ctrl); - ctrl = window[ctrl] || ctrl; - if(typeof ctrl === 'string') { - throw new Error('The controller function for ' + ctrl + ' could not be found.' + - ' Is the function registered under that name?'); - } - } - } - locals = locals || {}; - //If the controller is not in the list of already registered controllers - //and it is not connected to the local scope, it must be instantiated on the window - if(!controllers[ctrl] && (!locals.$scope || !locals.$scope[ctrl]) && - ctrl.toString().indexOf('@name ngModel.NgModelController#$render') === -1 && - ctrl.toString().indexOf('@name form.FormController') === -1) { - if(angular.version.minor <= 2) { - hintLog.logMessage(MODULE_NAME, 'It is against Angular best practices to ' + - 'instantiate a controller on the window. This behavior is deprecated in Angular' + - ' 1.3.0', SEVERITY_WARNING); - } else { - hintLog.logMessage(MODULE_NAME, 'Global instantiation of controllers was deprecated' + - ' in Angular 1.3.0. Define the controller on a module.', SEVERITY_ERROR); - } - } - var ctrlInstance = $delegate.apply(this, [ctrl, locals]); - return ctrlInstance; - }; - }); -}); - -/** -* 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 checkUppercaseName(controllerName) { - var firstLetter = controllerName.charAt(0); - if(firstLetter !== firstLetter.toUpperCase() && firstLetter === firstLetter.toLowerCase()) { - hintLog.logMessage(MODULE_NAME, 'The best practice is to name controllers with an' + - ' uppercase first letter. Check the name of \'' + controllerName + '\'.', SEVERITY_WARNING); - } -} - -function checkControllerInName(controllerName) { - var splitName = controllerName.split('Controller'); - if(splitName.length === 1 || splitName[splitName.length - 1] !== '') { - hintLog.logMessage(MODULE_NAME, 'The best practice is to name controllers ending with ' + - '\'Controller\'. Check the name of \'' + controllerName + '\'.', SEVERITY_WARNING); - } -} - -angular.module = function() { - var module = originalModule.apply(this, arguments), - originalController = module.controller; - module.controller = function(controllerName, controllerConstructor) { - nameToControllerMatch[controllerName] = controllerConstructor; - controllers[controllerConstructor] = controllerConstructor; - checkUppercaseName(controllerName); - checkControllerInName(controllerName); - return originalController.apply(this, arguments); - }; - return module; -}; - -},{"angular-hint-log":47}],3:[function(require,module,exports){ -'use strict'; - -var ddLibData = require('./lib/ddLib-data'); - -var RESTRICT_REGEXP = /restrict\s*:\s*['"](.+?)['"]/; -var customDirectives = []; -var dasherize = require('dasherize'); -var search = require('./lib/search'); -var checkPrelimErrors = require('./lib/checkPrelimErrors'); -var getKeysAndValues = require('./lib/getKeysAndValues'); -var defaultDirectives = ddLibData.directiveTypes['angular-default-directives'].directives; -var htmlDirectives = ddLibData.directiveTypes['html-directives'].directives; - -angular.module('ngHintDirectives', []) - .config(['$provide', function($provide) { - $provide.decorator('$compile', ['$delegate', function($delegate) { - return function(elem) { - elem = angular.element(elem); - for(var i = 0, length = elem.length; i < length; i+=2) { - if(elem[i].getElementsByTagName) { - var toSend = Array.prototype.slice.call(elem[i].getElementsByTagName('*')); - search(toSend, customDirectives); - } - } - return $delegate.apply(this, arguments); - }; - }]); - }]); - -function supportObject(directiveObject) { - if(typeof directiveObject === 'object') { - var keys = Object.keys(directiveObject); - for(var i = keys.length - 1; i >= 0; i--) { - if(typeof directiveObject[keys[i]] === 'function') { - return directiveObject[keys[i]]; - } - } - } - return function() {}; -} - -var originalAngularModule = angular.module; -angular.module = function() { - var module = originalAngularModule.apply(this, arguments); - var originalDirective = module.directive; - module.directive = function(directiveName, directiveFactory) { - directiveFactory = directiveFactory || supportObject(directiveName); - directiveName = typeof directiveName === 'string' ? directiveName : Object.keys(directiveName)[0]; - - var originalDirectiveFactory = typeof directiveFactory === 'function' ? directiveFactory : - directiveFactory[directiveFactory.length - 1]; - - var factoryStr = originalDirectiveFactory.toString(); - - checkPrelimErrors(directiveName, factoryStr); - - var pairs = getKeysAndValues(factoryStr); - pairs.map(function(pair) { - customDirectives.push(pair); - }); - - var matchRestrict = factoryStr.match(RESTRICT_REGEXP); - var restrict = (matchRestrict && matchRestrict[1]) || 'A'; - var directive = { - directiveName: directiveName, - restrict: restrict, - require: pairs - }; - - customDirectives.push(directive); - - return originalDirective.apply(this, arguments); - }; - return module; -}; - -},{"./lib/checkPrelimErrors":16,"./lib/ddLib-data":17,"./lib/getKeysAndValues":24,"./lib/search":32,"dasherize":34}],4:[function(require,module,exports){ -/** - *@param s: first string to compare - *@param t: second string to compare - * - *@description: - *Checks to see if two strings are similiar enough to even bother checking the Levenshtein Distance. - */ -module.exports = function(s, t) { - var strMap = {}, similarities = 0, STRICTNESS = 0.66; - if(Math.abs(s.length - t.length) > 3) { - return false; - } - s.split('').forEach(function(x){strMap[x] = x;}); - for (var i = t.length - 1; i >= 0; i--) { - similarities = strMap[t.charAt(i)] ? similarities + 1 : similarities; - } - return similarities >= t.length * STRICTNESS; -}; - -},{}],5:[function(require,module,exports){ -var ddLibData = require('./ddLib-data'); - -/** - *@param attribute: attribute name as string e.g. 'ng-click', 'width', 'src', etc. - *@param options: {} options object from beginSearch. - * - *@description attribute exsistance in the types of directives/attibutes (html, angular core, and - * angular custom) and checks the restrict property of values matches its use. - * - *@return {} with attribute exsistance and wrong use e.g. restrict property set to elements only. - **/ -module.exports = function(attribute, options) { - var anyTrue = false, - wrongUse = '', - directive, - restrictProp; - - options.directiveTypes.forEach(function(dirType) { - var isTag = attribute.charAt(0) === '*'; - var isCustomDir = dirType === 'angular-custom-directives'; - if(!isTag) { - directive = ddLibData.directiveTypes[dirType].directives[attribute] || ''; - restrictProp = directive.restrict || directive; - if(restrictProp) { - if(restrictProp.indexOf('E') > -1 && restrictProp.indexOf('A') < 0) { - wrongUse = 'element'; - } - if(restrictProp.indexOf('C') > -1 && restrictProp.indexOf('A') < 0) { - wrongUse = (wrongUse) ? 'element and class' : 'class'; - } - anyTrue = anyTrue || true; - } - } - else if(isTag && isCustomDir){ - directive = ddLibData.directiveTypes[dirType].directives[attribute.substring(1)] || ''; - restrictProp = directive.restrict || directive; - anyTrue = anyTrue || true; - if(restrictProp && restrictProp.indexOf('A') > -1 && restrictProp.indexOf('E') < 0) { - wrongUse = 'attribute'; - } - } - }); - var typeError = wrongUse? 'wronguse' : '' || !anyTrue ? 'nonexsisting' : '' || ''; - return {exsists: anyTrue, wrongUse: wrongUse, typeError: typeError}; -}; - -},{"./ddLib-data":17}],6:[function(require,module,exports){ -var ddLibData = require('./ddLib-data'), - SEVERITY_ERROR = 1; - -module.exports = function(info, id, type) { - var message = ddLibData.directiveTypes[info.directiveType].message + type + ' element' + id + '. '; - var error = info.error; - error = (error.charAt(0) === '*') ? error.substring(1): error; - message += 'Found deprecated directive "' + error + '". Use an alternative solution.'; - return [message, SEVERITY_ERROR]; -}; - -},{"./ddLib-data":17}],7:[function(require,module,exports){ -var SEVERITY_ERROR = 1; - -module.exports = function(info, id, type) { - var missingLength = info.missing.length; - var s = missingLength === 1 ? ' ' : 's '; - var waswere = missingLength === 1 ? 'is ' : 'are '; - var missing = ''; - info.missing.forEach(function(str){ - missing += '"' + str + '",'; - }); - missing = '[' + missing.substring(0, missing.length-1) + '] '; - var message = 'Attribute' + s + missing + waswere + 'missing in ' + type + ' element' + id + '.'; - return [message, SEVERITY_ERROR]; -}; - -},{}],8:[function(require,module,exports){ -var isMutExclusiveDir = require('./isMutExclusiveDir'), - SEVERITY_ERROR = 1; - -module.exports = function(info, id, type) { - var pair = isMutExclusiveDir(info.error); - var message = 'Angular attributes "'+info.error+'" and "'+pair+'" in '+type+ ' element'+id+ - ' should not be attributes together on the same HTML element'; - return [message, SEVERITY_ERROR]; -}; - -},{"./isMutExclusiveDir":29}],9:[function(require,module,exports){ -var hintLog = require('angular-hint-log'), - MODULE_NAME = 'Directives', - SEVERITY_SUGGESTION = 3; - -module.exports = function(directiveName) { - var message = 'Directive "'+directiveName+'" should have proper namespace try adding a prefix'+ - ' and/or using camelcase.'; - var domElement = '<'+directiveName+'> '; - hintLog.logMessage(MODULE_NAME, message, SEVERITY_SUGGESTION); -}; - -},{"angular-hint-log":47}],10:[function(require,module,exports){ -var SEVERITY_SUGGESTION = 3; - -module.exports = function(info, id, type) { - var ngDir = 'ng-' + info.error.substring(2), - message = 'Use Angular version of "' + info.error + '" in ' + type + ' element' + id + - '. Try: "' + ngDir + '"'; - return [message, SEVERITY_SUGGESTION]; -}; - -},{}],11:[function(require,module,exports){ -var SEVERITY_ERROR = 1; -module.exports = function(info, id, type) { - var message = 'ngRepeat in '+type+' element'+id+' was used incorrectly. '+info.suggestion; - return [message, SEVERITY_ERROR]; -}; - -},{}],12:[function(require,module,exports){ -var ddLibData = require('./ddLib-data'), - SEVERITY_ERROR = 1; - -module.exports = function(info, id, type) { - var message = ddLibData.directiveTypes[info.directiveType].message + type + ' element' + id + '. '; - var error = (info.error.charAt(0) === '*') ? info.error.substring(1): info.error; - message += 'Found incorrect attribute "' + error + '" try "' + info.match + '".'; - return [message, SEVERITY_ERROR]; -}; - -},{"./ddLib-data":17}],13:[function(require,module,exports){ -var hintLog = angular.hint = require('angular-hint-log'), - MODULE_NAME = 'Directives', - SEVERITY_ERROR = 1; - -module.exports = function(directiveName) { - var message = 'The use of "replace" in directive factories is deprecated,'+ - ' and it was found in "' + directiveName + '".'; - var domElement = '<' + directiveName + '> '; - hintLog.logMessage(MODULE_NAME, message, SEVERITY_ERROR); -}; - -},{"angular-hint-log":47}],14:[function(require,module,exports){ -var ddLibData = require('./ddLib-data'), - SEVERITY_ERROR = 1; - -module.exports = function(info, id, type) { - var message = ddLibData.directiveTypes[info.directiveType].message + type + ' element' + - id + '. ', - error = (info.error.charAt(0) === '*') ? info.error.substring(1): info.error, - aecmType = (info.wrongUse.indexOf('attribute') > -1)? 'Element' : 'Attribute'; - message += aecmType + ' name "' + error + '" is reserved for ' + info.wrongUse + ' names only.'; - return [message, SEVERITY_ERROR]; -}; - -},{"./ddLib-data":17}],15:[function(require,module,exports){ - -module.exports = function(attrVal){ - var suggestion, - error = false, - TRACK_REGEXP = /track\s+by\s+\S*/, - FILTER_REGEXP = /filter\s*:\s*\w+(?:\.\w+)*/; - var trackMatch = attrVal.match(TRACK_REGEXP); - var filterMatch = attrVal.match(FILTER_REGEXP); - var breakIndex = attrVal.indexOf('|') > -1 ? attrVal.indexOf('|') : Infinity; - - if(!trackMatch && filterMatch && breakIndex === Infinity) { - return 'Try: " | '+filterMatch[0]+'"'; - } - - if(trackMatch && filterMatch) { - var trackInd = attrVal.indexOf(trackMatch[0]); - var filterInd = attrVal.indexOf(filterMatch[0]); - if(!(breakIndex < filterInd && filterInd < trackInd)) { - return 'Try: " | '+filterMatch[0]+' '+trackMatch[0]+'"'; - } - } -} -},{}],16:[function(require,module,exports){ -var hasNameSpace = require('./hasNameSpace'); -var buildNameSpace = require('./buildNameSpace'); -var hasReplaceOption = require('./hasReplaceOption'); -var buildReplaceOption = require('./buildReplaceOption'); - -module.exports = function(dirName, dirFacStr) { - if (!hasNameSpace(dirName)) { - buildNameSpace(dirName); - } - if (hasReplaceOption(dirFacStr)) { - buildReplaceOption(dirName); - } -}; - -},{"./buildNameSpace":9,"./buildReplaceOption":13,"./hasNameSpace":27,"./hasReplaceOption":28}],17:[function(require,module,exports){ -module.exports = { - directiveTypes : { - 'html-directives': { - message: 'There was an HTML error in ', - directives: { - 'abbr' : 'A', - 'accept': 'A', - 'accesskey': 'A', - 'action': 'A', - 'align': 'A', - 'alt': 'A', - 'async': 'A', - 'background': 'A', - 'bgcolor': 'A', - 'border': 'A', - 'cellpadding': 'A', - 'char': 'A', - 'charoff': 'A', - 'charset': 'A', - 'checked': 'A', - 'cite': 'A', - 'class': 'A', - 'classid': 'A', - 'code': 'A', - 'codebase': 'A', - 'color': 'A', - 'cols': 'A', - 'colspan': 'A', - 'content': 'A', - 'data': 'A', - 'defer': 'A', - 'dir': 'A', - 'face': 'A', - 'for': 'A', - 'frame': 'A', - 'frameborder': 'A', - 'headers': 'A', - 'height': 'A', - 'http-equiv': 'A', - 'href': 'A', - 'id': 'A', - 'label': 'A', - 'lang': 'A', - 'language': 'A', - 'link': 'A', - 'marginheight': 'A', - 'marginwidth': 'A', - 'maxlength': 'A', - 'media': 'A', - 'multiple': 'A', - 'name': 'A', - 'object': '!A', - 'onblur': '!A', - 'onchange': '!A', - 'onclick': '!A', - 'onfocus': '!A', - 'onkeydown': '!A', - 'onkeypress': '!A', - 'onkeyup': '!A', - 'onload': '!A', - 'onmousedown': '!A', - 'onmousemove': '!A', - 'onmouseout': '!A', - 'onmouseover': '!A', - 'onmouseup': '!A', - 'onreset': '!A', - 'onselect': '!A', - 'onsubmit': '!A', - 'property': 'A', - 'readonly': 'A', - 'rel': 'A', - 'rev': 'A', - 'role': 'A', - 'rows': 'A', - 'rowspan': 'A', - 'size': 'A', - 'span': 'EA', - 'src': 'A', - 'start': 'A', - 'style': 'A', - 'text': 'A', - 'target': 'A', - 'title': 'A', - 'type': 'A', - 'value': 'A', - 'width': 'A' - } - }, - 'angular-default-directives': { - message: 'There was an AngularJS error in ', - directives: { - 'count': 'A', - 'min': 'A', - 'max': 'A', - 'ng-app': 'A', - 'ng-bind': 'A', - 'ng-bindhtml': 'A', - 'ng-bindtemplate': 'A', - 'ng-blur': 'A', - 'ng-change': 'A', - 'ng-checked': 'A', - 'ng-class': 'A', - 'ng-classeven': 'A', - 'ng-classodd': 'A', - 'ng-click': 'A', - 'ng-cloak': 'A', - 'ng-controller': 'A', - 'ng-copy': 'A', - 'ng-csp': 'A', - 'ng-cut': 'A', - 'ng-dblclick': 'A', - 'ng-disabled': 'A', - 'ng-dirty': 'A', - 'ng-focus': 'A', - 'ng-form': 'A', - 'ng-hide': 'A', - 'ng-hint': 'A', - 'ng-hint-exclude': 'A', - 'ng-hint-include': 'A', - 'ng-href': 'A', - 'ng-if': 'A', - 'ng-include': 'A', - 'ng-init': 'A', - 'ng-invalid': 'A', - 'ng-keydown': 'A', - 'ng-keypress': 'A', - 'ng-keyup': 'A', - 'ng-list': 'A', - 'ng-maxlength': 'A', - 'ng-minlength': 'A', - 'ng-model': 'A', - 'ng-model-options': 'A', - 'ng-mousedown': 'A', - 'ng-mouseenter': 'A', - 'ng-mouseleave': 'A', - 'ng-mousemove': 'A', - 'ng-mouseover': 'A', - 'ng-mouseup': 'A', - 'ng-nonbindable': 'A', - 'ng-open': 'A', - 'ng-options': 'A', - 'ng-paste': 'A', - 'ng-pattern': 'A', - 'ng-pluralize': 'A', - 'ng-pristine': 'A', - 'ng-readonly': 'A', - 'ng-repeat': 'A', - 'ng-repeat-start': 'A', - 'ng-repeat-end': 'A', - 'ng-required': 'A', - 'ng-selected': 'A', - 'ng-show': 'A', - 'ng-src': 'A', - 'ng-srcset': 'A', - 'ng-style': 'A', - 'ng-submit': 'A', - 'ng-switch': 'A', - 'ng-switch-when': 'A', - 'ng-transclude': 'A', - 'ng-true-value': 'A', - 'ng-trim': 'A', - 'ng-false-value': 'A', - 'ng-value': 'A', - 'ng-valid': 'A', - 'ng-view': 'A', - 'required': 'A', - 'when': 'A' - } - }, - 'angular-custom-directives': { - message: 'There was an AngularJS error in ', - directives: {} - }, - 'angular-deprecated-directives': { - message: 'There was an AngularJS error in ', - directives: { - 'ng-bind-html-unsafe': 'deprecated' - } - } - } -}; - -},{}],18:[function(require,module,exports){ -var areSimilarEnough = require('./areSimilarEnough'); -var levenshteinDistance = require('./levenshtein'); - -/** - *@param directiveTypeData: {} with list of directives/attributes and - *their respective restrict properties. - *@param attribute: attribute name as string e.g. 'ng-click', 'width', 'src', etc. - * - *@return {} with Levenshtein Distance and name of the closest match to given attribute. - **/ -module.exports = function(directiveTypeData, attribute) { - if(typeof attribute !== 'string') { - throw new Error('Function must be passed a string as second parameter.'); - } - if((directiveTypeData === null || directiveTypeData === undefined) || - typeof directiveTypeData !== 'object') { - throw new Error('Function must be passed a defined object as first parameter.'); - } - var min_levDist = Infinity, - closestMatch = ''; - - for(var directive in directiveTypeData){ - if(min_levDist !== 1 && areSimilarEnough(attribute,directive)) { - var currentlevDist = levenshteinDistance(attribute, directive); - closestMatch = (currentlevDist < min_levDist)? directive : closestMatch; - min_levDist = (currentlevDist < min_levDist)? currentlevDist : min_levDist; - } - } - return {min_levDist: min_levDist, match: closestMatch}; -}; - -},{"./areSimilarEnough":4,"./levenshtein":30}],19:[function(require,module,exports){ - -var getFailedAttributesOfElement = require('./getFailedAttributesOfElement'); - -module.exports = function(scopeElements, options) { - return scopeElements.map(getFailedAttributesOfElement.bind(null, options)) - .filter(function(x) {return x;}); -}; - -},{"./getFailedAttributesOfElement":23}],20:[function(require,module,exports){ -var ddLibData = require('./ddLib-data'); - -module.exports = function(dirName, attributes) { - attributes = attributes.map(function(x){return x.nodeName;}); - var directive = ddLibData.directiveTypes['angular-custom-directives'].directives[dirName]; - var missing = []; - if (directive && directive.require) { - for (var i = 0, length = directive.require.length; i < length; i++) { - var dirName = directive.require[i].directiveName; - if (attributes.indexOf(dirName) < 0) { - missing.push(dirName); - } - } - } - return missing; -}; - -},{"./ddLib-data":17}],21:[function(require,module,exports){ -var hintLog = angular.hint = require('angular-hint-log'), - MODULE_NAME = 'Directives'; - -var build = { - deprecated: require('./buildDeprecated'), - missingrequired: require('./buildMissingRequired'), - mutuallyexclusive: require('./buildMutuallyExclusive'), - ngevent: require('./buildNgEvent'), - ngrepeatformat: require('./buildNgRepeatFormat'), - nonexsisting: require('./buildNonExsisting'), - wronguse: require('./buildWrongUse') -}; - -/** - *@param failedElements: [] of {}s of all failed elements with their failed attributes and closest - *matches or restrict properties - * - *@return [] of failed messages. - **/ -module.exports = function(failedElements) { - failedElements.forEach(function(obj) { - obj.data.forEach(function(info) { - var id = (obj.domElement.id) ? ' with id: #' + obj.domElement.id : '', - type = obj.domElement.nodeName, - messageAndSeverity = build[info.typeError](info, id, type); - hintLog.logMessage(MODULE_NAME, messageAndSeverity[0], messageAndSeverity[1]); - }); - }); -}; - -},{"./buildDeprecated":6,"./buildMissingRequired":7,"./buildMutuallyExclusive":8,"./buildNgEvent":10,"./buildNgRepeatFormat":11,"./buildNonExsisting":12,"./buildWrongUse":14,"angular-hint-log":47}],22:[function(require,module,exports){ -var normalizeAttribute = require('./normalizeAttribute'); -var ddLibData = require('./ddLib-data'); -var isMutExclusiveDir = require('./isMutExclusiveDir'); -var hasMutExclusivePair = require('./hasMutExclusivePair'); -var attributeExsistsInTypes = require('./attributeExsistsInTypes'); -var getSuggestions = require('./getSuggestions'); -var checkNgRepeatFormat = require('./checkNgRepeatFormat'); - -/** - *@param attributes: [] of attributes from element (includes tag name of element, e.g. DIV, P, etc.) - *@param options: {} options object from beginSearch - * - *@return [] of failedAttributes with their respective suggestions and directiveTypes - **/ -module.exports = function(attributes, options) { - var failedAttrs = [], mutExPairFound = false; - for (var i = 0; i < attributes.length; i++) { - var attr = normalizeAttribute(attributes[i].nodeName); - var dirVal = ddLibData.directiveTypes['html-directives'].directives[attr] || - ddLibData.directiveTypes['angular-deprecated-directives'].directives[attr] || ''; - - if(dirVal === 'deprecated') { - failedAttrs.push({ - error: attr, - directiveType: 'angular-deprecated-directives', - typeError: 'deprecated' - }); - } - - //if attr is a event attr. Html event directives are prefixed with ! in ddLibData - if (dirVal.indexOf('!') > -1) { - failedAttrs.push({ - error: attr, - directiveType: 'html-directives', - typeError: 'ngevent' - }); - continue; - } - if (!mutExPairFound && isMutExclusiveDir(attr) && hasMutExclusivePair(attr, attributes)) { - failedAttrs.push({ - error: attr, - directiveType: 'angular-default-directives', - typeError: 'mutuallyexclusive' - }); - mutExPairFound = true; - continue; - } - var attrVal = attributes[i].value || ''; - if(attr === 'ng-repeat') { - var result = checkNgRepeatFormat(attrVal); - if(result) { - failedAttrs.push({ - error: attr, - suggestion: result, - directiveType: 'angular-default-directives', - typeError: 'ngrepeatformat' - }); - } - } - - var result = attributeExsistsInTypes(attr,options); - - var suggestion = result.typeError === 'nonexsisting' ? - getSuggestions(attr, options) : {match: ''}; - - if (result.typeError) { - failedAttrs.push({ - match: suggestion.match || '', - wrongUse: result.wrongUse || '', - error: attr, - directiveType: suggestion.directiveType || 'angular-custom-directives', - typeError: result.typeError - }); - } - } - return failedAttrs; -}; -},{"./attributeExsistsInTypes":5,"./checkNgRepeatFormat":15,"./ddLib-data":17,"./getSuggestions":25,"./hasMutExclusivePair":26,"./isMutExclusiveDir":29,"./normalizeAttribute":31}],23:[function(require,module,exports){ -var getFailedAttributes = require('./getFailedAttributes'); -var findMissingAttrs = require('./findMissingAttrs'); - - -/** - *@description - *Adds element tag name (DIV, P, SPAN) to list of attributes with '*' prepended - *for identification later. - * - *@param options: {} options object from beginSearch - *@param element: HTML element to check attributes of - * - *@return {} of html element and [] of failed attributes - **/ -module.exports = function(options, element) { - if(element.attributes.length) { - var eleName = element.nodeName.toLowerCase(); - var eleAttrs = Array.prototype.slice.call(element.attributes); - eleAttrs.push({ - nodeName: '*'+eleName - }); - var failedAttrs = getFailedAttributes(eleAttrs, options); - var missingRequired = findMissingAttrs(eleName, eleAttrs); - var missingLength = missingRequired.length; - - if(failedAttrs.length || missingLength) { - if(missingLength) { - failedAttrs.push({ - directiveType: 'angular-custom-directive', - missing: missingRequired, - typeError: 'missingrequired' - }); - } - return { - domElement: element, - data: failedAttrs - }; - } - } -}; - -},{"./findMissingAttrs":20,"./getFailedAttributes":22}],24:[function(require,module,exports){ -module.exports = function(str) { - var customDirectives = [], - pairs = [], - SCOPE_REGEXP = /scope\s*:\s*{\s*[^}]*['"]\s*}/, - PROPERTY_REGEXP = /\w+\s*:\s*['"][a-zA-Z=@&]+['"]/g, - KEYVAL_REGEXP = /(\w+)\s*:\s*['"](.+)['"]/; - var matchScope = str.replace(/\n/g,'').match(SCOPE_REGEXP); - var propertiesMatch = matchScope ? matchScope[0].match(PROPERTY_REGEXP) : undefined; - - if (matchScope && propertiesMatch) { - propertiesMatch.map(function(str){ - var temp = str.match(KEYVAL_REGEXP); - pairs.push({key: temp[1], value: temp[2]}); - }); - pairs.forEach(function(pair){ - var name = (['=', '@', '&'].indexOf(pair.value) !== -1)? pair.key : pair.value.substring(1); - customDirectives.push({directiveName: name , restrict:'A'}); - }); - } - return customDirectives; -}; - -},{}],25:[function(require,module,exports){ -var ddLibData = require('./ddLib-data'); -var findClosestMatchIn = require('./findClosestMatchIn'); - -/** - *@param attribute: attribute name as string e.g. 'ng-click', 'width', 'src', etc. - *@param options: {} options object from beginSearch. - * - *@return {} with closest match to attribute and the directive type it corresponds to. - **/ -module.exports = function(attribute, options) { - var min_levDist = Infinity, - match = '', - dirType = ''; - - options.directiveTypes.forEach(function(directiveType) { - var isTag = attribute.charAt(0) === '*'; - var isCustomDir = directiveType === 'angular-custom-directives'; - if (!isTag || (isTag && isCustomDir)) { - var directiveTypeData = ddLibData.directiveTypes[directiveType].directives; - var tempMatch = findClosestMatchIn(directiveTypeData, attribute); - if (tempMatch.min_levDist < options.tolerance && tempMatch.min_levDist < min_levDist) { - match = tempMatch.match; - dirType = directiveType; - min_levDist = tempMatch.min_levDist; - } - } - }); - return { - match: match, - directiveType: dirType - }; -}; - -},{"./ddLib-data":17,"./findClosestMatchIn":18}],26:[function(require,module,exports){ -var isMutExclusiveDir = require('./isMutExclusiveDir'); - -module.exports = function(attr, attributes) { - var pair = isMutExclusiveDir(attr); - - return attributes.some(function(otherAttr) { - return otherAttr.nodeName === pair; - }); -}; - -},{"./isMutExclusiveDir":29}],27:[function(require,module,exports){ -var dasherize = require('dasherize'); -var validate = require('validate-element-name'); - -module.exports = function(str) { - var dashStr = dasherize(str); - var validated = !validate(dashStr).message ? true : false; - //Check for message definition because validate-element-name returns true for things starting - //with ng-, polymer-, and data- but message is defined for those and errors. - return validated && str.toLowerCase() !== str; -}; - -},{"dasherize":34,"validate-element-name":35}],28:[function(require,module,exports){ -module.exports = function(facStr) { - return facStr.match(/replace\s*:/); -}; - -},{}],29:[function(require,module,exports){ -module.exports = function (dirName) { - var exclusiveDirHash = { - 'ng-show' : 'ng-hide', - 'ng-hide' : 'ng-show', - 'ng-switch-when' : 'ng-switch-default', - 'ng-switch-default' : 'ng-switch-when', - }; - return exclusiveDirHash[dirName]; -}; - -},{}],30:[function(require,module,exports){ -/** - *@param s: first string to compare for Levenshtein Distance. - *@param t: second string to compare for Levenshtein Distance. - * - *@description - *Calculates the minimum number of changes (insertion, deletion, transposition) to get from s to t. - * - *credit: http://stackoverflow.com/questions/11919065/sort-an-array-by-the-levenshtein-distance-with-best-performance-in-javascript - *http://www.merriampark.com/ld.htm, http://www.mgilleland.com/ld/ldjavascript.htm, Damerau–Levenshtein distance (Wikipedia) - **/ -module.exports = function(s, t) { - if(typeof s !== 'string' || typeof t !== 'string') { - throw new Error('Function must be passed two strings, given: '+typeof s+' and '+typeof t+'.'); - } - var d = []; - var n = s.length; - var m = t.length; - - if (n === 0) {return m;} - if (m === 0) {return n;} - - for (var ii = n; ii >= 0; ii--) { d[ii] = []; } - for (var ii = n; ii >= 0; ii--) { d[ii][0] = ii; } - for (var jj = m; jj >= 0; jj--) { d[0][jj] = jj; } - for (var i = 1; i <= n; i++) { - var s_i = s.charAt(i - 1); - - for (var j = 1; j <= m; j++) { - if (i == j && d[i][j] > 4) return n; - var t_j = t.charAt(j - 1); - var cost = (s_i == t_j) ? 0 : 1; - var mi = d[i - 1][j] + 1; - var b = d[i][j - 1] + 1; - var c = d[i - 1][j - 1] + cost; - if (b < mi) mi = b; - if (c < mi) mi = c; - d[i][j] = mi; - if (i > 1 && j > 1 && s_i == t.charAt(j - 2) && s.charAt(i - 2) == t_j) { - d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost); - } - } - } - return d[n][m]; -}; - -},{}],31:[function(require,module,exports){ -/** - *@param attribute: attribute name before normalization as string - * e.g. 'data-ng-click', 'width', 'x:ng:src', etc. - * - *@return normalized attribute name - **/ -module.exports = function(attribute) { - return attribute.replace(/^(?:data|x)[-_:]/,'').replace(/[:_]/g,'-'); -}; - -},{}],32:[function(require,module,exports){ - -var formatResults = require('./formatResults'); -var findFailedElements = require('./findFailedElements'); -var setCustomDirectives = require('./setCustomDirectives'); -var defaultTypes = [ - 'html-directives', - 'angular-default-directives', - 'angular-custom-directives', - 'angular-deprecated-directives' -]; - - -/** - * - *@param scopeElements: [] of HTML elements to be checked for incorrect attributes - *@param customDirectives: [] of custom directive objects from $compile decorator - *@param options: {} of options for app to run with: - * options.tolerance: Integer, maximum Levenshtein Distance to be allowed for misspellings - * options.directiveTypes: [] of which type of directives/attributes to search through - **/ -module.exports = function(scopeElements, customDirectives, options) { - if(!Array.isArray(scopeElements)) { - throw new Error('Function search must be passed an array.'); - } - options = options || {}; - options.directiveTypes = options.directiveTypes || defaultTypes; - options.tolerance = options.tolerance || 4; - if(customDirectives && customDirectives.length){ - setCustomDirectives(customDirectives); - } - var failedElements = findFailedElements(scopeElements, options); - formatResults(failedElements); -}; - -},{"./findFailedElements":19,"./formatResults":21,"./setCustomDirectives":33}],33:[function(require,module,exports){ -var ddLibData = require('../lib/ddLib-data'); - -module.exports = function(customDirectives) { - customDirectives.forEach(function(directive) { - var directiveName = directive.directiveName.replace(/([A-Z])/g, '-$1').toLowerCase(); - ddLibData.directiveTypes['angular-custom-directives'] - .directives[directiveName] = directive; - }); -}; - -},{"../lib/ddLib-data":17}],34:[function(require,module,exports){ -'use strict'; - -var isArray = Array.isArray || function (obj) { - return Object.prototype.toString.call(obj) === '[object Array]'; -}; - -var isDate = function (obj) { - return Object.prototype.toString.call(obj) === '[object Date]'; -}; - -var isRegex = function (obj) { - return Object.prototype.toString.call(obj) === '[object RegExp]'; -}; - -var has = Object.prototype.hasOwnProperty; -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - if (has.call(obj, key)) { - keys.push(key); - } - } - return keys; -}; - -function dashCase(str) { - return str.replace(/([A-Z])/g, function ($1) { - return '-' + $1.toLowerCase(); - }); -} - -function map(xs, f) { - if (xs.map) { - return xs.map(f); - } - var res = []; - for (var i = 0; i < xs.length; i++) { - res.push(f(xs[i], i)); - } - return res; -} - -function reduce(xs, f, acc) { - if (xs.reduce) { - return xs.reduce(f, acc); - } - for (var i = 0; i < xs.length; i++) { - acc = f(acc, xs[i], i); - } - return acc; -} - -function walk(obj) { - if (!obj || typeof obj !== 'object') { - return obj; - } - if (isDate(obj) || isRegex(obj)) { - return obj; - } - if (isArray(obj)) { - return map(obj, walk); - } - return reduce(objectKeys(obj), function (acc, key) { - var camel = dashCase(key); - acc[camel] = walk(obj[key]); - return acc; - }, {}); -} - -module.exports = function (obj) { - if (typeof obj === 'string') { - return dashCase(obj); - } - return walk(obj); -}; - -},{}],35:[function(require,module,exports){ -'use strict'; -var ncname = require('ncname'); - -var reservedNames = [ - 'annotation-xml', - 'color-profile', - 'font-face', - 'font-face-src', - 'font-face-uri', - 'font-face-format', - 'font-face-name', - 'missing-glyph' -]; - -function hasError(name) { - if (!name) { - return 'Missing element name.'; - } - - if (/[A-Z]/.test(name)) { - return 'Custom element names must not contain uppercase ASCII characters.'; - } - - if (name.indexOf('-') === -1) { - return 'Custom element names must contain a hyphen. Example: unicorn-cake'; - } - - if (/^\d/i.test(name)) { - return 'Custom element names must not start with a digit.'; - } - - if (/^-/i.test(name)) { - return 'Custom element names must not start with a hyphen.'; - } - - // http://www.w3.org/TR/custom-elements/#concepts - if (!ncname.test(name)) { - return 'Invalid element name.'; - } - - if (reservedNames.indexOf(name) !== -1) { - return 'The supplied element name is reserved and can\'t be used.\nSee: http://www.w3.org/TR/custom-elements/#concepts'; - } -} - -function hasWarning(name) { - if (/^polymer-/i.test(name)) { - return 'Custom element names should not start with `polymer-`.\nSee: http://webcomponents.github.io/articles/how-should-i-name-my-element'; - } - - if (/^x-/i.test(name)) { - return 'Custom element names should not start with `x-`.\nSee: http://webcomponents.github.io/articles/how-should-i-name-my-element/'; - } - - if (/^ng-/i.test(name)) { - return 'Custom element names should not start with `ng-`.\nSee: http://docs.angularjs.org/guide/directive#creating-directives'; - } - - if (/^xml/i.test(name)) { - return 'Custom element names should not start with `xml`.'; - } - - if (/^[^a-z]/i.test(name)) { - return 'This element name is only valid in XHTML, not in HTML. First character should be in the range a-z.'; - } - - if (/[^a-z0-9]$/i.test(name)) { - return 'Custom element names should not end with a non-alpha character.'; - } - - if (/[\.]/.test(name)) { - return 'Custom element names should not contain a dot character as it would need to be escaped in a CSS selector.'; - } - - if (/[^\x20-\x7E]/.test(name)) { - return 'Custom element names should not contain non-ASCII characters.'; - } - - if (/--/.test(name)) { - return 'Custom element names should not contain consecutive hyphens.'; - } - - if (/[^a-z0-9]{2}/i.test(name)) { - return 'Custom element names should not contain consecutive non-alpha characters.'; - } -} - -module.exports = function (name) { - var errMsg = hasError(name); - - return { - isValid: !errMsg, - message: errMsg || hasWarning(name) - }; -}; - -},{"ncname":36}],36:[function(require,module,exports){ -'use strict'; -var xmlChars = require('xml-char-classes'); - -function getRange(re) { - return re.source.slice(1, -1); -} - -// http://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-NCName -module.exports = new RegExp('^[' + getRange(xmlChars.letter) + '_][' + getRange(xmlChars.letter) + getRange(xmlChars.digit) + '\\.\\-_' + getRange(xmlChars.combiningChar) + getRange(xmlChars.extender) + ']*$'); - -},{"xml-char-classes":37}],37:[function(require,module,exports){ -exports.baseChar = /[A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\u0131\u0134-\u013E\u0141-\u0148\u014A-\u017E\u0180-\u01C3\u01CD-\u01F0\u01F4\u01F5\u01FA-\u0217\u0250-\u02A8\u02BB-\u02C1\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03CE\u03D0-\u03D6\u03DA\u03DC\u03DE\u03E0\u03E2-\u03F3\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E-\u0481\u0490-\u04C4\u04C7\u04C8\u04CB\u04CC\u04D0-\u04EB\u04EE-\u04F5\u04F8\u04F9\u0531-\u0556\u0559\u0561-\u0586\u05D0-\u05EA\u05F0-\u05F2\u0621-\u063A\u0641-\u064A\u0671-\u06B7\u06BA-\u06BE\u06C0-\u06CE\u06D0-\u06D3\u06D5\u06E5\u06E6\u0905-\u0939\u093D\u0958-\u0961\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8B\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AE0\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B36-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB5\u0BB7-\u0BB9\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CDE\u0CE0\u0CE1\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D28\u0D2A-\u0D39\u0D60\u0D61\u0E01-\u0E2E\u0E30\u0E32\u0E33\u0E40-\u0E45\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD\u0EAE\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0F40-\u0F47\u0F49-\u0F69\u10A0-\u10C5\u10D0-\u10F6\u1100\u1102\u1103\u1105-\u1107\u1109\u110B\u110C\u110E-\u1112\u113C\u113E\u1140\u114C\u114E\u1150\u1154\u1155\u1159\u115F-\u1161\u1163\u1165\u1167\u1169\u116D\u116E\u1172\u1173\u1175\u119E\u11A8\u11AB\u11AE\u11AF\u11B7\u11B8\u11BA\u11BC-\u11C2\u11EB\u11F0\u11F9\u1E00-\u1E9B\u1EA0-\u1EF9\u1F00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2126\u212A\u212B\u212E\u2180-\u2182\u3041-\u3094\u30A1-\u30FA\u3105-\u312C\uAC00-\uD7A3]/; - -exports.ideographic = /[\u3007\u3021-\u3029\u4E00-\u9FA5]/; - -exports.letter = /[A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\u0131\u0134-\u013E\u0141-\u0148\u014A-\u017E\u0180-\u01C3\u01CD-\u01F0\u01F4\u01F5\u01FA-\u0217\u0250-\u02A8\u02BB-\u02C1\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03CE\u03D0-\u03D6\u03DA\u03DC\u03DE\u03E0\u03E2-\u03F3\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E-\u0481\u0490-\u04C4\u04C7\u04C8\u04CB\u04CC\u04D0-\u04EB\u04EE-\u04F5\u04F8\u04F9\u0531-\u0556\u0559\u0561-\u0586\u05D0-\u05EA\u05F0-\u05F2\u0621-\u063A\u0641-\u064A\u0671-\u06B7\u06BA-\u06BE\u06C0-\u06CE\u06D0-\u06D3\u06D5\u06E5\u06E6\u0905-\u0939\u093D\u0958-\u0961\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8B\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AE0\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B36-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB5\u0BB7-\u0BB9\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CDE\u0CE0\u0CE1\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D28\u0D2A-\u0D39\u0D60\u0D61\u0E01-\u0E2E\u0E30\u0E32\u0E33\u0E40-\u0E45\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD\u0EAE\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0F40-\u0F47\u0F49-\u0F69\u10A0-\u10C5\u10D0-\u10F6\u1100\u1102\u1103\u1105-\u1107\u1109\u110B\u110C\u110E-\u1112\u113C\u113E\u1140\u114C\u114E\u1150\u1154\u1155\u1159\u115F-\u1161\u1163\u1165\u1167\u1169\u116D\u116E\u1172\u1173\u1175\u119E\u11A8\u11AB\u11AE\u11AF\u11B7\u11B8\u11BA\u11BC-\u11C2\u11EB\u11F0\u11F9\u1E00-\u1E9B\u1EA0-\u1EF9\u1F00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2126\u212A\u212B\u212E\u2180-\u2182\u3007\u3021-\u3029\u3041-\u3094\u30A1-\u30FA\u3105-\u312C\u4E00-\u9FA5\uAC00-\uD7A3]/; - -exports.combiningChar = /[\u0300-\u0345\u0360\u0361\u0483-\u0486\u0591-\u05A1\u05A3-\u05B9\u05BB-\u05BD\u05BF\u05C1\u05C2\u05C4\u064B-\u0652\u0670\u06D6-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0901-\u0903\u093C\u093E-\u094D\u0951-\u0954\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A02\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A70\u0A71\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0B01-\u0B03\u0B3C\u0B3E-\u0B43\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B82\u0B83\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C01-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C82\u0C83\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0D02\u0D03\u0D3E-\u0D43\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86-\u0F8B\u0F90-\u0F95\u0F97\u0F99-\u0FAD\u0FB1-\u0FB7\u0FB9\u20D0-\u20DC\u20E1\u302A-\u302F\u3099\u309A]/; - -exports.digit = /[0-9\u0660-\u0669\u06F0-\u06F9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE7-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29]/; - -exports.extender = /[\xB7\u02D0\u02D1\u0387\u0640\u0E46\u0EC6\u3005\u3031-\u3035\u309D\u309E\u30FC-\u30FE]/; -},{}],38:[function(require,module,exports){ -'use strict'; - -/** -* Load necessary functions from /lib into variables. -*/ -var ngEventDirectives = require('./lib/getEventDirectives')(), - getEventAttribute = require('./lib/getEventAttribute'), - getFunctionNames = require('./lib/getFunctionNames'), - formatResults = require('./lib/formatResults'); - -/** -* Decorate $provide in order to examine ng-event directives -* and hint about their effective use. -*/ -angular.module('ngHintEvents', []) - .config(['$provide', function($provide) { - - for(var directive in ngEventDirectives) { - var dirName = ngEventDirectives[directive]+'Directive'; - try{ - $provide.decorator(dirName, ['$delegate', '$timeout', '$parse', - function($delegate, $timeout, $parse) { - - var original = $delegate[0].compile, falseBinds = [], messages = []; - - $delegate[0].compile = function(element, attrs, transclude) { - var angularAttrs = attrs.$attr; - var eventAttrName = getEventAttribute(angularAttrs); - var fn = $parse(attrs[eventAttrName]); - var messages = []; - return function ngEventHandler(scope, element, attrs) { - for(var attr in angularAttrs) { - var boundFuncs = getFunctionNames(attrs[attr]); - boundFuncs.forEach(function(boundFn) { - if(ngEventDirectives[attr] && !(boundFn in scope)) { - messages.push({ - scope: scope, - element:element, - attrs: attrs, - boundFunc: boundFn - }); - } - }); - } - element.on(eventAttrName.substring(2).toLowerCase(), function(event) { - scope.$apply(function() { - fn(scope, {$event:event}); - }); - }); - formatResults(messages); - }; - }; - return $delegate; - }]); - } catch(e) {} - } - }]); -},{"./lib/formatResults":40,"./lib/getEventAttribute":41,"./lib/getEventDirectives":42,"./lib/getFunctionNames":43}],39:[function(require,module,exports){ -'use strict'; - -var getValidProps = require('./getValidProps'), - suggest = require('suggest-it'); - -module.exports = function addSuggestions(messages) { - messages.forEach(function(messageObj) { - var dictionary = getValidProps(messageObj.scope), - suggestion = suggest(dictionary)(messageObj.boundFunc); - messageObj['match'] = suggestion; - }); - return messages; -}; - -},{"./getValidProps":44,"suggest-it":46}],40:[function(require,module,exports){ -'use strict'; - -var hintLog = angular.hint = require('angular-hint-log'), - addSuggestions = require('./addSuggestions'), - MODULE_NAME = 'Events', - SEVERITY_ERROR = 1; - -module.exports = function formatResults(messages) { - messages = addSuggestions(messages); - if(messages.length) { - messages.forEach(function(obj) { - var id = (obj.element[0].id) ? ' with id: #' + obj.element[0].id : '', - type = obj.element[0].nodeName, - suggestion = obj.match ? ' (Try "' + obj.match + '").': '.', - message = 'Variable "' + obj.boundFunc + '" called on ' + type + ' element' + id + - ' does not exist in that scope' + suggestion + ' Event directive found on "' + - obj.element[0].outerHTML + '".'; - hintLog.logMessage(MODULE_NAME, message, SEVERITY_ERROR); - }); - } -}; - -},{"./addSuggestions":39,"angular-hint-log":47}],41:[function(require,module,exports){ -'use strict'; - -var ngEventDirectives = require('./getEventDirectives')(); - -module.exports = function getEventAttribute(attrs) { - for(var attr in attrs) { - if(ngEventDirectives[attr]) { - return attr; - } - } -}; - -},{"./getEventDirectives":42}],42:[function(require,module,exports){ -'use strict'; - -module.exports = function getEventDirectives() { - var list = 'click submit mouseenter mouseleave mousemove mousedown mouseover mouseup dblclick keyup keydown keypress blur focus submit cut copy paste'.split(' '); - var eventDirHash = {}; - list.forEach(function(dirName) { - dirName = 'ng'+dirName.charAt(0).toUpperCase()+dirName.substring(1); - eventDirHash[dirName] = dirName; - }); - return eventDirHash; -}; - -},{}],43:[function(require,module,exports){ -'use strict'; - -module.exports = function getFunctionNames(str) { - var results = str.replace(/\s+/g, '').split(/[\+\-\/\|\<\>\^=&!%~]/g).map(function(x) { - if(isNaN(+x)) { - if(x.match(/\w+\(.*\)$/)){ - return x.substring(0, x.indexOf('(')); - } - return x; - } - }).filter(function(x){return x;}); - return results; -}; - -},{}],44:[function(require,module,exports){ -'use strict'; - -module.exports = function getValidProps(obj) { - var props = []; - for(var prop in obj) { - if (prop.charAt(0) !== '$' && typeof obj[prop] === 'function') { - props.push(prop); - } - } - return props; -}; - -},{}],45:[function(require,module,exports){ -module.exports = distance; - -function distance(a, b) { - var table = []; - if (a.length === 0 || b.length === 0) return Math.max(a.length, b.length); - for (var ii = 0, ilen = a.length + 1; ii !== ilen; ++ii) { - table[ii] = []; - for (var jj = 0, jlen = b.length + 1; jj !== jlen; ++jj) { - if (ii === 0 || jj === 0) table[ii][jj] = Math.max(ii, jj); - else { - var diagPenalty = Number(a[ii-1] !== b[jj-1]); - var diag = table[ii - 1][jj - 1] + diagPenalty; - var top = table[ii - 1][jj] + 1; - var left = table[ii][jj - 1] + 1; - table[ii][jj] = Math.min(left, top, diag); - } - } - } - return table[a.length][b.length]; -} - - -},{}],46:[function(require,module,exports){ -module.exports = suggestDictionary; - -var distance = require('./levenstein_distance'); - -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 result; - }, { score: Infinity }).word; - }; -} - -suggestDictionary.distance = distance; - -},{"./levenstein_distance":45}],47:[function(require,module,exports){ -/** -* HintLog creates a queue of messages logged by ngHint modules. This object -* has a key for each ngHint module that corresponds to the messages -* from that module. -*/ -var queuedMessages = {}, - MESSAGE_TYPES = [ - 'error', - 'warning', - 'suggestion' - ]; - -/** -* Add a message to the HintLog message queue. Messages are organized into categories -* according to their module name and severity. -**/ -function logMessage(moduleName, message, severity, category) { - // If no severity was provided, categorize the message as a `suggestion` - severity = severity || 3; - var messageType = MESSAGE_TYPES[severity - 1]; - - // If no ModuleName was found, categorize the message under `General` - moduleName = moduleName || 'General'; - - // If the category does not exist, initialize a new object - queuedMessages[moduleName] = queuedMessages[moduleName] || {}; - queuedMessages[moduleName][messageType] = queuedMessages[moduleName][messageType] || []; - - if (queuedMessages[moduleName][messageType].indexOf(message) < 0) { - queuedMessages[moduleName][messageType].push(message); - } - - module.exports.onMessage(moduleName, message, messageType, category); -} - -/** -* Return and empty the current queue of messages. -**/ -function flush() { - var flushMessages = queuedMessages; - queuedMessages = {}; - return flushMessages; -} - -module.exports.onMessage = function(message) {}; -module.exports.logMessage = logMessage; -module.exports.flush = flush; - -},{}],48:[function(require,module,exports){ -'use strict'; - -var storeDependencies = require('./lib/storeDependencies'), - getModule = require('./lib/getModule'), - start = require('./lib/start'), - storeNgAppAndView = require('./lib/storeNgAppAndView'), - storeUsedModules = require('./lib/storeUsedModules'), - hasNameSpace = require('./lib/hasNameSpace'), - modData = require('./lib/moduleData'); - -var doc = Array.prototype.slice.call(document.getElementsByTagName('*')), - originalAngularModule = angular.module, - modules = {}; - -storeNgAppAndView(doc); - -angular.module = function() { - var requiresOriginal = arguments[1], - module = originalAngularModule.apply(this, arguments), - name = module.name; - module.requiresOriginal = requiresOriginal; - modules[name] = module; - hasNameSpace(name); - var modToCheck = getModule(name, true); - - if(modToCheck && modToCheck.requiresOriginal !== module.requiresOriginal) { - if(!modData.createdMulti[name]) { - modData.createdMulti[name] = [getModule(name,true)]; - } - modData.createdMulti[name].push(module); - } - modData.createdModules[name] = module; - return module; -}; - -angular.module('ngHintModules', []).config(function() { - var ngAppMod = modules[modData.ngAppMod]; - storeUsedModules(ngAppMod, modules); - start(); -}); - -},{"./lib/getModule":51,"./lib/hasNameSpace":55,"./lib/moduleData":57,"./lib/start":60,"./lib/storeDependencies":61,"./lib/storeNgAppAndView":62,"./lib/storeUsedModules":63}],49:[function(require,module,exports){ -var hintLog = angular.hint = require('angular-hint-log'), - MODULE_NAME = 'Modules'; - -module.exports = function(modules) { - modules.forEach(function(module) { - hintLog.logMessage(MODULE_NAME, module.message, module.severity); - }); -}; - -},{"angular-hint-log":47}],50:[function(require,module,exports){ -var modData = require('./moduleData'); - MODULE_NAME = 'Modules', - SEVERITY_WARNING = 2; - -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; -}; - -},{"./moduleData":57}],51:[function(require,module,exports){ -var modData = require('./moduleData'); - -module.exports = function(moduleName, getCreated) { - return (getCreated)? modData.createdModules[moduleName] : modData.loadedModules[moduleName]; -}; - -},{"./moduleData":57}],52:[function(require,module,exports){ -var hintLog = angular.hint = require('angular-hint-log'), - MODULE_NAME = 'Modules', - SEVERITY_ERROR = 1; - module.exports = function(attrs, ngAppFound) { - if(attrs['ng-app'] && ngAppFound) { - hintLog.logMessage(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; - }; - - - -},{"angular-hint-log":47}],53:[function(require,module,exports){ -var getModule = require('./getModule'), - dictionary = Object.keys(require('./moduleData').createdModules), - suggest = require('suggest-it')(dictionary), - SEVERITY_ERROR = 1; - -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+'.'; - - undeclaredModules.push({module: null, message: message, severity: SEVERITY_ERROR}); - } - } - return undeclaredModules; -}; - -},{"./getModule":51,"./moduleData":57,"suggest-it":65}],54:[function(require,module,exports){ -var getModule = require('./getModule'), - IGNORED = ['ngHintControllers', 'ngHintDirectives', 'ngHintDOM', 'ngHintEvents', - 'ngHintInterpolation', 'ngHintModules']; - SEVERITY_WARNING = 2; - -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; -}; - -},{"./getModule":51}],55:[function(require,module,exports){ -var hintLog = angular.hint = require('angular-hint-log'), - MODULE_NAME = 'Modules', - SEVERITY_SUGGESTION = 3; -module.exports = function(str) { - if(str.toLowerCase() === str || str.charAt(0).toUpperCase() === str.charAt(0)) { - hintLog.logMessage(MODULE_NAME, 'The best practice for' + - ' module names is to use lowerCamelCase. Check the name of "' + str + '".', - SEVERITY_SUGGESTION); - return false; - } - return true; -}; - -},{"angular-hint-log":47}],56:[function(require,module,exports){ -var normalizeAttribute = require('./normalizeAttribute'); - -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; - } - } -}; - -},{"./normalizeAttribute":59}],57:[function(require,module,exports){ -module.exports = { - createdModules: {}, - createdMulti: {}, - loadedModules: {} -}; - -},{}],58:[function(require,module,exports){ -var modData = require('./moduleData'), - getModule = require('./getModule'); - -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.'}; - } -}; - -},{"./getModule":51,"./moduleData":57}],59:[function(require,module,exports){ -module.exports = function(attribute) { - return attribute.replace(/^(?:data|x)[-_:]/, '').replace(/[:_]/g, '-'); -}; - -},{}],60:[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); - } - display(toSend); - } -}; - -},{"./display":49,"./formatMultiLoaded":50,"./getUndeclaredModules":53,"./getUnusedModules":54,"./moduleData":57,"./ngViewNoNgRoute":58}],61:[function(require,module,exports){ -var modData = require('./moduleData'); - -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; - } -}; - -},{"./moduleData":57}],62:[function(require,module,exports){ -var getNgAppMod = require('./getNgAppMod'), - inAttrsOrClasses = require('./inAttrsOrClasses'), - storeDependencies = require('./storeDependencies'), - modData = require('./moduleData'); - -module.exports = function(doms) { - var bothFound, - ngViewFound, - elem, - isElemName, - isInAttrsOrClasses, - ngAppMod; - - for(var i = 0; i < doms.length; i++) { - elem = doms[i]; - var attributes = elem.attributes; - isElemName = elem.nodeName.toLowerCase() === 'ng-view'; - isInAttrsOrClasses = inAttrsOrClasses(attributes); - - ngViewFound = isElemName || isInAttrsOrClasses; - - ngAppMod = getNgAppMod(attributes, modData.ngAppFound); - modData.ngAppFound = modData.ngAppFound || ngAppMod; - - if(ngAppMod) { - storeDependencies(ngAppMod, true); - } - modData.ngViewExists = ngViewFound ? true : modData.ngViewExists; - - if(bothFound) { - break; - } - } -}; - -},{"./getNgAppMod":52,"./inAttrsOrClasses":56,"./moduleData":57,"./storeDependencies":61}],63:[function(require,module,exports){ -var storeDependencies = require('./storeDependencies'); - -var storeUsedModules = module.exports = function(module, modules){ - if(module) { - storeDependencies(module); - module.requires.forEach(function(modName) { - var mod = modules[modName]; - storeUsedModules(mod, modules); - }); - } -}; -},{"./storeDependencies":61}],64:[function(require,module,exports){ -module.exports=require(45) -},{"/usr/local/google/home/sjelin/angular-hint/node_modules/angular-hint-events/node_modules/suggest-it/lib/levenstein_distance.js":45}],65:[function(require,module,exports){ -module.exports=require(46) -},{"./levenstein_distance":64,"/usr/local/google/home/sjelin/angular-hint/node_modules/angular-hint-events/node_modules/suggest-it/lib/suggest-it.js":46}],66:[function(require,module,exports){ -'use strict'; - -var summarize = require('./lib/summarize-model'); -var hint = angular.hint = require('angular-hint-log'); -var debounceOn = require('debounce-on'); - -hint.emit = function () {}; - -module.exports = angular.module('ngHintScopes', []).config(['$provide', function ($provide) { - $provide.decorator('$rootScope', ['$delegate', '$parse', decorateRootScope]); - $provide.decorator('$compile', ['$delegate', decorateDollaCompile]); -}]); - -function decorateRootScope($delegate, $parse) { - - var perf = window.performance || { now: function () { return 0; } }; - - var scopes = {}, - watching = {}; - - var debouncedEmitModelChange = debounceOn(emitModelChange, 10, byScopeId); - - hint.watch = function (scopeId, path) { - path = typeof path === 'string' ? path.split('.') : path; - - if (!watching[scopeId]) { - watching[scopeId] = {}; - } - - 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 - }); - } - }; - - hint.unwatch = function (scopeId, unwatchPath) { - Object.keys(watching[scopeId]). - forEach(function (path) { - if (path.indexOf(unwatchPath) === 0) { - delete watching[scopeId][path]; - } - }); - }; - - var debouncedEmit = debounceOn(hint.emit, 10, function (params) { - return params.id + params.path; - }); - - - var scopePrototype = ('getPrototypeOf' in Object) ? - Object.getPrototypeOf($delegate) : $delegate.__proto__; - - var _watch = scopePrototype.$watch; - scopePrototype.$watch = function (watchExpression, reactionFunction) { - 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(); - hint.emit('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(); - hint.emit('scope:watch', { - id: scopeId, - watch: watchStr, - time: end - start - }); - return ret; - }; - } - - if (typeof reactionFunction === 'function') { - var applyStr = reactionFunction.toString(); - arguments[1] = function () { - var start = perf.now(); - var ret = reactionFunction.apply(this, arguments); - var end = perf.now(); - hint.emit('scope:reaction', { - id: this.$id, - watch: watchStr, - time: end - start - }); - return ret; - }; - } - - return _watch.apply(this, arguments); - }; - - - var _destroy = scopePrototype.$destroy; - scopePrototype.$destroy = function () { - var id = this.id; - - hint.emit('scope:destroy', { id: id }); - - delete scopes[id]; - delete watching[id]; - - return _destroy.apply(this, arguments); - }; - - - var _new = scopePrototype.$new; - scopePrototype.$new = function () { - var child = _new.apply(this, arguments); - - scopes[child.$id] = child; - watching[child.$id] = {}; - - hint.emit('scope:new', { parent: this.$id, child: child.$id }); - setTimeout(function () { - emitScopeElt(child); - }, 0); - return child; - }; - - function emitScopeElt (scope) { - var scopeId = scope.$id; - var elt = findElt(scopeId); - var descriptor = scopeDescriptor(elt, scope); - hint.emit('scope:link', { - id: scopeId, - descriptor: descriptor - }); - } - - function findElt (scopeId) { - var elts = document.querySelectorAll('.ng-scope'); - var elt, scope; - - for (var i = 0; i < elts.length; i++) { - elt = angular.element(elts[i]); - scope = elt.scope(); - if (scope.$id === scopeId) { - return elt; - } - } - } - - - var _digest = scopePrototype.$digest; - scopePrototype.$digest = function (fn) { - var start = perf.now(); - var ret = _digest.apply(this, arguments); - var end = perf.now(); - hint.emit('scope:digest', { id: this.$id, time: end - start }); - return ret; - }; - - - 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; - }; - - - function gettterer (scopeId, path) { - if (path === '') { - return function () { - return scopes[scopeId]; - }; - } - var getter = $parse(path); - return function () { - return getter(scopes[scopeId]); - }; - } - - 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; - } - }); - } - } - - hint.emit('scope:new', { - parent: null, - child: $delegate.$id - }); - scopes[$delegate.$id] = $delegate; - watching[$delegate.$id] = {}; - - return $delegate; -} - -function decorateDollaCompile ($delegate) { - return function () { - var link = $delegate.apply(this, arguments); - - 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; - } - } -} - -function scopeDescriptor (elt, scope) { - var val, - types = [ - 'ng-app', - 'ng-controller', - 'ng-repeat', - 'ng-include' - ], - theseTypes = [], - type; - - if (elt) { - for (var i = 0; i < types.length; 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; -} - -function humanReadableWatchExpression (fn) { - if (fn.exp) { - fn = fn.exp; - } else if (fn.name) { - fn = fn.name; - } - return fn.toString(); -} - -},{"./lib/summarize-model":67,"angular-hint-log":47,"debounce-on":68}],67:[function(require,module,exports){ - -module.exports = function summarizeModel (model) { - - 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; - } - - function shallowSummary (obj, prop) { - obj[prop] = summarizeProperty(model[prop]); - return obj; - } -}; - -function isAngularPrivatePropertyName (key) { - return !(key[0] === '$' && key[1] === '$') && key !== '$parent' && key !== '$root'; -} - -// 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; -} - -},{}],68:[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, '::'); -} - -},{}]},{},[1]); diff --git a/testapp/ngHint/noNgHint.html b/testapp/ngHint/noNgHint.html deleted file mode 100644 index b15e05299..000000000 --- a/testapp/ngHint/noNgHint.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - Angular.js Example - - - - - - First name: -
    - Last name: -
    - Hello {{firstName}} {{lastName}} - - diff --git a/testapp/ngHint/noTag.html b/testapp/ngHint/noTag.html deleted file mode 100644 index 29aeed91a..000000000 --- a/testapp/ngHint/noTag.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - Angular.js Example - - - - - - - First name: -
    - Last name: -
    - Hello {{firstName}} {{lastName}} - - diff --git a/testapp/ngHint/unused.html b/testapp/ngHint/unused.html deleted file mode 100644 index 58475a888..000000000 --- a/testapp/ngHint/unused.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - Angular.js Example - - - - - - - First name: -
    - Last name: -
    - Hello {{firstName}} {{lastName}} - - From ddb8584a59343284904676ef6d8db5c1c996b900 Mon Sep 17 00:00:00 2001 From: Matt Fritz Date: Fri, 13 Nov 2015 15:31:45 -0700 Subject: [PATCH 023/678] chore(cucumber): Remove cucumber from internal implementation --- docs/frameworks.md | 25 ++-- docs/infrastructure.md | 2 +- docs/jasmine-upgrade.md | 2 +- docs/referenceConf.js | 6 +- lib/cli.js | 2 +- lib/configParser.js | 13 -- lib/frameworks/README.md | 10 +- lib/frameworks/cucumber.js | 189 --------------------------- lib/runner.js | 2 - package.json | 1 - scripts/test.js | 2 - scripts/test/test_util.js | 2 +- spec/cucumber/lib.feature | 15 --- spec/cucumber/stepDefinitions.js | 41 ------ spec/cucumberConf.js | 23 ---- spec/plugins/cucumberPostTestConf.js | 1 - spec/plugins/features/simple.feature | 3 - spec/plugins/postTestConfTemplate.js | 3 +- spec/unit/config_test.js | 12 -- 19 files changed, 29 insertions(+), 325 deletions(-) delete mode 100644 lib/frameworks/cucumber.js delete mode 100644 spec/cucumber/lib.feature delete mode 100644 spec/cucumber/stepDefinitions.js delete mode 100644 spec/cucumberConf.js delete mode 100644 spec/plugins/cucumberPostTestConf.js delete mode 100644 spec/plugins/features/simple.feature diff --git a/docs/frameworks.md b/docs/frameworks.md index cd4679dba..b00679b9d 100644 --- a/docs/frameworks.md +++ b/docs/frameworks.md @@ -1,7 +1,7 @@ Choosing a Framework ==================== -Protractor supports three behavior driven development (BDD) test frameworks: Jasmine, Mocha, and Cucumber. These frameworks are based on JavaScript and Node.js and provide the syntax, scaffolding, and reporting tools you will use to write and manage your tests. +Protractor supports two behavior driven development (BDD) test frameworks out of the box: Jasmine and Mocha. These frameworks are based on JavaScript and Node.js and provide the syntax, scaffolding, and reporting tools you will use to write and manage your tests. Using Jasmine @@ -58,28 +58,35 @@ For a full example, see Protractor’s own test: [/spec/mocha/lib_spec.js](/spec Using Cucumber -------------- -_Note: Limited support for Cucumber is available as of January 2015. Support for Cucumber in Protractor is maintained by the community, so bug fixes may be slow. For more information, see the [Cucumber GitHub site](https://github.com/cucumber/cucumber-js)._ +_Note: Cucumber is no longer included by default as of version `3.0`. You can integrate Cucumber with Protractor with the `custom` framework option. For more information, see the [Protractor Cucumber Framework site](https://github.com/mattfritz/protractor-cucumber-framework) or the [Cucumber GitHub site](https://github.com/cucumber/cucumber-js)._ If you would like to use the Cucumber test framework, download the dependencies with npm. Cucumber should be installed in the same place as Protractor - so if protractor was installed globally, install Cucumber with -g. ``` npm install -g cucumber +npm install --save-dev protractor-cucumber-framework ``` -Set the 'framework' property to cucumber, either by adding `framework: 'cucumber'` to the [config file](../spec/cucumberConf.js) or by adding `--framework=cucumber` to the command line. +Set the 'framework' property to custom by adding `framework: 'custom'` and `frameworkPath: 'protractor-cucumber-framework'` to the [config file](../spec/cucumberConf.js) Options for Cucumber such as 'format' can be given in the config file with cucumberOpts: ```js -cucumberOpts: { - format: "summary" -} +exports.config = { + // set to "custom" instead of cucumber. + framework: 'custom', + + // path relative to the current config file + frameworkPath: 'protractor-cucumber-framework' + + // relevant cucumber command line options + cucumberOpts: { + format: "summary" + } +}; ``` -For a full example, see Protractor’s own test: [/spec/cucumber/lib.feature](/spec/cucumber/lib.feature). - - Using a Custom Framework ------------------------ diff --git a/docs/infrastructure.md b/docs/infrastructure.md index 4c1a64212..3e83300ca 100644 --- a/docs/infrastructure.md +++ b/docs/infrastructure.md @@ -2,7 +2,7 @@ How It Works ============ -Protractor is an end-to-end test framework for AngularJS applications. Protractor is a Node.js program that supports the Jasmine, Mocha, and Cucumber test frameworks. +Protractor is an end-to-end test framework for AngularJS applications. Protractor is a Node.js program that supports the Jasmine and Mocha test frameworks. Selenium is a browser automation framework. Selenium includes the Selenium Server, the WebDriver APIs, and the WebDriver browser drivers. diff --git a/docs/jasmine-upgrade.md b/docs/jasmine-upgrade.md index f683d79b6..c4df4c9dc 100644 --- a/docs/jasmine-upgrade.md +++ b/docs/jasmine-upgrade.md @@ -9,7 +9,7 @@ Specify that you want to use jasmine2.x: ```javascript exports.config = { - // Specify you want to use jasmine 2.x as you would with mocha and cucumber. Note, 'jasmine' by default will use the latest jasmine framework. + // Specify you want to use jasmine 2.x as you would with mocha. Note, 'jasmine' by default will use the latest jasmine framework. framework: 'jasmine' }; diff --git a/docs/referenceConf.js b/docs/referenceConf.js index 64d130846..04548b936 100644 --- a/docs/referenceConf.js +++ b/docs/referenceConf.js @@ -279,7 +279,7 @@ exports.config = { // --------------------------------------------------------------------------- // Test framework to use. This may be one of: - // jasmine, cucumber, mocha or custom. + // jasmine, mocha or custom. // // When the framework is set to "custom" you'll need to additionally // set frameworkPath with the path relative to the config file or absolute @@ -289,7 +289,7 @@ exports.config = { // to comply with the interface details of your custom implementation. // // Jasmine is fully supported as test and assertion frameworks. - // Mocha and Cucumber have limited support. You will need to include your + // Mocha has limited support. You will need to include your // own assertion framework (such as Chai) if working with Mocha. framework: 'jasmine', @@ -319,7 +319,7 @@ exports.config = { reporter: 'list' }, - // Options to be passed to Cucumber. + // Options to be passed to Cucumber (when set up as a custom framework). cucumberOpts: { // Require files before executing the features. require: 'cucumber/stepDefinitions.js', diff --git a/lib/cli.js b/lib/cli.js index 05ee94f75..6a2ac66c7 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -48,7 +48,7 @@ var optimist = require('optimist'). describe('verbose', 'Print full spec names'). describe('stackTrace', 'Print stack trace on error'). describe('params', 'Param object to be passed to the tests'). - describe('framework', 'Test framework to use: jasmine, cucumber or mocha'). + describe('framework', 'Test framework to use: jasmine, mocha, or custom'). describe('resultJsonOutputFile', 'Path to save JSON test result'). describe('troubleshoot', 'Turn on troubleshooting output'). describe('elementExplorer', 'Interactively test Protractor commands'). diff --git a/lib/configParser.js b/lib/configParser.js index f03e1cd42..5d0ed8e2e 100644 --- a/lib/configParser.js +++ b/lib/configParser.js @@ -34,7 +34,6 @@ var ConfigParser = function() { defaultTimeoutInterval: (30 * 1000) }, seleniumArgs: [], - cucumberOpts: {}, mochaOpts: { ui: 'bdd', reporter: 'list' @@ -95,16 +94,7 @@ ConfigParser.resolveFilePatterns = if (patterns) { for (var i = 0; i < patterns.length; ++i) { - // Cucumber allows running a spec given a line number. See - // https://github.com/angular/protractor/issues/2413 - // TODO: when we deprecated node < v0.12 switch to using path.parse as in - // d6aebbad6e9b191fef141472887637ee4318438e var fileName = patterns[i]; - var lineNumber = /:\d+$/.exec(fileName); - if (lineNumber) { - fileName = fileName.slice(0, lineNumber.index); - lineNumber = lineNumber[0].slice(1); - } var matches = glob.sync(fileName, {cwd: cwd}); if (!matches.length && !opt_omitWarnings) { @@ -112,9 +102,6 @@ ConfigParser.resolveFilePatterns = } for (var j = 0; j < matches.length; ++j) { var resolvedPath = path.resolve(cwd, matches[j]); - if (lineNumber) { - resolvedPath += ':' + lineNumber; - } resolvedFiles.push(resolvedPath); } } diff --git a/lib/frameworks/README.md b/lib/frameworks/README.md index 49a28179b..7db48c1df 100644 --- a/lib/frameworks/README.md +++ b/lib/frameworks/README.md @@ -29,7 +29,7 @@ Requirements - `runner.getConfig().onComplete` must be called when tests are finished. - - The returned promise must be resolved when tests are finished and it should return a results object. This object must have a `failedCount` property and optionally a `specResults` + - The returned promise must be resolved when tests are finished and it should return a results object. This object must have a `failedCount` property and optionally a `specResults` object of the following structure: ``` specResults = [{ @@ -37,7 +37,7 @@ Requirements assertions: [{ passed: boolean, errorMsg: string, - stackTrace: string + stackTrace: string }], duration: integer }] @@ -46,14 +46,14 @@ Requirements Custom Frameworks ----------------- -If you have created/adapted a custom framework and want it added to -Protractor core please send a PR so it can evaluated for addition as an +If you have created/adapted a custom framework and want it added to +Protractor core please send a PR so it can evaluated for addition as an official supported framework. In the meantime you can instruct Protractor to use your own framework via the config file: ```js exports.config = { - // set to "custom" instead of jasmine/mocha/cucumber. + // set to "custom" instead of jasmine/mocha framework: 'custom', // path relative to the current config file frameworkPath: './frameworks/my_custom_jasmine.js', diff --git a/lib/frameworks/cucumber.js b/lib/frameworks/cucumber.js deleted file mode 100644 index f8dde2398..000000000 --- a/lib/frameworks/cucumber.js +++ /dev/null @@ -1,189 +0,0 @@ -var ConfigParser = require('../configParser'), - q = require('q'); - -/** - * Execute the Runner's test cases through Cucumber. - * - * @param {Runner} runner The current Protractor Runner. - * @param {Array} specs Array of Directory Path Strings. - * @return {q.Promise} Promise resolved with the test results - */ -exports.run = function(runner, specs) { - // TODO - add the event interface for cucumber. - var Cucumber = require('cucumber'), - execOptions = ['node', 'node_modules/.bin/cucumber-js'], - cucumberResolvedRequire; - - // Set up exec options for Cucumber - execOptions = execOptions.concat(specs); - if (runner.getConfig().cucumberOpts) { - - // Process Cucumber Require param - if (runner.getConfig().cucumberOpts.require) { - // TODO - this should move into the launcher. - cucumberResolvedRequire = - ConfigParser.resolveFilePatterns( - runner.getConfig().cucumberOpts.require, - false, - runner.getConfig().configDir); - if (cucumberResolvedRequire && cucumberResolvedRequire.length) { - execOptions = cucumberResolvedRequire.reduce(function(a, fn) { - return a.concat('-r', fn); - }, execOptions); - } - } - - // Process Cucumber Tag param - if (Array.isArray(runner.getConfig().cucumberOpts.tags)) { - for (var i in runner.getConfig().cucumberOpts.tags) { - var tags = runner.getConfig().cucumberOpts.tags[i]; - execOptions.push('-t'); - execOptions.push(tags); - } - } else if (runner.getConfig().cucumberOpts.tags) { - execOptions.push('-t'); - execOptions.push(runner.getConfig().cucumberOpts.tags); - } - - // Process Cucumber Format param - if (Array.isArray(runner.getConfig().cucumberOpts.format)) { - runner.getConfig().cucumberOpts.format.forEach(function (format) { - execOptions.push('-f'); - execOptions.push(format); - }); - } else if (runner.getConfig().cucumberOpts.format) { - execOptions.push('-f'); - execOptions.push(runner.getConfig().cucumberOpts.format); - } - - // Process Cucumber 'coffee' param - if (runner.getConfig().cucumberOpts.coffee) { - execOptions.push('--coffee'); - } - - // Process Cucumber 'no-snippets' param - if (runner.getConfig().cucumberOpts.noSnippets) { - execOptions.push('--no-snippets'); - } - - // Process Cucumber 'dry-run' param - if (runner.getConfig().cucumberOpts.dryRun) { - execOptions.push('-d'); - } - } - global.cucumber = Cucumber.Cli(execOptions); - - var testResult = []; - var stepResults = { - description: null, - assertions: [], - duration: 0 - }; - var scenarioFailed = false; - - var failedCount = 0; - // Add a listener into cucumber so that protractor can find out which - // steps passed/failed - var addResultListener = function(formatter) { - var feature = { getName: function() { return ''; } }; - var originalHandleBeforeFeatureEvent = formatter.handleBeforeFeatureEvent; - formatter.handleBeforeFeatureEvent = function(event, callback) { - feature = event.getPayloadItem('feature'); - if (typeof originalHandleBeforeFeatureEvent == 'function') { - originalHandleBeforeFeatureEvent.apply(formatter, arguments); - } else { - callback(); - } - }; - var originalHandleAfterScenarioEvent = formatter.handleAfterScenarioEvent; - formatter.handleAfterScenarioEvent = function(event, callback) { - var scenarioInfo = { - name: event.getPayloadItem('scenario').getName(), - category: feature.getName() - }; - stepResults.description = scenarioInfo.name; - if (scenarioFailed) { - ++failedCount; - runner.emit('testFail', scenarioInfo); - } else { - runner.emit('testPass', scenarioInfo); - } - - testResult.push(stepResults); - stepResults = { - description: null, - assertions: [], - duration: 0 - }; - scenarioFailed = false; - - if (originalHandleAfterScenarioEvent - && typeof(originalHandleAfterScenarioEvent) === 'function') { - originalHandleAfterScenarioEvent(event, callback); - } else { - callback(); - } - }; - - var originalHandleStepResultEvent = formatter.handleStepResultEvent; - formatter.handleStepResultEvent = function(event, callback) { - var stepResult = event.getPayloadItem('stepResult'); - var isStepFailed = stepResult.isFailed ? - stepResult.isFailed() : - stepResult.getStatus() === Cucumber.Status.FAILED; - var isStepSuccessful = stepResult.isSuccessful ? - stepResult.isSuccessful() : - stepResult.getStatus() === Cucumber.Status.PASSED; - - if (isStepSuccessful) { - stepResults.assertions.push({ - passed: true - }); - stepResults.duration += stepResult.getDuration(); - } else if (isStepFailed) { - scenarioFailed = true; - var failureMessage = stepResult.getFailureException(); - stepResults.assertions.push({ - passed: false, - errorMsg: failureMessage.message, - stackTrace: failureMessage.stack - }); - stepResults.duration += stepResult.getDuration(); - } - - if (originalHandleStepResultEvent - && typeof(originalHandleStepResultEvent) === 'function') { - originalHandleStepResultEvent(event, callback); - } else { - callback(); - } - }; - }; - - return runner.runTestPreparer().then(function() { - return q.promise(function(resolve, reject) { - var cucumberConf = Cucumber.Cli.Configuration(execOptions); - var runtime = Cucumber.Runtime(cucumberConf); - var formatters = cucumberConf.getFormatter ? - [cucumberConf.getFormatter()] : - cucumberConf.getFormatters(); - - addResultListener(formatters[0]); - formatters.forEach(runtime.attachListener.bind(runtime)); - - runtime.start(function() { - try { - if (runner.getConfig().onComplete) { - runner.getConfig().onComplete(); - } - resolve({ - failedCount: failedCount, - specResults: testResult - }); - } catch (err) { - reject(err); - } - }); - }); - }); -}; diff --git a/lib/runner.js b/lib/runner.js index 0965689f0..eeb99a579 100644 --- a/lib/runner.js +++ b/lib/runner.js @@ -295,8 +295,6 @@ Runner.prototype.run = function() { frameworkPath = './frameworks/jasmine.js'; } else if (self.config_.framework === 'mocha') { frameworkPath = './frameworks/mocha.js'; - } else if (self.config_.framework === 'cucumber') { - frameworkPath = './frameworks/cucumber.js'; } else if (self.config_.framework === 'debugprint') { // Private framework. Do not use. frameworkPath = './frameworks/debugprint.js'; diff --git a/package.json b/package.json index ed2ed0665..7d5e99d1e 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,6 @@ "chai-as-promised": "~5.1.0", "jshint": "2.5.0", "mocha": "2.3.3", - "cucumber": "~0.8.0", "express": "~3.3.4", "rimraf": "~2.2.6" }, diff --git a/scripts/test.js b/scripts/test.js index 3ae550d6b..fb88ae97d 100755 --- a/scripts/test.js +++ b/scripts/test.js @@ -14,7 +14,6 @@ var passingTests = [ 'node lib/cli.js spec/onPreparePromiseConf.js', 'node lib/cli.js spec/onPreparePromiseFileConf.js', 'node lib/cli.js spec/mochaConf.js', - 'node lib/cli.js spec/cucumberConf.js', 'node lib/cli.js spec/withLoginConf.js', 'node lib/cli.js spec/suitesConf.js --suite okmany', 'node lib/cli.js spec/suitesConf.js --suite okspec', @@ -23,7 +22,6 @@ var passingTests = [ 'node lib/cli.js spec/plugins/multiPluginConf.js', 'node lib/cli.js spec/plugins/jasminePostTestConf.js', 'node lib/cli.js spec/plugins/mochaPostTestConf.js', - 'node lib/cli.js spec/plugins/cucumberPostTestConf.js', 'node lib/cli.js spec/plugins/browserGetSyncedConf.js', 'node lib/cli.js spec/plugins/browserGetUnsyncedConf.js', 'node lib/cli.js spec/plugins/waitForAngularConf.js', diff --git a/scripts/test/test_util.js b/scripts/test/test_util.js index b9f6e3417..93bd39d05 100644 --- a/scripts/test/test_util.js +++ b/scripts/test/test_util.js @@ -192,7 +192,7 @@ var CommandlineTest = function(command) { * exitCode, test durations, expected errors, and expected stackTrace * Note, this will work with any commandline tests, but only if it supports * the flag '--resultJsonOutputFile', unless only exitCode is being tested. - * For now, this means protractor tests (jasmine/mocha/cucumber). + * For now, this means protractor tests (jasmine/mocha). */ exports.Executor = function() { var tests = []; diff --git a/spec/cucumber/lib.feature b/spec/cucumber/lib.feature deleted file mode 100644 index bdd005738..000000000 --- a/spec/cucumber/lib.feature +++ /dev/null @@ -1,15 +0,0 @@ -Feature: Running Cucumber with Protractor - As a user of Protractor - I should be able to use Cucumber - to run my E2E tests - - @dev - Scenario: Running Cucumber with Protractor - Given I run Cucumber with Protractor - Then it should still do normal tests - Then it should expose the correct global variables - - @dev - Scenario: Wrapping WebDriver - Given I go on "index.html" - Then the title should equal "My AngularJS App" diff --git a/spec/cucumber/stepDefinitions.js b/spec/cucumber/stepDefinitions.js deleted file mode 100644 index 0d8374b1c..000000000 --- a/spec/cucumber/stepDefinitions.js +++ /dev/null @@ -1,41 +0,0 @@ -// Use the external Chai As Promised to deal with resolving promises in -// expectations. -var chai = require('chai'); -var chaiAsPromised = require('chai-as-promised'); -chai.use(chaiAsPromised); - -var expect = chai.expect; - -// Chai expect().to.exist syntax makes default jshint unhappy. -// jshint expr:true - -module.exports = function() { - - this.Given(/^I run Cucumber with Protractor$/, function(next) { - next(); - }); - - this.Given(/^I go on(?: the website)? "([^"]*)"$/, function(url, next) { - browser.get(url); - next(); - }); - - this.Then(/^it should still do normal tests$/, function(next) { - expect(true).to.equal(true); - next(); - }); - - this.Then(/^it should expose the correct global variables$/, function(next) { - expect(protractor).to.exist; - expect(browser).to.exist; - expect(by).to.exist; - expect(element).to.exist; - expect($).to.exist; - next(); - }); - - this.Then(/the title should equal "([^"]*)"$/, function(text, next) { - expect(browser.getTitle()).to.eventually.equal(text).and.notify(next); - }); - -}; diff --git a/spec/cucumberConf.js b/spec/cucumberConf.js deleted file mode 100644 index cbf1ab40e..000000000 --- a/spec/cucumberConf.js +++ /dev/null @@ -1,23 +0,0 @@ -var env = require('./environment.js'); - -// A small suite to make sure the cucumber framework works. -exports.config = { - seleniumAddress: env.seleniumAddress, - - framework: 'cucumber', - - // Spec patterns are relative to this directory. - specs: [ - 'cucumber/*.feature' - ], - - capabilities: env.capabilities, - - baseUrl: env.baseUrl, - - cucumberOpts: { - require: 'cucumber/stepDefinitions.js', - tags: '@dev', - format: 'pretty' - } -}; diff --git a/spec/plugins/cucumberPostTestConf.js b/spec/plugins/cucumberPostTestConf.js deleted file mode 100644 index 5eeb8e435..000000000 --- a/spec/plugins/cucumberPostTestConf.js +++ /dev/null @@ -1 +0,0 @@ -exports.config = require('./postTestConfTemplate')('cucumber'); diff --git a/spec/plugins/features/simple.feature b/spec/plugins/features/simple.feature deleted file mode 100644 index fbd070a69..000000000 --- a/spec/plugins/features/simple.feature +++ /dev/null @@ -1,3 +0,0 @@ -Feature: category - This is spec does nothing - Scenario: name diff --git a/spec/plugins/postTestConfTemplate.js b/spec/plugins/postTestConfTemplate.js index 4d37410f7..8a39db240 100644 --- a/spec/plugins/postTestConfTemplate.js +++ b/spec/plugins/postTestConfTemplate.js @@ -7,8 +7,7 @@ module.exports = function(framework) { framework: framework, specs: [ - framework != 'cucumber' ? 'specs/simple_spec.js' : - 'features/simple.feature' + 'specs/simple_spec.js' ], capabilities: env.capabilities, diff --git a/spec/unit/config_test.js b/spec/unit/config_test.js index 9a51a704e..15c655657 100644 --- a/spec/unit/config_test.js +++ b/spec/unit/config_test.js @@ -62,17 +62,5 @@ describe('the config parser', function() { expect(specs[0].indexOf(path.normalize('unit/data/fakespecA.js'))).not.toEqual(-1); expect(specs[1].indexOf(path.normalize('unit/data/fakespecB.js'))).not.toEqual(-1); }); - - it('should allow for line numbers in file paths', function() { - spyOn(process, 'cwd').and.returnValue(__dirname + '/'); - var toAdd = { - specs: ['data/fakespecA.js:32', 'data/fakespecB.js'] - }; - var config = new ConfigParser().addConfig(toAdd).getConfig(); - var specs = ConfigParser.resolveFilePatterns(config.specs); - expect(specs.length).toEqual(2); - expect(specs[0].indexOf(path.normalize('unit/data/fakespecA.js:32'))).not.toEqual(-1); - expect(specs[1]).toMatch(/unit\/data\/fakespecB.js$/); - }); }); }); From 121703bad1dd7b54e17f1537a571c3b3fbfad8b9 Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Mon, 9 Nov 2015 20:36:15 -0800 Subject: [PATCH 024/678] chore(docs): include `webdriver.Key` and `webdriver.promise` in API page Closes #402 --- website/docgen/dgeni-config.js | 5 ++++- website/docgen/processors/filter-promise.js | 24 +++++++++++++++++++++ website/package.json | 6 +++--- 3 files changed, 31 insertions(+), 4 deletions(-) create mode 100644 website/docgen/processors/filter-promise.js diff --git a/website/docgen/dgeni-config.js b/website/docgen/dgeni-config.js index c0a8fb59d..bdb47871d 100644 --- a/website/docgen/dgeni-config.js +++ b/website/docgen/dgeni-config.js @@ -62,6 +62,7 @@ myPackage.processor(require('./processors/filter-jsdoc')); myPackage.processor(require('./processors/set-file-name')); myPackage.processor(require('./processors/transfer-see')); myPackage.processor(require('./processors/add-links')); +myPackage.processor(require('./processors/filter-promise')); myPackage.processor(require('./processors/add-toc')); myPackage.config(function(readFilesProcessor, templateFinder, writeFilesProcessor) { @@ -75,7 +76,9 @@ myPackage.config(function(readFilesProcessor, templateFinder, writeFilesProcesso {include: 'lib/**/locators.js'}, {include: 'lib/**/expectedConditions.js'}, {include: 'node_modules/selenium-webdriver/lib/**/locators.js'}, - {include: 'node_modules/selenium-webdriver/lib/webdriver/webdriver.js'} + {include: 'node_modules/selenium-webdriver/lib/webdriver/webdriver.js'}, + {include: 'node_modules/selenium-webdriver/lib/webdriver/key.js'}, + {include: 'node_modules/selenium-webdriver/lib/webdriver/promise.js'} ]; // Add a folder to search for our own templates to use when rendering docs diff --git a/website/docgen/processors/filter-promise.js b/website/docgen/processors/filter-promise.js new file mode 100644 index 000000000..ec2320146 --- /dev/null +++ b/website/docgen/processors/filter-promise.js @@ -0,0 +1,24 @@ +var _ = require('lodash'); + +/** + * Remove docs of private variables from selenium's promise.js file. + * + * @param {Array.} docs The jsdoc list. + */ +var filter = function(docs) { + return _.reject(docs, function(doc) { + return doc.fileName == "promise" && doc.name && + doc.name.substr(0,7) != "promise"; + }); +}; + +/** + * Filter functions that will not go into the documentation. + */ +module.exports = function filterPromise() { + return { + $runAfter: ['extracting-tags'], + $runBefore: ['tags-extracted'], + $process: filter + }; +}; diff --git a/website/package.json b/website/package.json index f5405c1d4..2995fad3f 100644 --- a/website/package.json +++ b/website/package.json @@ -5,7 +5,7 @@ "bower": "^1.3.9", "del": "^0.1.1", "dgeni": "^0.4.1", - "dgeni-packages": "^0.10.19", + "dgeni-packages": "^0.11.1", "esprima": "1.1.0", "gulp": "^3.8.7", "gulp-concat": "^2.3.4", @@ -15,12 +15,12 @@ "gulp-minify-css": "^0.3.7", "gulp-rename": "^1.2.0", "gulp-replace": "^0.4.0", + "jasmine": "2.3.2", "karma": "^0.12.21", "karma-chrome-launcher": "^0.1.4", "karma-jasmine": "^0.1.5", "lodash": "^2.4.1", - "marked": "^0.3.3", - "jasmine": "2.3.2" + "marked": "^0.3.3" }, "scripts": { "prepublish": "./node_modules/bower/bin/bower install", From 5c8b88e993bb1156bf6695658cda99eb9ffe78b5 Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Mon, 16 Nov 2015 14:34:46 -0800 Subject: [PATCH 025/678] chore(plugins): Better error message for invalid plugin paths Closes #2348 --- lib/plugins.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/plugins.js b/lib/plugins.js index b275e119b..d2c60db1f 100644 --- a/lib/plugins.js +++ b/lib/plugins.js @@ -27,6 +27,9 @@ var Plugins = function(config) { if (pluginConf.path) { path = ConfigParser.resolveFilePatterns(pluginConf.path, true, config.configDir)[0]; + if (!path) { + throw new Error('Invalid path to plugin: ' + pluginConf.path); + } } else { path = pluginConf.package; } From 63e330d24f75162a8a603bdde6d0a68a8af555ca Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Mon, 16 Nov 2015 15:12:31 -0800 Subject: [PATCH 026/678] chore(error message): make error message for client-side navigation clearer Closes #2643 --- lib/clientsidescripts.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/clientsidescripts.js b/lib/clientsidescripts.js index 092022888..fdfc935b7 100644 --- a/lib/clientsidescripts.js +++ b/lib/clientsidescripts.js @@ -56,7 +56,10 @@ functions.waitForAngular = function(rootSelector, callback) { return; } if (!window.angular) { - throw new Error('angular could not be found on the window'); + throw new Error('window.angular is undefined. This could be either ' + + 'because this is a non-angular page or because your test involves ' + + 'client-side navigation, which can interfere with Protractor\'s ' + + 'bootstrapping. See http://git.io/v4gXM for details'); } if (angular.getTestability) { angular.getTestability(el).whenStable(callback); From 1f44a6ef3f7ae8680a03a3cc7a7c06f75a8c7d4c Mon Sep 17 00:00:00 2001 From: Julie Ralph Date: Tue, 17 Nov 2015 14:45:41 -0800 Subject: [PATCH 027/678] chore(deps): bump chromedriver and iedriver versions IEDriver from 2.47.0 to 2.48.0 ChromeDriver from 2.19 to 2.20. Changelog: http://chromedriver.storage.googleapis.com/2.20/notes.txt --- config.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/config.json b/config.json index b02dff369..898633fc9 100644 --- a/config.json +++ b/config.json @@ -1,7 +1,7 @@ { "webdriverVersions": { "selenium": "2.48.2", - "chromedriver": "2.19", - "iedriver": "2.47.0" + "chromedriver": "2.20", + "iedriver": "2.48.0" } } From 12d030879103e981c222293d2d1f56bef217e341 Mon Sep 17 00:00:00 2001 From: Julie Ralph Date: Tue, 17 Nov 2015 14:50:23 -0800 Subject: [PATCH 028/678] chore(ci): bump to latest 2 versions of ie, chrome, safari --- spec/ciFullConf.js | 4 ++-- spec/ciSmokeConf.js | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/spec/ciFullConf.js b/spec/ciFullConf.js index de363d079..0c909faa6 100644 --- a/spec/ciFullConf.js +++ b/spec/ciFullConf.js @@ -22,7 +22,7 @@ exports.config = { 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, 'build': process.env.TRAVIS_BUILD_NUMBER, 'name': 'Protractor suite tests', - 'version': '45', + 'version': '46', 'selenium-version': '2.48.2', 'chromedriver-version': '2.19', 'platform': 'OS X 10.9' @@ -31,7 +31,7 @@ exports.config = { 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, 'build': process.env.TRAVIS_BUILD_NUMBER, 'name': 'Protractor suite tests', - 'version': '40', + 'version': '42', 'selenium-version': '2.48.2' }], diff --git a/spec/ciSmokeConf.js b/spec/ciSmokeConf.js index 9ca49c89a..4f76e21f4 100644 --- a/spec/ciSmokeConf.js +++ b/spec/ciSmokeConf.js @@ -23,7 +23,7 @@ exports.config = { 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, 'build': process.env.TRAVIS_BUILD_NUMBER, 'name': 'Protractor smoke tests', - 'version': '44', + 'version': '45', 'selenium-version': '2.48.2', 'chromedriver-version': '2.19', 'platform': 'OS X 10.9' @@ -32,14 +32,14 @@ exports.config = { 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, 'build': process.env.TRAVIS_BUILD_NUMBER, 'name': 'Protractor smoke tests', - 'version': '39', + 'version': '41', 'selenium-version': '2.48.2' }, { 'browserName': 'safari', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, 'build': process.env.TRAVIS_BUILD_NUMBER, 'name': 'Protractor smoke tests', - 'version': '7', + 'version': '8', 'selenium-version': '2.44.0' // Use an old version because Safari has // issues loading pages after 2.44. }, { @@ -47,7 +47,7 @@ exports.config = { 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, 'build': process.env.TRAVIS_BUILD_NUMBER, 'name': 'Protractor smoke tests', - 'version': '8', + 'version': '9', 'selenium-version': '2.44.0' }, { 'browserName': 'internet explorer', From d57bdc2d3ba879c90d8ca01b3c0b5f8ab7e4ded4 Mon Sep 17 00:00:00 2001 From: Julie Ralph Date: Tue, 17 Nov 2015 15:07:22 -0800 Subject: [PATCH 029/678] fix(tests): fix error tests after testapp api slight rename x /slowcall -> slowcall --- scripts/test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/test.js b/scripts/test.js index fb88ae97d..f35b59ffb 100755 --- a/scripts/test.js +++ b/scripts/test.js @@ -110,7 +110,7 @@ executor.addCommandlineTest('node lib/cli.js spec/errorTest/pluginsFailingConf.j executor.addCommandlineTest('node lib/cli.js spec/errorTest/slowHttpAndTimeoutConf.js') .expectExitCode(1) .expectErrors([ - {message: 'The following tasks were pending[\\s\\S]*\\$http: \/slowcall'}, + {message: 'The following tasks were pending[\\s\\S]*\\$http: slowcall'}, {message: 'The following tasks were pending[\\s\\S]*' + '\\$timeout: function \\(\\) {[\\s\\S]*' + '\\$scope\\.slowAngularTimeoutStatus = \'done\';[\\s\\S]' + @@ -121,7 +121,7 @@ executor.addCommandlineTest('node lib/cli.js spec/errorTest/slowHttpAndTimeoutCo '--untrackOutstandingTimeouts true') .expectExitCode(1) .expectErrors([ - {message: 'The following tasks were pending[\\s\\S]*\\$http: \/slowcall'}, + {message: 'The following tasks were pending[\\s\\S]*\\$http: slowcall'}, {message: '^((?!The following tasks were pending).)*$'} ]); From 1a8bb5357ccc254ce9453972fee8521efbeb0a4d Mon Sep 17 00:00:00 2001 From: Julie Ralph Date: Tue, 17 Nov 2015 16:59:20 -0800 Subject: [PATCH 030/678] chore(release): changelog and version bump for 3.0.0 --- CHANGELOG.md | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++ package.json | 6 ++-- 2 files changed, 82 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 54aeec97c..8de89e680 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,83 @@ +# 3.0.0 + +_We're releasing version 3.0 with some breaking changes. In summary - Jasmine 1.3 is removed, only Jasmine 2 is now supported, old Node.JS support is dropped, and plugins now need to be explicitly required. Full details below._ + +## Dependency Version Upgrades + +- ([18e1f71](https://github.com/angular/protractor/commit/18e1f71a4dd868709f4e259e05a8a196921e22be)) + chore(webdriver): upgrade Protractor to webdriver 2.48.2 + +- ([1f44a6e](https://github.com/angular/protractor/commit/1f44a6ef3f7ae8680a03a3cc7a7c06f75a8c7d4c)) + chore(deps): bump chromedriver and iedriver versions IEDriver from 2.47.0 to 2.48.0 + + ChromeDriver from 2.19 to 2.20. Changelog: + http://chromedriver.storage.googleapis.com/2.20/notes.txt + +## Features + +- ([97e6703](https://github.com/angular/protractor/commit/97e6703eb0e7a5dffc1017d0a44f0dfeeb91f327)) + feat(protractor): Add protractor.prototype.restart + +- ([2007f06](https://github.com/angular/protractor/commit/2007f06078b6569a2cfd9f361f17d765c07bc7f8)) + feat(protractor): add flag to stop protractor from tracking $timeout + +- ([a40a4ba](https://github.com/angular/protractor/commit/a40a4ba2a509bc762f1f5937454fdbf074405f07)) + feat(ElementArrayFinder#get): Implemented ability to pass promise as index to + ElementArrayFinder#get + +- ([a54c0e0](https://github.com/angular/protractor/commit/a54c0e0d72b9d7d1d8364ade5046e5007ff53906)) + feat(plugins): Add config option to disable logging of warnings in console plugin + + Running tests in multiple browsers ends up printing out a lot of useless warnings I'm already + aware of. To make skimming through logs in the case of an actual failure easier, I want to be able + to disable the logging of warnings in the console plugin. + +- ([7015010](https://github.com/angular/protractor/commit/7015010188dfb70c1e49e4f2eae19d5ba1126b34)) + feat(driver providers): Add BrowserStack support. + + Also added BrowserStack to CI + +## Bug Fixes + +- ([7cba4ec](https://github.com/angular/protractor/commit/7cba4ecf0f3915dfec33dbc04decd42857744b37)) + fix(ng-repeat): properly detect the end of an ng-repeat-start block + + Discovered while investigating issue #2365 + +## Breaking Changes + +- ([2bde92b](https://github.com/angular/protractor/commit/2bde92b3e745e09ad3876932b2d187365e9aaa31)) + chore(jasmine): remove jasmine 1.3 + + and update docs. Also, use jasmine 2 for running all Protractor's unit tests. + + BREAKING CHANGE: Now, both jasmine and jasmine2 frameworks use jasmine 2.3. Users still using + jasmine version <2 will have to upgrade. + +- ([18e1f71](https://github.com/angular/protractor/commit/18e1f71a4dd868709f4e259e05a8a196921e22be)) + chore(webdriver): upgrade Protractor to webdriver 2.48.2 + + BREAKING CHANGE: 1) Users will no longer be able to use node versions <4. 2) There is significant + changes to the control flow, and tests may need to be + modified to be compliant with the new control flow. See + https://github.com/SeleniumHQ/selenium/blob/master/javascript/node/selenium-webdriver/CHANGES.md + +- ([ac1e21e](https://github.com/angular/protractor/commit/ac1e21e7e09a773de981bf9e70b0fcd489d17a83)) + chore(plugins): Split first party plugins into seperate repos + + BREAKING CHANGE: + + The Accessibility, NgHint, Timeline, and Console plugins are now located in their own separate + node modules. You will need to explicitly require each module you use. See https://github.com/angular/protractor/blob/master/docs/plugins.md#first-party-plugins for info for each module. + +- ([ddb8584](https://github.com/angular/protractor/commit/ddb8584a59343284904676ef6d8db5c1c996b900)) + chore(cucumber): Remove cucumber from internal implementation + + BREAKING CHANGE: + + Cucumber has been community maintianed for a while, and in order to allow it to move faster, it is no longer part of the core Protractor library. It is now published on npm under `protractor-cucumber-framework` and will require setting `frameworkPath` in your configuration file. See https://github.com/angular/protractor/blob/master/docs/frameworks.md#using-cucumber for full instructions on use now. + + # 2.5.1 _This release is a hotfix for node 0.10 support_ diff --git a/package.json b/package.json index 7d5e99d1e..3e6205db1 100644 --- a/package.json +++ b/package.json @@ -22,9 +22,7 @@ "optimist": "~0.6.0", "q": "1.0.0", "lodash": "~2.4.1", - "source-map-support": "~0.3.2", - "html-entities": "~1.1.1", - "accessibility-developer-tools": "~2.6.0" + "source-map-support": "~0.3.2" }, "devDependencies": { "expect.js": "~0.2.0", @@ -50,5 +48,5 @@ "start": "node testapp/scripts/web-server.js" }, "license": "MIT", - "version": "2.5.1" + "version": "3.0.0" } From f080ac8edbd2c23075a589a8126fd9333211bc1b Mon Sep 17 00:00:00 2001 From: Julie Ralph Date: Tue, 17 Nov 2015 19:29:29 -0800 Subject: [PATCH 031/678] docs(contributing): mention the test application Strengthening the plea to include a reproducible test case, now with test app! --- CONTRIBUTING.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c0834cca7..bce989178 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,14 +16,15 @@ Thank you! Issues ------- +====== If you have a bug or feature request, please file an issue. Before submitting an issue, please search the issue archive to help reduce duplicates, and read the [FAQ](https://github.com/angular/protractor/blob/master/docs/faq.md). -When submitting an issue, please include context from your test and -your application. Include a reproducible case that we can actually run, if possible. If there's an error, please include the error text. Try running with troubleshooting messages (`protractor --troubleshoot`) against your configuration to make sure that there is not an error with your setup. +Try running with troubleshooting messages (`protractor --troubleshoot`) against your configuration to make sure that there is not an error with your setup. + +When submitting an issue, please include a reproducible case that we can actually run. Protractor has a test Angular application available at `http://www.protractortest.org/testapp` which you can use for the reproducible test case. If there's an error, please include the error text. Please format code and markup in your issue using [github markdown](https://help.github.com/articles/github-flavored-markdown). From 2ae1ec36a49629bf923b299e0a7f2a136e8ec655 Mon Sep 17 00:00:00 2001 From: Julie Ralph Date: Tue, 17 Nov 2015 19:36:43 -0800 Subject: [PATCH 032/678] docs(element): improve docs for evalute Closes #2323 --- lib/element.js | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/lib/element.js b/lib/element.js index 4716ed9ad..1d3d4cc6d 100644 --- a/lib/element.js +++ b/lib/element.js @@ -553,10 +553,10 @@ ElementArrayFinder.prototype.reduce = function(reduceFn, initialValue) { * elements. * * @view - * {{variableInScope}} + * {{variableInScope}} * * @example - * var value = element(by.id('foo')).evaluate('variableInScope'); + * var value = element.all(by.css('.foo')).evaluate('variableInScope'); * * @param {string} expression * @@ -932,6 +932,12 @@ ElementFinder.prototype.isElementPresent = function(subLocator) { * Evaluates the input as if it were on the scope of the current element. * @see ElementArrayFinder.evaluate * + * @view + * {{variableInScope}} + * + * @example + * var value = element(by.id('foo')).evaluate('variableInScope'); + * * @param {string} expression * * @return {ElementFinder} which resolves to the evaluated expression. From 5fa86dc477b9502a046bac38179f5134e2dcd449 Mon Sep 17 00:00:00 2001 From: Julie Ralph Date: Tue, 17 Nov 2015 19:46:24 -0800 Subject: [PATCH 033/678] docs(faq): fix XML reporter documentation Closes #2491 --- docs/faq.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/docs/faq.md b/docs/faq.md index d337db8fd..fd4b7c130 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -136,7 +136,16 @@ jasmine.Spec.prototype.addExpectationResult = function() { How do I produce an XML report of my test results? -------------------------------------------------- -You can use the npm package jasmine-reporters@1.0.0 and add a JUnit XML Reporter. Check out this [example (junitOutputConf.js)](https://github.com/angular/protractor/blob/master/spec/junitOutputConf.js). Make sure that you are using the correct version of jasmine-reporters for your version of Jasmine. +You can use the npm package jasmine-reporters@^2.0.0 and add a JUnit XML Reporter in the `onPrepare` block. This would look something like: + +``` +var jasmineReporters = require('jasmine-reporters'); +jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({ + consolidateAll: true, + savePath: 'testresults', + filePrefix: 'reportXMLoutput' +})); +``` How can I catch errors such as ElementNotFound? ----------------------------------------------- From 1ad647fba00cf03459a9ec8a83e6006914e7688d Mon Sep 17 00:00:00 2001 From: Julie Ralph Date: Tue, 17 Nov 2015 19:53:05 -0800 Subject: [PATCH 034/678] docs(addMockModules): improve messaging around browser context Closes #2628 --- lib/protractor.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/protractor.js b/lib/protractor.js index 6f2769257..511ede4cc 100644 --- a/lib/protractor.js +++ b/lib/protractor.js @@ -485,6 +485,8 @@ Protractor.prototype.isElementPresent = function(locatorOrElement) { * * @param {!string} name The name of the module to load or override. * @param {!string|Function} script The JavaScript to load the module. + * Note that this will be executed in the browser context, so it cannot + * access variables from outside its scope. * @param {...*} varArgs Any additional arguments will be provided to * the script and may be referenced using the `arguments` object. */ From 950d3eeb7784e0666967e53c3cbaa7b12be697a3 Mon Sep 17 00:00:00 2001 From: Ariel Serafini Date: Wed, 18 Nov 2015 16:14:19 -0200 Subject: [PATCH 035/678] docs(changelog): fix minor typo --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8de89e680..7df632c2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -75,7 +75,7 @@ _We're releasing version 3.0 with some breaking changes. In summary - Jasmine 1. BREAKING CHANGE: - Cucumber has been community maintianed for a while, and in order to allow it to move faster, it is no longer part of the core Protractor library. It is now published on npm under `protractor-cucumber-framework` and will require setting `frameworkPath` in your configuration file. See https://github.com/angular/protractor/blob/master/docs/frameworks.md#using-cucumber for full instructions on use now. + Cucumber has been community maintained for a while, and in order to allow it to move faster, it is no longer part of the core Protractor library. It is now published on npm under `protractor-cucumber-framework` and will require setting `frameworkPath` in your configuration file. See https://github.com/angular/protractor/blob/master/docs/frameworks.md#using-cucumber for full instructions on use now. # 2.5.1 From 148f020bf4bbd71e17326581a2f7ed6f4ff55832 Mon Sep 17 00:00:00 2001 From: gkohen Date: Wed, 17 Jun 2015 10:57:34 -0400 Subject: [PATCH 036/678] feat(protractor): Add support to allow Protractor to test an Angular application which has debugging info disabled Currently Angular application which for performance reasons, have debug information turn off cannot be tested. This PR allows users to add the Angular debug logging flag to the Protractor run. --- lib/protractor.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/protractor.js b/lib/protractor.js index 511ede4cc..3524b4fdb 100644 --- a/lib/protractor.js +++ b/lib/protractor.js @@ -17,6 +17,7 @@ var ExpectedConditions = require('./expectedConditions.js'); /* global angular */ var DEFER_LABEL = 'NG_DEFER_BOOTSTRAP!'; +var ENABLE_DEBUG_INFO_LABEL = 'NG_ENABLE_DEBUG_INFO!'; var DEFAULT_RESET_URL = 'data:text/html,'; var DEFAULT_GET_PAGE_TIMEOUT = 10000; @@ -632,7 +633,7 @@ Protractor.prototype.get = function(destination, opt_timeout) { this.driver.get(this.resetUrl).then(null, deferred.reject); this.executeScript_( - 'window.name = "' + DEFER_LABEL + '" + window.name;' + + 'window.name = "' + DEFER_LABEL + ENABLE_DEBUG_INFO_LABEL + '" + window.name;' + 'window.location.replace("' + destination + '");', msg('reset url')) .then(null, deferred.reject); From b110ed92442eb8b14768c512a890bb3ceb0e4973 Mon Sep 17 00:00:00 2001 From: Hank Duan Date: Thu, 3 Dec 2015 14:57:20 -0800 Subject: [PATCH 037/678] feat(debugger): allow multiple browser.pause() After this change, you can put multiple browser.pause() in the code. Each browser.pause() is like a traditional breakpoint. To detach from the debugger, press ^D (CTRL+D). This will continue code execution until it hits the next browser.pause() or code finishes running. This PR also fixes a number of small formatting issues. --- lib/debugger/clients/explorer.js | 20 ++---- lib/debugger/clients/wddebugger.js | 28 ++------ lib/debugger/modes/debuggerRepl.js | 7 +- lib/protractor.js | 109 +++++++++++++++++++++-------- 4 files changed, 93 insertions(+), 71 deletions(-) diff --git a/lib/debugger/clients/explorer.js b/lib/debugger/clients/explorer.js index b961d7a14..1fd9f0ab9 100644 --- a/lib/debugger/clients/explorer.js +++ b/lib/debugger/clients/explorer.js @@ -12,15 +12,6 @@ var WdRepl = function() { this.client; }; -/** - * Initiate debugger client. - * @private - */ -WdRepl.prototype.initClient_ = function() { - this.client = - debuggerCommons.attachDebugger(process.argv[2], process.argv[3]); -}; - /** * Instantiate a server to handle IO. * @param {number} port The port to start the server. @@ -143,12 +134,11 @@ WdRepl.prototype.initReplOrServer_ = function() { * @public */ WdRepl.prototype.init = function() { - console.log('Type to see a list of locator strategies.'); - console.log('Use the `list` helper function to find elements by strategy:'); - console.log(' e.g., list(by.binding(\'\')) gets all bindings.'); - - this.initClient_(); - this.initReplOrServer_(); + var self = this; + this.client = debuggerCommons.attachDebugger(process.argv[2], process.argv[3]); + this.client.once('ready', function() { + self.initReplOrServer_(); + }); }; var wdRepl = new WdRepl(); diff --git a/lib/debugger/clients/wddebugger.js b/lib/debugger/clients/wddebugger.js index 5ff454165..7be4427fa 100644 --- a/lib/debugger/clients/wddebugger.js +++ b/lib/debugger/clients/wddebugger.js @@ -21,24 +21,6 @@ var WdDebugger = function() { this.currentRepl; }; -/** - * Initiate debugger client. - * @private - */ -WdDebugger.prototype.initClient_ = function() { - this.client = - debuggerCommons.attachDebugger(process.argv[2], process.argv[3]); - this.client.once('ready', function() { - console.log(' ready\n'); - console.log('press c to continue to the next webdriver command'); - console.log('press d to continue to the next debugger statement'); - console.log('type "repl" to enter interactive mode'); - console.log('type "exit" to break out of interactive mode'); - console.log('press ^C to exit'); - console.log(); - }); -}; - /** * Eval function for processing a single step in repl. * @private @@ -116,7 +98,7 @@ WdDebugger.prototype.initRepl_ = function() { self.replServer.complete = self.currentRepl.complete.bind(self.currentRepl); self.replServer.on('exit', function() { - console.log('Exiting debugger.'); + console.log('Resuming code execution'); self.client.req({command: 'disconnect'}, function() { // Intentionally blank. }); @@ -129,9 +111,11 @@ WdDebugger.prototype.initRepl_ = function() { * @public */ WdDebugger.prototype.init = function() { - console.log('------- WebDriver Debugger -------'); - this.initClient_(); - this.initRepl_(); + var self = this; + this.client = debuggerCommons.attachDebugger(process.argv[2], process.argv[3]); + this.client.once('ready', function() { + self.initRepl_(); + }); }; var wdDebugger = new WdDebugger(); diff --git a/lib/debugger/modes/debuggerRepl.js b/lib/debugger/modes/debuggerRepl.js index 18753ca3d..55592c7ad 100644 --- a/lib/debugger/modes/debuggerRepl.js +++ b/lib/debugger/modes/debuggerRepl.js @@ -1,7 +1,7 @@ var util = require('util'); var DBG_INITIAL_SUGGESTIONS = - ['repl', 'c', 'frame', 'scopes', 'scripts', 'source', 'backtrace', 'd']; + ['repl', 'c', 'frame', 'scopes', 'scripts', 'source', 'backtrace']; /** * Repl to step through code. @@ -60,11 +60,6 @@ DebuggerRepl.prototype.stepEval = function(cmd, callback) { callback(); }); break; - case 'd': - this.client.req({command: 'disconnect'}, function() { - // Intentionally blank. - }); - break; default: console.log('Unrecognized command.'); callback(); diff --git a/lib/protractor.js b/lib/protractor.js index 3524b4fdb..e9b21da4a 100644 --- a/lib/protractor.js +++ b/lib/protractor.js @@ -824,6 +824,48 @@ Protractor.prototype.debugger = function() { 'add breakpoint to control flow'); }; +/** + * Validates that the port is free to use. This will only validate the first + * time it is called. The reason is that on subsequent calls, the port will + * already be bound to the debugger, so it will not be available, but that is + * okay. + * + * @return {Promise} A promise that becomes ready when the validation + * is done. The promise will resolve to a boolean which represents whether + * this is the first time that the debugger is called. + */ +Protractor.prototype.validatePortAvailability_ = function(port) { + if (this.debuggerValidated_) { + return webdriver.promise.fulfilled(false); + } + this.debuggerValidated_ = true; + + var doneDeferred = webdriver.promise.defer(); + + // Resolve doneDeferred if port is available. + var net = require('net'); + var tester = net.connect({port: port}, function() { + doneDeferred.reject('Port ' + port + + ' is already in use. Please specify ' + 'another port to debug.'); + }); + tester.once('error', function (err) { + if (err.code === 'ECONNREFUSED') { + tester.once('close', function() { + doneDeferred.fulfill(true); + }).end(); + } else { + doneDeferred.reject( + 'Unexpected failure testing for port ' + port + ': ' + + JSON.stringify(err)); + } + }); + + return doneDeferred.then(null, function(err) { + console.error(err); + process.exit(1); + }); +}, + /** * Helper function to: * 1) Set up helper functions for debugger clients to call on (e.g. @@ -831,10 +873,13 @@ Protractor.prototype.debugger = function() { * 2) Enter process into debugger mode. (i.e. process._debugProcess). * 3) Invoke the debugger client specified by debuggerClientPath. * - * @param {string=} debuggerClientPath Absolute path of debugger client to use + * @param {string} debuggerClientPath Absolute path of debugger client to use + * @param {Function} onStartFn Function to call when the debugger starts. The + * function takes a single parameter, which represents whether this is the + * first time that the debugger is called. * @param {number=} opt_debugPort Optional port to use for the debugging process */ -Protractor.prototype.initDebugger_ = function(debuggerClientPath, opt_debugPort) { +Protractor.prototype.initDebugger_ = function(debuggerClientPath, onStartFn, opt_debugPort) { // Patch in a function to help us visualize what's going on in the control // flow. webdriver.promise.ControlFlow.prototype.getControlFlowText = function() { @@ -847,26 +892,6 @@ Protractor.prototype.initDebugger_ = function(debuggerClientPath, opt_debugPort) // hackier, and involves messing with the control flow's internals / private // variables. return helper.filterStackTrace(controlFlowText); - - }; - - // Invoke fn if port is available. - var onPortAvailable = function(port, fn) { - var net = require('net'); - var tester = net.connect({port: port}, function() { - console.error('Port ' + port + ' is already in use. Please specify ' + - 'another port to debug.'); - process.exit(1); - }); - tester.once('error', function (err) { - if (err.code === 'ECONNREFUSED') { - tester.once('close', fn).end(); - } else { - console.error('Unexpected failure testing for port ' + port + ': ', - err); - process.exit(1); - } - }); }; var vm_ = require('vm'); @@ -892,11 +917,11 @@ Protractor.prototype.initDebugger_ = function(debuggerClientPath, opt_debugPort) var browserUnderDebug = this; var debuggerReadyPromise = webdriver.promise.defer(); - flow.execute(function() { - log.puts('Starting WebDriver debugger in a child process. Pause is ' + - 'still beta, please report issues at github.com/angular/protractor\n'); + flow.execute(function() { process.debugPort = opt_debugPort || process.debugPort; - onPortAvailable(process.debugPort, function() { + browserUnderDebug.validatePortAvailability_(process.debugPort).then(function(firstTime) { + onStartFn(firstTime); + var args = [process.pid, process.debugPort]; if (browserUnderDebug.debuggerServerPort_) { args.push(browserUnderDebug.debuggerServerPort_); @@ -1038,7 +1063,19 @@ Protractor.prototype.initDebugger_ = function(debuggerClientPath, opt_debugPort) */ Protractor.prototype.enterRepl = function(opt_debugPort) { var debuggerClientPath = __dirname + '/debugger/clients/explorer.js'; - this.initDebugger_(debuggerClientPath, opt_debugPort); + var onStartFn = function() { + log.puts(); + log.puts('------- Element Explorer -------'); + log.puts('Starting WebDriver debugger in a child process. Element ' + + 'Explorer is still beta, please report issues at ' + + 'github.com/angular/protractor'); + log.puts(); + log.puts('Type to see a list of locator strategies.'); + log.puts('Use the `list` helper function to find elements by strategy:'); + log.puts(' e.g., list(by.binding(\'\')) gets all bindings.'); + log.puts(); + }; + this.initDebugger_(debuggerClientPath, onStartFn, opt_debugPort); }; /** @@ -1059,7 +1096,23 @@ Protractor.prototype.enterRepl = function(opt_debugPort) { */ Protractor.prototype.pause = function(opt_debugPort) { var debuggerClientPath = __dirname + '/debugger/clients/wddebugger.js'; - this.initDebugger_(debuggerClientPath, opt_debugPort); + var onStartFn = function(firstTime) { + log.puts(); + log.puts('Encountered browser.pause(). Attaching debugger...'); + if (firstTime) { + log.puts(); + log.puts('------- WebDriver Debugger -------'); + log.puts('Starting WebDriver debugger in a child process. Pause is ' + + 'still beta, please report issues at github.com/angular/protractor'); + log.puts(); + log.puts('press c to continue to the next webdriver command'); + log.puts('press ^D to detach debugger and resume code execution'); + log.puts('type "repl" to enter interactive mode'); + log.puts('type "exit" to break out of interactive mode'); + log.puts(); + } + }; + this.initDebugger_(debuggerClientPath, onStartFn, opt_debugPort); }; /** From 01de64fa377779b1213e436eb1b1b83a0ad6b4f4 Mon Sep 17 00:00:00 2001 From: Nick Tomlin Date: Mon, 21 Dec 2015 17:23:53 -0600 Subject: [PATCH 038/678] chore(README): Add gitter badge and info to README --- README.md | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index ac0fa0d06..ae7b64104 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -Protractor [![Build Status](https://travis-ci.org/angular/protractor.png?branch=master)](https://travis-ci.org/angular/protractor) +Protractor [![Build Status](https://travis-ci.org/angular/protractor.png?branch=master)](https://travis-ci.org/angular/protractor) [![Join the chat at https://gitter.im/angular/protractor](https://badges.gitter.im/angular/protractor.svg)](https://gitter.im/angular/protractor) ========== [Protractor](http://angular.github.io/protractor) is an end-to-end test framework for [AngularJS](http://angularjs.org/) applications. Protractor is a [Node.js](http://nodejs.org/) program built on top of [WebDriverJS](https://github.com/SeleniumHQ/selenium/wiki/WebDriverJs). Protractor runs tests against your application running in a real browser, interacting with it as a user would. @@ -22,17 +22,9 @@ To better understand how Protractor works with the Selenium WebDriver and Seleni Getting Help ------------ -Check the -[Protractor FAQ](https://github.com/angular/protractor/blob/master/docs/faq.md) -and read through -the [Top 20 questions on StackOverflow](http://stackoverflow.com/questions/tagged/protractor?sort=votes&pageSize=20). - -Please ask usage and debugging questions on -[StackOverflow](http://stackoverflow.com/questions/tagged/protractor) (use -the "protractor" tag) -or in the -[Angular discussion group](https://groups.google.com/forum/?fromgroups#!forum/angular). -(Please do not ask support questions here on Github.) +Check the [Protractor FAQ](https://github.com/angular/protractor/blob/master/docs/faq.md) and read through the [Top 20 questions on StackOverflow](http://stackoverflow.com/questions/tagged/protractor?sort=votes&pageSize=20). + +Please ask usage and debugging questions on [StackOverflow](http://stackoverflow.com/questions/tagged/protractor) (use the ["protractor"](http://stackoverflow.com/questions/ask?tags=protractor) tag), the [Gitter](https://gitter.im/angular/protractor) chat room, or in the [Angular discussion group](https://groups.google.com/forum/?fromgroups#!forum/angular). (Please do not ask support questions here on Github.) For Contributors From 54dd3dbd6e44284730ed9bf394ee1162fc4f862d Mon Sep 17 00:00:00 2001 From: jakub-g Date: Tue, 24 Nov 2015 13:39:08 +0100 Subject: [PATCH 039/678] docs(readme): compatibility with node --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index ae7b64104..af53511d1 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,12 @@ Protractor [![Build Status](https://travis-ci.org/angular/protractor.png?branch= [Protractor](http://angular.github.io/protractor) is an end-to-end test framework for [AngularJS](http://angularjs.org/) applications. Protractor is a [Node.js](http://nodejs.org/) program built on top of [WebDriverJS](https://github.com/SeleniumHQ/selenium/wiki/WebDriverJs). Protractor runs tests against your application running in a real browser, interacting with it as a user would. +Compatibility +------------- + +Protractor 3 is compatible with nodejs v4 and newer. + +When using nodejs v0.12, use protractor 2 (`npm install -g protractor@2`). Getting Started --------------- From 90dfa727455695f526be9e197e9dac73f8117288 Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Tue, 24 Nov 2015 21:17:56 -0800 Subject: [PATCH 040/678] chore(docs): fix comment on ElementFinter.prototype.evaluate Closes #2723 --- lib/element.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/element.js b/lib/element.js index 1d3d4cc6d..80b2e9630 100644 --- a/lib/element.js +++ b/lib/element.js @@ -930,7 +930,7 @@ ElementFinder.prototype.isElementPresent = function(subLocator) { /** * Evaluates the input as if it were on the scope of the current element. - * @see ElementArrayFinder.evaluate + * @see ElementArrayFinder.prototype.evaluate * * @view * {{variableInScope}} From d2c9082c59a682167c7110ee722df80119c2affc Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Tue, 24 Nov 2015 21:45:33 -0800 Subject: [PATCH 041/678] chore(docs): fix link in webdriver v protractor Closes #2738 --- docs/webdriver-vs-protractor.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/webdriver-vs-protractor.md b/docs/webdriver-vs-protractor.md index c40f9ec83..b22b3fe65 100644 --- a/docs/webdriver-vs-protractor.md +++ b/docs/webdriver-vs-protractor.md @@ -34,7 +34,7 @@ Using ElementFinders In Protractor, you use the `element` function to find and interact with elements through an `ElementFinder` object. This extends a WebDriver `WebElement` by adding chaining and utilities for dealing with lists. See -[locators#actions](/docs/locators) for details. +[locators#actions](/docs/locators.md#actions) for details. Jasmine Integration ------------------- From 3f622bc0e0164021f1e04d3dba72d0e258f47519 Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Wed, 25 Nov 2015 13:31:53 -0800 Subject: [PATCH 042/678] chore(docs): include information about using `suite` property in config file --- docs/referenceConf.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/referenceConf.js b/docs/referenceConf.js index 04548b936..5e7e226d2 100644 --- a/docs/referenceConf.js +++ b/docs/referenceConf.js @@ -99,6 +99,9 @@ exports.config = { smoke: 'spec/smoketests/*.js', full: 'spec/*.js' }, + // If you would like protractor to use a specific suite by default instead of + // all suites, you can put that in the config file as well. + suite: null, // --------------------------------------------------------------------------- // ----- How to set up browsers ---------------------------------------------- From f533341085921409d16d577e38ba1745c37a17b7 Mon Sep 17 00:00:00 2001 From: Dmitry Shirokov Date: Fri, 11 Dec 2015 14:44:21 +1100 Subject: [PATCH 043/678] bug(driverProvider): fix driver path generation for *nix platforms Makes error messages better --- README.md | 3 ++- lib/driverProviders/direct.js | 17 ++++++++--------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index af53511d1..9683166ff 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ Protractor [![Build Status](https://travis-ci.org/angular/protractor.png?branch=master)](https://travis-ci.org/angular/protractor) [![Join the chat at https://gitter.im/angular/protractor](https://badges.gitter.im/angular/protractor.svg)](https://gitter.im/angular/protractor) ========== -[Protractor](http://angular.github.io/protractor) is an end-to-end test framework for [AngularJS](http://angularjs.org/) applications. Protractor is a [Node.js](http://nodejs.org/) program built on top of [WebDriverJS](https://github.com/SeleniumHQ/selenium/wiki/WebDriverJs). Protractor runs tests against your application running in a real browser, interacting with it as a user would. +[Protractor](http://angular.github.io/protractor) is an end-to-end test framework for [AngularJS](http://angularjs.org/) applications. Protractor is a [Node.js](http://nodejs.org/) program built on top of [WebDriverJS](https://github.com/SeleniumHQ/selenium/wiki/WebDriverJs). Protractor runs tests against your application running in a real browser, interacting with it as a user would. Compatibility ------------- @@ -40,6 +40,7 @@ Clone the github repository: git clone https://github.com/angular/protractor.git cd protractor npm install + ./bin/webdriver-manager update cd website npm install cd .. diff --git a/lib/driverProviders/direct.js b/lib/driverProviders/direct.js index 6f1ff71c4..f8155f048 100644 --- a/lib/driverProviders/direct.js +++ b/lib/driverProviders/direct.js @@ -51,17 +51,16 @@ DirectDriverProvider.prototype.getNewDriver = function() { var driver; switch (this.config_.capabilities.browserName) { case 'chrome': - var chromeDriverFile = this.config_.chromeDriver || - path.resolve(__dirname, '../../selenium/chromedriver'); + var defaultChromeDriverPath = path.resolve(__dirname, '../../selenium/chromedriver'); + + if (process.platform.indexOf('win') === 0) { + defaultChromeDriverPath += '.exe'; + } + + var chromeDriverFile = this.config_.chromeDriver || defaultChromeDriverPath; - // Check if file exists, if not try .exe or fail accordingly if (!fs.existsSync(chromeDriverFile)) { - chromeDriverFile += '.exe'; - // Throw error if the client specified conf chromedriver and its not found - if (!fs.existsSync(chromeDriverFile)) { - throw new Error('Could not find chromedriver at ' + - chromeDriverFile); - } + throw new Error('Could not find chromedriver at ' + chromeDriverFile); } var service = new chrome.ServiceBuilder(chromeDriverFile).build(); From dbde3c6f2a7d88761fd283cd3caeeb55d793a87a Mon Sep 17 00:00:00 2001 From: Nick Tomlin Date: Thu, 10 Dec 2015 22:21:56 -0600 Subject: [PATCH 044/678] chore(style): Add "curly" rule to jshintrc --- .jshintrc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.jshintrc b/.jshintrc index 8e63f0f1f..d87c2efaa 100644 --- a/.jshintrc +++ b/.jshintrc @@ -17,5 +17,6 @@ "sub": true, "undef": true, "quotmark": "single", - "evil": true + "evil": true, + "curly": true } From 34797c047a9016b6a46f274d5936f6512dd373bc Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Fri, 11 Dec 2015 14:52:15 -0800 Subject: [PATCH 045/678] chore(taskScheduler): remove redundent resolve --- lib/taskScheduler.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/lib/taskScheduler.js b/lib/taskScheduler.js index 4dbf80b0f..9a0533f19 100644 --- a/lib/taskScheduler.js +++ b/lib/taskScheduler.js @@ -45,10 +45,9 @@ var TaskScheduler = function(config) { if (capabilities.exclude) { var capabilitiesSpecExcludes = ConfigParser.resolveFilePatterns( capabilities.exclude, true, config.configDir); - capabilitiesSpecs = ConfigParser.resolveFilePatterns( - capabilitiesSpecs).filter(function(path) { - return capabilitiesSpecExcludes.indexOf(path) < 0; - }); + capabilitiesSpecs = capabilitiesSpecs.filter(function(path) { + return capabilitiesSpecExcludes.indexOf(path) < 0; + }); } var specLists = []; From 55956c518a6b111adfc48cb1f3ae274152a54bda Mon Sep 17 00:00:00 2001 From: Davy Duperron Date: Fri, 18 Dec 2015 11:30:33 +0100 Subject: [PATCH 046/678] chore(docs): Updated afterLaunch method documentation in referenceConf file. --- docs/referenceConf.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/referenceConf.js b/docs/referenceConf.js index 5e7e226d2..83b66925a 100644 --- a/docs/referenceConf.js +++ b/docs/referenceConf.js @@ -246,9 +246,10 @@ exports.config = { // A callback function called once all tests have finished running and // the WebDriver instance has been shut down. It is passed the exit code - // (0 if the tests passed). This is called only once before the program - // exits (after onCleanUp). - afterLaunch: function() {}, + // (0 if the tests passed). afterLaunch must return a promise if you want + // asynchronous code to be executed before the program exits. + // This is called only once before the program exits (after onCleanUp). + afterLaunch: function(exitCode) {}, // The params object will be passed directly to the Protractor instance, // and can be accessed from your test as browser.params. It is an arbitrary From 4a3d5e7af164fec9ae85b109505afb582d3f196c Mon Sep 17 00:00:00 2001 From: Alexander Afanasyev Date: Sat, 19 Dec 2015 21:53:29 -0500 Subject: [PATCH 047/678] chore(docs): Fixed typo - getMultiCapabilities promise is resolved after beforeLaunch --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7df632c2e..4351d90c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -725,7 +725,7 @@ _Why is this change version 2.0? Protractor is following semver, and there's som Enables adding `getMultiCapabilities: function(){}` to your configuration file. The function returns either multiCapabilities or a promise of a multiCapabilities that is resolved after - `afterLaunch` and before driver set up. If this is specified, both capabilities and + `beforeLaunch` and before driver set up. If this is specified, both capabilities and multiCapabilities will be ignored. Also allows specifying `seleniumAddress` in the capabilities/multiCapabilities object, which will From 3142e387fe120dfa8dec87f8ba38983870fa1a15 Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Mon, 28 Dec 2015 10:46:30 -0800 Subject: [PATCH 048/678] cleanup(lodash): remove lodash dependency --- lib/configParser.js | 31 +++++++++++++++++++++++++------ package.json | 1 - 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/lib/configParser.js b/lib/configParser.js index 5d0ed8e2e..da72364d6 100644 --- a/lib/configParser.js +++ b/lib/configParser.js @@ -1,7 +1,6 @@ var path = require('path'), glob = require('glob'), log = require('./logger'), - _ = require('lodash'), helper = require('./util'); // Coffee is required here to enable config files written in coffee-script. @@ -72,7 +71,27 @@ var merge_ = function(into, from) { * if it was not one already. */ var makeArray = function(item) { - return _.isArray(item) ? item : [item]; + return Array.isArray(item) ? item : [item]; +}; + +/** + * Adds to an array all the elements in another array without adding any + * duplicates + * + * @param {Array} dest The array to add to + * @param {Array} src The array to copy from + */ +var union = function(dest, src) { + var elems = {}; + for (var key in dest) { + elems[key] = true; + } + for (key in src) { + if (!elems[key]) { + dest.push(key); + elems[key] = true; + } + } }; /** @@ -117,12 +136,12 @@ ConfigParser.resolveFilePatterns = ConfigParser.getSpecs = function(config) { var specs = []; if (config.suite) { - _.forEach(config.suite.split(','), function(suite) { + config.suite.split(',').forEach(function(suite) { var suiteList = config.suites[suite]; if (suiteList == null) { throw new Error('Unknown test suite: ' + suite); } - specs = _.union(specs, makeArray(suiteList)); + union(specs, makeArray(suiteList)); }); return specs; } @@ -131,8 +150,8 @@ ConfigParser.getSpecs = function(config) { return config.specs; } - _.forEach(config.suites, function(suite) { - specs = _.union(specs, makeArray(suite)); + config.suites.forEach(function(suite) { + union(specs, makeArray(suite)); }); return specs; }; diff --git a/package.json b/package.json index 3e6205db1..a93576817 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,6 @@ "adm-zip": "0.4.4", "optimist": "~0.6.0", "q": "1.0.0", - "lodash": "~2.4.1", "source-map-support": "~0.3.2" }, "devDependencies": { From b1ea4760215c5dfe91fafd71280502486f889257 Mon Sep 17 00:00:00 2001 From: Julie Ralph Date: Tue, 12 Jan 2016 10:17:53 -0800 Subject: [PATCH 049/678] docs(timeouts): add section on how to use ignoreSynchronization Closes #2831 --- docs/timeouts.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/docs/timeouts.md b/docs/timeouts.md index 7ca987076..affa9e737 100644 --- a/docs/timeouts.md +++ b/docs/timeouts.md @@ -39,6 +39,21 @@ Protractor only works with Angular applications, so it waits for the `angular` v - How to change: To change globally, add `getPageTimeout: timeout_in_millis` to your Protractor configuration file. For an individual call to `get`, pass an additional parameter: `browser.get(address, timeout_in_millis)` +_*How to disable waiting for Angular*_ + +If you need to navigate to a page which does not use Angular, you can turn off waiting for Angular by setting +`browser.ignoreSynchronization = true`. For example: + +```js +browser.get('page-containing-angular'); +navigateToVanillaPage.click(); +browser.ignoreSynchronization = true; +otherButton.click(); +navigateToAngularPage.click(); +browser.ignoreSynchronization = false; +``` + + Timeouts from WebDriver ----------------------- From d033214e9ff26f0cccedfd70f85b0661867d0398 Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Wed, 13 Jan 2016 16:20:25 -0800 Subject: [PATCH 050/678] fix(config parser): lodash removal had mistakes which broke the suite feature --- lib/configParser.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/configParser.js b/lib/configParser.js index da72364d6..2a58a56bd 100644 --- a/lib/configParser.js +++ b/lib/configParser.js @@ -84,12 +84,12 @@ var makeArray = function(item) { var union = function(dest, src) { var elems = {}; for (var key in dest) { - elems[key] = true; + elems[dest[key]] = true; } for (key in src) { - if (!elems[key]) { - dest.push(key); - elems[key] = true; + if (!elems[src[key]]) { + dest.push(src[key]); + elems[src[key]] = true; } } }; @@ -150,7 +150,7 @@ ConfigParser.getSpecs = function(config) { return config.specs; } - config.suites.forEach(function(suite) { + Array.prototype.forEach.call(config.suites, function(suite) { union(specs, makeArray(suite)); }); return specs; From fa32f34db9b662839bcccf99766aef790ca0dfbb Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Wed, 13 Jan 2016 02:40:07 -0800 Subject: [PATCH 051/678] chore(docs): correct docs for config.baseUrl --- docs/referenceConf.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/referenceConf.js b/docs/referenceConf.js index 83b66925a..7f0e79c23 100644 --- a/docs/referenceConf.js +++ b/docs/referenceConf.js @@ -181,7 +181,7 @@ exports.config = { // --------------------------------------------------------------------------- // // A base URL for your application under test. Calls to protractor.get() - // with relative paths will be prepended with this. + // with relative paths will be resolved against this URL (via url.resolve) baseUrl: 'http://localhost:9876', // CSS Selector for the element housing the angular app - this defaults to From bd5c290ac908fb17284ad832eb3d44c56e3789aa Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Wed, 13 Jan 2016 02:32:54 -0800 Subject: [PATCH 052/678] chore(testapp): section off angular 1 testapp --- scripts/interactive_tests/interactive_test.js | 4 +- scripts/interactive_tests/with_base_url.js | 4 +- spec/altRootConf.js | 2 +- spec/basic/lib_spec.js | 2 +- spec/basic/navigation_spec.js | 12 ++-- spec/basicConf.js | 2 +- spec/ciBStackConf.js | 2 +- spec/ciFullConf.js | 2 +- spec/ciSmokeConf.js | 2 +- spec/controlLockConf.js | 2 +- spec/customFramework.js | 2 +- spec/directConnectConf.js | 2 +- .../afterLaunchChangesExitCodeConf.js | 2 +- spec/errorTest/mochaFailureConf.js | 2 +- spec/errorTest/multiFailureConf.js | 2 +- spec/errorTest/pluginsFailingConf.js | 2 +- spec/errorTest/shardedFailureConf.js | 2 +- spec/errorTest/singleFailureConf.js | 2 +- spec/errorTest/slowHttpAndTimeoutConf.js | 2 +- spec/errorTest/timeoutConf.js | 2 +- spec/getCapabilitiesConf.js | 2 +- spec/interactionConf.js | 2 +- spec/login/login_spec.js | 2 +- spec/mochaConf.js | 2 +- spec/multiConf.js | 2 +- spec/onCleanUpAsyncReturnValueConf.js | 2 +- spec/onCleanUpNoReturnValueConf.js | 2 +- spec/onCleanUpSyncReturnValueConf.js | 2 +- spec/onPrepareConf.js | 2 +- spec/onPrepareFileConf.js | 2 +- spec/onPreparePromiseConf.js | 2 +- spec/onPreparePromiseFileConf.js | 2 +- spec/plugins/browserGetSyncedConf.js | 2 +- spec/plugins/browserGetUnsyncedConf.js | 2 +- spec/plugins/multiPluginConf.js | 2 +- spec/plugins/postTestConfTemplate.js | 2 +- spec/plugins/smokeConf.js | 2 +- spec/plugins/waitForAngularConf.js | 2 +- .../setCookies_spec.js | 4 +- spec/restartBrowserBetweenTestsConf.js | 2 +- spec/shardingConf.js | 2 +- spec/suitesConf.js | 2 +- spec/withLoginConf.js | 4 +- testapp/app.css | 54 ++++++----------- testapp/index.html | 56 +++++------------- testapp/{ => ng1}/alt_root_index.html | 0 testapp/{ => ng1}/animation/animation.css | 0 testapp/{ => ng1}/animation/animation.html | 0 testapp/{ => ng1}/animation/animation.js | 0 testapp/ng1/app.css | 47 +++++++++++++++ testapp/{ => ng1}/app.js | 0 testapp/{ => ng1}/async/async.html | 0 testapp/{ => ng1}/async/async.js | 0 testapp/{ => ng1}/bindings/bindings.html | 0 testapp/{ => ng1}/bindings/bindings.js | 0 testapp/{ => ng1}/components/app-version.js | 0 testapp/{ => ng1}/conflict/conflict.html | 0 testapp/{ => ng1}/conflict/conflict.js | 0 testapp/{ => ng1}/favicon.ico | Bin testapp/{ => ng1}/form/form.html | 0 testapp/{ => ng1}/form/form.js | 0 testapp/ng1/index.html | 43 ++++++++++++++ .../{ => ng1}/interaction/interaction.html | 0 testapp/{ => ng1}/interaction/interaction.js | 0 .../lib/angular_v1.2.9/angular-animate.min.js | 0 .../angular_v1.2.9/angular-animate.min.js.map | 0 .../lib/angular_v1.2.9/angular-route.min.js | 0 .../angular_v1.2.9/angular-route.min.js.map | 0 .../lib/angular_v1.2.9/angular.min.js | 0 .../lib/angular_v1.2.9/angular.min.js.map | 0 .../angular_v1.3.13/angular-animate.min.js | 0 .../angular-animate.min.js.map | 0 .../lib/angular_v1.3.13/angular-aria.min.js | 0 .../lib/angular_v1.3.13/angular-route.min.js | 0 .../angular_v1.3.13/angular-route.min.js.map | 0 .../lib/angular_v1.3.13/angular.min.js | 0 .../lib/angular_v1.3.13/angular.min.js.map | 0 testapp/{ => ng1}/lib/angular_version.js | 0 testapp/{ => ng1}/login.html | 0 testapp/{ => ng1}/polling/polling.html | 0 testapp/{ => ng1}/polling/polling.js | 0 testapp/{ => ng1}/repeater/repeater.html | 0 testapp/{ => ng1}/repeater/repeater.js | 0 testapp/{ => ng1}/shadow/shadow.html | 0 testapp/{ => ng1}/shadow/shadow.js | 0 testapp/scripts/web-server.js | 16 ++--- website/gulpfile.js | 10 ++-- 87 files changed, 189 insertions(+), 141 deletions(-) rename testapp/{ => ng1}/alt_root_index.html (100%) rename testapp/{ => ng1}/animation/animation.css (100%) rename testapp/{ => ng1}/animation/animation.html (100%) rename testapp/{ => ng1}/animation/animation.js (100%) create mode 100644 testapp/ng1/app.css rename testapp/{ => ng1}/app.js (100%) rename testapp/{ => ng1}/async/async.html (100%) rename testapp/{ => ng1}/async/async.js (100%) rename testapp/{ => ng1}/bindings/bindings.html (100%) rename testapp/{ => ng1}/bindings/bindings.js (100%) rename testapp/{ => ng1}/components/app-version.js (100%) rename testapp/{ => ng1}/conflict/conflict.html (100%) rename testapp/{ => ng1}/conflict/conflict.js (100%) rename testapp/{ => ng1}/favicon.ico (100%) rename testapp/{ => ng1}/form/form.html (100%) rename testapp/{ => ng1}/form/form.js (100%) create mode 100644 testapp/ng1/index.html rename testapp/{ => ng1}/interaction/interaction.html (100%) rename testapp/{ => ng1}/interaction/interaction.js (100%) rename testapp/{ => ng1}/lib/angular_v1.2.9/angular-animate.min.js (100%) rename testapp/{ => ng1}/lib/angular_v1.2.9/angular-animate.min.js.map (100%) rename testapp/{ => ng1}/lib/angular_v1.2.9/angular-route.min.js (100%) rename testapp/{ => ng1}/lib/angular_v1.2.9/angular-route.min.js.map (100%) rename testapp/{ => ng1}/lib/angular_v1.2.9/angular.min.js (100%) rename testapp/{ => ng1}/lib/angular_v1.2.9/angular.min.js.map (100%) rename testapp/{ => ng1}/lib/angular_v1.3.13/angular-animate.min.js (100%) rename testapp/{ => ng1}/lib/angular_v1.3.13/angular-animate.min.js.map (100%) rename testapp/{ => ng1}/lib/angular_v1.3.13/angular-aria.min.js (100%) rename testapp/{ => ng1}/lib/angular_v1.3.13/angular-route.min.js (100%) rename testapp/{ => ng1}/lib/angular_v1.3.13/angular-route.min.js.map (100%) rename testapp/{ => ng1}/lib/angular_v1.3.13/angular.min.js (100%) rename testapp/{ => ng1}/lib/angular_v1.3.13/angular.min.js.map (100%) rename testapp/{ => ng1}/lib/angular_version.js (100%) rename testapp/{ => ng1}/login.html (100%) rename testapp/{ => ng1}/polling/polling.html (100%) rename testapp/{ => ng1}/polling/polling.js (100%) rename testapp/{ => ng1}/repeater/repeater.html (100%) rename testapp/{ => ng1}/repeater/repeater.js (100%) rename testapp/{ => ng1}/shadow/shadow.html (100%) rename testapp/{ => ng1}/shadow/shadow.js (100%) diff --git a/scripts/interactive_tests/interactive_test.js b/scripts/interactive_tests/interactive_test.js index b2db38d53..2aac1ef81 100644 --- a/scripts/interactive_tests/interactive_test.js +++ b/scripts/interactive_tests/interactive_test.js @@ -13,9 +13,9 @@ test.addCommandExpectation('y', 'function (param) {return param;}'); // Check promises complete. test.addCommandExpectation('browser.driver.getCurrentUrl()', 'data:,'); -test.addCommandExpectation('browser.get("http://localhost:' + env.webServerDefaultPort + '")'); +test.addCommandExpectation('browser.get("http://localhost:' + env.webServerDefaultPort + '/ng1")'); test.addCommandExpectation('browser.getCurrentUrl()', - 'http://localhost:' + env.webServerDefaultPort + '/#/form'); + 'http://localhost:' + env.webServerDefaultPort + '/ng1/#/form'); // Check promises are resolved before being returned. test.addCommandExpectation('var greetings = element(by.binding("greeting"))'); diff --git a/scripts/interactive_tests/with_base_url.js b/scripts/interactive_tests/with_base_url.js index c8e8d7ca8..3a7186b2c 100644 --- a/scripts/interactive_tests/with_base_url.js +++ b/scripts/interactive_tests/with_base_url.js @@ -3,10 +3,10 @@ var InteractiveTest = require('./interactive_test_util').InteractiveTest; var port = env.interactiveTestPort; var test = new InteractiveTest( 'node lib/cli.js --baseUrl http://localhost:' + env.webServerDefaultPort + - ' --elementExplorer true', port); + '/ng1 --elementExplorer true', port); // Check we automatically go to to baseUrl. test.addCommandExpectation( 'browser.driver.getCurrentUrl()', - 'http://localhost:' + env.webServerDefaultPort + '/#/form'); + 'http://localhost:' + env.webServerDefaultPort + '/ng1/#/form'); test.run(); diff --git a/spec/altRootConf.js b/spec/altRootConf.js index 0d480d009..080e4245d 100644 --- a/spec/altRootConf.js +++ b/spec/altRootConf.js @@ -13,7 +13,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', // Selector for the element housing the angular app. rootElement: 'div#nested-ng-app' diff --git a/spec/basic/lib_spec.js b/spec/basic/lib_spec.js index e8056b89c..8484fab19 100644 --- a/spec/basic/lib_spec.js +++ b/spec/basic/lib_spec.js @@ -110,7 +110,7 @@ describe('protractor library', function() { it('should allow self-wrapped webdriver instances', function() { var driver = protractor.wrapDriver(browser.driver); - var url = browser.baseUrl + '/index.html'; + var url = require('url').resolve(browser.baseUrl, 'index.html'); driver.get(url); }); diff --git a/spec/basic/navigation_spec.js b/spec/basic/navigation_spec.js index fe18341e7..f3689d7d3 100644 --- a/spec/basic/navigation_spec.js +++ b/spec/basic/navigation_spec.js @@ -32,29 +32,29 @@ describe('navigation', function() { it('should navigate back and forward properly', function() { browser.get('index.html#/repeater'); expect(browser.getCurrentUrl()). - toEqual(env.baseUrl+'/index.html#/repeater'); + toEqual(env.baseUrl+'/ng1/index.html#/repeater'); browser.navigate().back(); expect(browser.getCurrentUrl()). - toEqual(env.baseUrl+'/index.html#/form'); + toEqual(env.baseUrl+'/ng1/index.html#/form'); browser.navigate().forward(); expect(browser.getCurrentUrl()). - toEqual(env.baseUrl+'/index.html#/repeater'); + toEqual(env.baseUrl+'/ng1/index.html#/repeater'); }); */ it('should navigate back and forward properly from link', function() { element(by.linkText('repeater')).click(); expect(browser.getCurrentUrl()). - toEqual(env.baseUrl + '/index.html#/repeater'); + toEqual(env.baseUrl + '/ng1/index.html#/repeater'); browser.navigate().back(); expect(browser.getCurrentUrl()). - toEqual(env.baseUrl + '/index.html#/form'); + toEqual(env.baseUrl + '/ng1/index.html#/form'); browser.navigate().forward(); expect(browser.getCurrentUrl()). - toEqual(env.baseUrl + '/index.html#/repeater'); + toEqual(env.baseUrl + '/ng1/index.html#/repeater'); }); }); diff --git a/spec/basicConf.js b/spec/basicConf.js index 5e0bdd275..46b451a85 100644 --- a/spec/basicConf.js +++ b/spec/basicConf.js @@ -18,7 +18,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', params: { login: { diff --git a/spec/ciBStackConf.js b/spec/ciBStackConf.js index 407fbbe56..5ffc8c187 100644 --- a/spec/ciBStackConf.js +++ b/spec/ciBStackConf.js @@ -19,7 +19,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', jasmineNodeOpts: { isVerbose: true, diff --git a/spec/ciFullConf.js b/spec/ciFullConf.js index 0c909faa6..1249fd1e6 100644 --- a/spec/ciFullConf.js +++ b/spec/ciFullConf.js @@ -35,7 +35,7 @@ exports.config = { 'selenium-version': '2.48.2' }], - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', jasmineNodeOpts: { showTiming: true, diff --git a/spec/ciSmokeConf.js b/spec/ciSmokeConf.js index 4f76e21f4..bf791de2b 100644 --- a/spec/ciSmokeConf.js +++ b/spec/ciSmokeConf.js @@ -67,7 +67,7 @@ exports.config = { 'platform': 'Windows 7' }], - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', // Up the timeouts for the slower browsers (IE, Safari). allScriptsTimeout: 30000, diff --git a/spec/controlLockConf.js b/spec/controlLockConf.js index 9f8f7bf38..06d2a6066 100644 --- a/spec/controlLockConf.js +++ b/spec/controlLockConf.js @@ -14,7 +14,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', onPrepare: function() { diff --git a/spec/customFramework.js b/spec/customFramework.js index d1af1af3a..fc0badbde 100644 --- a/spec/customFramework.js +++ b/spec/customFramework.js @@ -12,5 +12,5 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl + baseUrl: env.baseUrl + '/ng1/' }; diff --git a/spec/directConnectConf.js b/spec/directConnectConf.js index 28e924e97..b9858fdad 100644 --- a/spec/directConnectConf.js +++ b/spec/directConnectConf.js @@ -12,7 +12,7 @@ exports.config = { 'browserName': 'firefox' }], - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', specs: ['directConnect/*_spec.js'], diff --git a/spec/errorTest/afterLaunchChangesExitCodeConf.js b/spec/errorTest/afterLaunchChangesExitCodeConf.js index 107d5e30d..049140fc7 100644 --- a/spec/errorTest/afterLaunchChangesExitCodeConf.js +++ b/spec/errorTest/afterLaunchChangesExitCodeConf.js @@ -13,7 +13,7 @@ exports.config = { 'browserName': 'chrome' }], - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', jasmineNodeOpts: { defaultTimeoutInterval: 90000 diff --git a/spec/errorTest/mochaFailureConf.js b/spec/errorTest/mochaFailureConf.js index 29bf7b94a..5e726330f 100644 --- a/spec/errorTest/mochaFailureConf.js +++ b/spec/errorTest/mochaFailureConf.js @@ -11,7 +11,7 @@ exports.config = { 'browserName': 'chrome' }], - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', mochaOpts: { reporter: 'spec', diff --git a/spec/errorTest/multiFailureConf.js b/spec/errorTest/multiFailureConf.js index 42ee68101..ba06b506b 100644 --- a/spec/errorTest/multiFailureConf.js +++ b/spec/errorTest/multiFailureConf.js @@ -14,7 +14,7 @@ exports.config = { 'browserName': 'chrome' }], - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', jasmineNodeOpts: { defaultTimeoutInterval: 90000 diff --git a/spec/errorTest/pluginsFailingConf.js b/spec/errorTest/pluginsFailingConf.js index c159e912e..ecb6c88e6 100644 --- a/spec/errorTest/pluginsFailingConf.js +++ b/spec/errorTest/pluginsFailingConf.js @@ -14,7 +14,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', // Plugin patterns are relative to this directory. plugins: [{ diff --git a/spec/errorTest/shardedFailureConf.js b/spec/errorTest/shardedFailureConf.js index 1e9b687bf..a36d509dc 100644 --- a/spec/errorTest/shardedFailureConf.js +++ b/spec/errorTest/shardedFailureConf.js @@ -16,7 +16,7 @@ exports.config = { shardTestFiles: true }], - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', jasmineNodeOpts: { defaultTimeoutInterval: 90000 diff --git a/spec/errorTest/singleFailureConf.js b/spec/errorTest/singleFailureConf.js index 4da76b8cd..5c8a930ab 100644 --- a/spec/errorTest/singleFailureConf.js +++ b/spec/errorTest/singleFailureConf.js @@ -13,7 +13,7 @@ exports.config = { 'browserName': 'chrome' }], - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', jasmineNodeOpts: { defaultTimeoutInterval: 90000 diff --git a/spec/errorTest/slowHttpAndTimeoutConf.js b/spec/errorTest/slowHttpAndTimeoutConf.js index 22d5974ea..054d10e92 100644 --- a/spec/errorTest/slowHttpAndTimeoutConf.js +++ b/spec/errorTest/slowHttpAndTimeoutConf.js @@ -13,7 +13,7 @@ exports.config = { 'browserName': 'chrome' }], - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', allScriptsTimeout: 1000 }; diff --git a/spec/errorTest/timeoutConf.js b/spec/errorTest/timeoutConf.js index 25d7ba2ca..213432cba 100644 --- a/spec/errorTest/timeoutConf.js +++ b/spec/errorTest/timeoutConf.js @@ -13,7 +13,7 @@ exports.config = { 'browserName': 'chrome' }], - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', jasmineNodeOpts: { defaultTimeoutInterval: 90000 diff --git a/spec/getCapabilitiesConf.js b/spec/getCapabilitiesConf.js index 59e89bd1f..50035871f 100644 --- a/spec/getCapabilitiesConf.js +++ b/spec/getCapabilitiesConf.js @@ -21,6 +21,6 @@ exports.config = { return deferred.promise; }, - baseUrl: env.baseUrl + baseUrl: env.baseUrl + '/ng1/' }; diff --git a/spec/interactionConf.js b/spec/interactionConf.js index e4fbc49b7..daa9f76bd 100644 --- a/spec/interactionConf.js +++ b/spec/interactionConf.js @@ -13,5 +13,5 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl + baseUrl: env.baseUrl + '/ng1/' }; diff --git a/spec/login/login_spec.js b/spec/login/login_spec.js index 13f1be5f9..f39fd428b 100644 --- a/spec/login/login_spec.js +++ b/spec/login/login_spec.js @@ -2,7 +2,7 @@ var env = require('../environment.js'); describe('pages with login', function() { it('should log in with a non-Angular page', function() { - browser.get(env.baseUrl + '/index.html'); + browser.get(env.baseUrl + '/ng1/index.html'); var angularElement = element(by.model('username')); expect(angularElement.getAttribute('value')).toEqual('Anon'); diff --git a/spec/mochaConf.js b/spec/mochaConf.js index 544ab0687..a51b7ade2 100644 --- a/spec/mochaConf.js +++ b/spec/mochaConf.js @@ -13,7 +13,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', mochaOpts: { reporter: 'spec', diff --git a/spec/multiConf.js b/spec/multiConf.js index a15775cec..a0290feec 100644 --- a/spec/multiConf.js +++ b/spec/multiConf.js @@ -17,7 +17,7 @@ exports.config = { 'browserName': 'firefox' }], - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', params: { login: { diff --git a/spec/onCleanUpAsyncReturnValueConf.js b/spec/onCleanUpAsyncReturnValueConf.js index d32dbe282..7c0a45f0f 100644 --- a/spec/onCleanUpAsyncReturnValueConf.js +++ b/spec/onCleanUpAsyncReturnValueConf.js @@ -13,7 +13,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', onCleanUp: function(exitCode) { var deferred = q.defer(); diff --git a/spec/onCleanUpNoReturnValueConf.js b/spec/onCleanUpNoReturnValueConf.js index f17585ca8..938458013 100644 --- a/spec/onCleanUpNoReturnValueConf.js +++ b/spec/onCleanUpNoReturnValueConf.js @@ -12,7 +12,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', onCleanUp: function(exitCode) { // no return diff --git a/spec/onCleanUpSyncReturnValueConf.js b/spec/onCleanUpSyncReturnValueConf.js index 600eb6ab3..460df1558 100644 --- a/spec/onCleanUpSyncReturnValueConf.js +++ b/spec/onCleanUpSyncReturnValueConf.js @@ -12,7 +12,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', onCleanUp: function(exitCode) { return exitCode; diff --git a/spec/onPrepareConf.js b/spec/onPrepareConf.js index 9dd9720c0..25f6d93b2 100644 --- a/spec/onPrepareConf.js +++ b/spec/onPrepareConf.js @@ -14,7 +14,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', onPrepare: function() { browser.params.password = '12345'; diff --git a/spec/onPrepareFileConf.js b/spec/onPrepareFileConf.js index 2f9c4ba24..bd67998c1 100644 --- a/spec/onPrepareFileConf.js +++ b/spec/onPrepareFileConf.js @@ -14,7 +14,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', onPrepare: 'onPrepare/startup.js' }; diff --git a/spec/onPreparePromiseConf.js b/spec/onPreparePromiseConf.js index 719ddbdec..8ec3cb9c3 100644 --- a/spec/onPreparePromiseConf.js +++ b/spec/onPreparePromiseConf.js @@ -15,7 +15,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', onPrepare: function() { return q.fcall(function() { diff --git a/spec/onPreparePromiseFileConf.js b/spec/onPreparePromiseFileConf.js index 57a708238..fddccdba7 100644 --- a/spec/onPreparePromiseFileConf.js +++ b/spec/onPreparePromiseFileConf.js @@ -14,7 +14,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', onPrepare: 'onPrepare/asyncstartup.js' }; diff --git a/spec/plugins/browserGetSyncedConf.js b/spec/plugins/browserGetSyncedConf.js index 6757c5725..87ef0e162 100644 --- a/spec/plugins/browserGetSyncedConf.js +++ b/spec/plugins/browserGetSyncedConf.js @@ -14,7 +14,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', // Plugin patterns are relative to this directory. plugins: [{ diff --git a/spec/plugins/browserGetUnsyncedConf.js b/spec/plugins/browserGetUnsyncedConf.js index b677eed58..7031d3950 100644 --- a/spec/plugins/browserGetUnsyncedConf.js +++ b/spec/plugins/browserGetUnsyncedConf.js @@ -14,7 +14,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', // Plugin patterns are relative to this directory. plugins: [{ diff --git a/spec/plugins/multiPluginConf.js b/spec/plugins/multiPluginConf.js index 1ed3f1ec4..44c799564 100644 --- a/spec/plugins/multiPluginConf.js +++ b/spec/plugins/multiPluginConf.js @@ -13,7 +13,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', // Plugin patterns are relative to this directory. plugins: [{ diff --git a/spec/plugins/postTestConfTemplate.js b/spec/plugins/postTestConfTemplate.js index 8a39db240..185cfcbb4 100644 --- a/spec/plugins/postTestConfTemplate.js +++ b/spec/plugins/postTestConfTemplate.js @@ -12,7 +12,7 @@ module.exports = function(framework) { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', plugins: [{ path: 'plugins/post_test_plugin.js' diff --git a/spec/plugins/smokeConf.js b/spec/plugins/smokeConf.js index f1145e24b..44cbc5ef0 100644 --- a/spec/plugins/smokeConf.js +++ b/spec/plugins/smokeConf.js @@ -14,7 +14,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', // Plugin patterns are relative to this directory. plugins: [{ diff --git a/spec/plugins/waitForAngularConf.js b/spec/plugins/waitForAngularConf.js index 934c045dc..53f1200c2 100644 --- a/spec/plugins/waitForAngularConf.js +++ b/spec/plugins/waitForAngularConf.js @@ -14,7 +14,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', // Plugin patterns are relative to this directory. plugins: [{ diff --git a/spec/restartBrowserBetweenTests/setCookies_spec.js b/spec/restartBrowserBetweenTests/setCookies_spec.js index 38714c1e5..9b7b4619b 100644 --- a/spec/restartBrowserBetweenTests/setCookies_spec.js +++ b/spec/restartBrowserBetweenTests/setCookies_spec.js @@ -2,7 +2,7 @@ var env = require('../environment.js'); describe('pages with login', function() { it('should set a cookie', function() { - browser.get(env.baseUrl + '/index.html'); + browser.get(env.baseUrl + '/ng1/index.html'); browser.manage().addCookie('testcookie', 'Jane-1234'); @@ -13,7 +13,7 @@ describe('pages with login', function() { }); it('should check the cookie is gone', function() { - browser.get(env.baseUrl + '/index.html'); + browser.get(env.baseUrl + '/ng1/index.html'); // Make sure the cookie is gone. browser.manage().getCookie('testcookie').then(function(cookie) { diff --git a/spec/restartBrowserBetweenTestsConf.js b/spec/restartBrowserBetweenTestsConf.js index f0ff5ec15..d74cf0bef 100644 --- a/spec/restartBrowserBetweenTestsConf.js +++ b/spec/restartBrowserBetweenTestsConf.js @@ -13,7 +13,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', restartBrowserBetweenTests: true }; diff --git a/spec/shardingConf.js b/spec/shardingConf.js index 31df8113e..3d53d1ea3 100644 --- a/spec/shardingConf.js +++ b/spec/shardingConf.js @@ -34,7 +34,7 @@ exports.config = { specs: 'basic/action*' }], - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', params: { login: { diff --git a/spec/suitesConf.js b/spec/suitesConf.js index eb6e0113a..2705378aa 100644 --- a/spec/suitesConf.js +++ b/spec/suitesConf.js @@ -14,5 +14,5 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl + baseUrl: env.baseUrl + '/ng1/' }; diff --git a/spec/withLoginConf.js b/spec/withLoginConf.js index aee125cd1..f51c3e5c7 100644 --- a/spec/withLoginConf.js +++ b/spec/withLoginConf.js @@ -13,10 +13,10 @@ exports.config = { capabilities: env.capabilities, - baseUrl: env.baseUrl, + baseUrl: env.baseUrl + '/ng1/', onPrepare: function() { - browser.driver.get(env.baseUrl + '/login.html'); + browser.driver.get(env.baseUrl + '/ng1/login.html'); browser.driver.findElement(by.id('username')).sendKeys('Jane'); browser.driver.findElement(by.id('password')).sendKeys('1234'); diff --git a/testapp/app.css b/testapp/app.css index 1f4a15414..b5a4f12ad 100644 --- a/testapp/app.css +++ b/testapp/app.css @@ -1,47 +1,29 @@ -/* app css stylesheet */ - -.menu { - list-style: none; - border-bottom: 0.1em solid black; - margin-bottom: 2em; - padding: 0 0 0.5em; -} - -.menu:before { - content: "["; -} - -.menu:after { - content: "]"; -} - -.menu > li { - display: inline; +body { + font-family: Helvetica, Arial, san-sarif; + font-size: 2em; } -.menu > li:before { - content: "|"; - padding-right: 0.3em; +h1 { + text-align: center; } -.menu > li:nth-child(1):before { - content: ""; +ol { + position: relative; padding: 0; } -.ng-scope { - background-color: rgba(0,0,0,.05); +li { + width: 40%; + padding: 5%; + display: block; } -.ng-binding { - border: 1px solid rgba(50, 200, 50, .8); +li.left { + text-align: right; } -#chat-box { - width: 300px; - height: 200px; - padding: 25px; - border: 2px solid; - margin: 25px; - overflow: scroll; -} +li.right { + position: absolute; + top: 0; + right: 0; +} diff --git a/testapp/index.html b/testapp/index.html index 39581223b..432c94281 100644 --- a/testapp/index.html +++ b/testapp/index.html @@ -1,43 +1,19 @@ - - - My AngularJS App - - - - - - -
    - -
    Angular seed app: v
    - - - - - - - - - - - - - - - - - - + + + My AngularJS App + + + +

    Choose Version

    +
      +
    1. + Angular 1 +
    2. +
    3. + Angular 2 +
    4. +
    + diff --git a/testapp/alt_root_index.html b/testapp/ng1/alt_root_index.html similarity index 100% rename from testapp/alt_root_index.html rename to testapp/ng1/alt_root_index.html diff --git a/testapp/animation/animation.css b/testapp/ng1/animation/animation.css similarity index 100% rename from testapp/animation/animation.css rename to testapp/ng1/animation/animation.css diff --git a/testapp/animation/animation.html b/testapp/ng1/animation/animation.html similarity index 100% rename from testapp/animation/animation.html rename to testapp/ng1/animation/animation.html diff --git a/testapp/animation/animation.js b/testapp/ng1/animation/animation.js similarity index 100% rename from testapp/animation/animation.js rename to testapp/ng1/animation/animation.js diff --git a/testapp/ng1/app.css b/testapp/ng1/app.css new file mode 100644 index 000000000..1f4a15414 --- /dev/null +++ b/testapp/ng1/app.css @@ -0,0 +1,47 @@ +/* app css stylesheet */ + +.menu { + list-style: none; + border-bottom: 0.1em solid black; + margin-bottom: 2em; + padding: 0 0 0.5em; +} + +.menu:before { + content: "["; +} + +.menu:after { + content: "]"; +} + +.menu > li { + display: inline; +} + +.menu > li:before { + content: "|"; + padding-right: 0.3em; +} + +.menu > li:nth-child(1):before { + content: ""; + padding: 0; +} + +.ng-scope { + background-color: rgba(0,0,0,.05); +} + +.ng-binding { + border: 1px solid rgba(50, 200, 50, .8); +} + +#chat-box { + width: 300px; + height: 200px; + padding: 25px; + border: 2px solid; + margin: 25px; + overflow: scroll; +} diff --git a/testapp/app.js b/testapp/ng1/app.js similarity index 100% rename from testapp/app.js rename to testapp/ng1/app.js diff --git a/testapp/async/async.html b/testapp/ng1/async/async.html similarity index 100% rename from testapp/async/async.html rename to testapp/ng1/async/async.html diff --git a/testapp/async/async.js b/testapp/ng1/async/async.js similarity index 100% rename from testapp/async/async.js rename to testapp/ng1/async/async.js diff --git a/testapp/bindings/bindings.html b/testapp/ng1/bindings/bindings.html similarity index 100% rename from testapp/bindings/bindings.html rename to testapp/ng1/bindings/bindings.html diff --git a/testapp/bindings/bindings.js b/testapp/ng1/bindings/bindings.js similarity index 100% rename from testapp/bindings/bindings.js rename to testapp/ng1/bindings/bindings.js diff --git a/testapp/components/app-version.js b/testapp/ng1/components/app-version.js similarity index 100% rename from testapp/components/app-version.js rename to testapp/ng1/components/app-version.js diff --git a/testapp/conflict/conflict.html b/testapp/ng1/conflict/conflict.html similarity index 100% rename from testapp/conflict/conflict.html rename to testapp/ng1/conflict/conflict.html diff --git a/testapp/conflict/conflict.js b/testapp/ng1/conflict/conflict.js similarity index 100% rename from testapp/conflict/conflict.js rename to testapp/ng1/conflict/conflict.js diff --git a/testapp/favicon.ico b/testapp/ng1/favicon.ico similarity index 100% rename from testapp/favicon.ico rename to testapp/ng1/favicon.ico diff --git a/testapp/form/form.html b/testapp/ng1/form/form.html similarity index 100% rename from testapp/form/form.html rename to testapp/ng1/form/form.html diff --git a/testapp/form/form.js b/testapp/ng1/form/form.js similarity index 100% rename from testapp/form/form.js rename to testapp/ng1/form/form.js diff --git a/testapp/ng1/index.html b/testapp/ng1/index.html new file mode 100644 index 000000000..39581223b --- /dev/null +++ b/testapp/ng1/index.html @@ -0,0 +1,43 @@ + + + + + My AngularJS App + + + + + + +
    + +
    Angular seed app: v
    + + + + + + + + + + + + + + + + + + + diff --git a/testapp/interaction/interaction.html b/testapp/ng1/interaction/interaction.html similarity index 100% rename from testapp/interaction/interaction.html rename to testapp/ng1/interaction/interaction.html diff --git a/testapp/interaction/interaction.js b/testapp/ng1/interaction/interaction.js similarity index 100% rename from testapp/interaction/interaction.js rename to testapp/ng1/interaction/interaction.js diff --git a/testapp/lib/angular_v1.2.9/angular-animate.min.js b/testapp/ng1/lib/angular_v1.2.9/angular-animate.min.js similarity index 100% rename from testapp/lib/angular_v1.2.9/angular-animate.min.js rename to testapp/ng1/lib/angular_v1.2.9/angular-animate.min.js diff --git a/testapp/lib/angular_v1.2.9/angular-animate.min.js.map b/testapp/ng1/lib/angular_v1.2.9/angular-animate.min.js.map similarity index 100% rename from testapp/lib/angular_v1.2.9/angular-animate.min.js.map rename to testapp/ng1/lib/angular_v1.2.9/angular-animate.min.js.map diff --git a/testapp/lib/angular_v1.2.9/angular-route.min.js b/testapp/ng1/lib/angular_v1.2.9/angular-route.min.js similarity index 100% rename from testapp/lib/angular_v1.2.9/angular-route.min.js rename to testapp/ng1/lib/angular_v1.2.9/angular-route.min.js diff --git a/testapp/lib/angular_v1.2.9/angular-route.min.js.map b/testapp/ng1/lib/angular_v1.2.9/angular-route.min.js.map similarity index 100% rename from testapp/lib/angular_v1.2.9/angular-route.min.js.map rename to testapp/ng1/lib/angular_v1.2.9/angular-route.min.js.map diff --git a/testapp/lib/angular_v1.2.9/angular.min.js b/testapp/ng1/lib/angular_v1.2.9/angular.min.js similarity index 100% rename from testapp/lib/angular_v1.2.9/angular.min.js rename to testapp/ng1/lib/angular_v1.2.9/angular.min.js diff --git a/testapp/lib/angular_v1.2.9/angular.min.js.map b/testapp/ng1/lib/angular_v1.2.9/angular.min.js.map similarity index 100% rename from testapp/lib/angular_v1.2.9/angular.min.js.map rename to testapp/ng1/lib/angular_v1.2.9/angular.min.js.map diff --git a/testapp/lib/angular_v1.3.13/angular-animate.min.js b/testapp/ng1/lib/angular_v1.3.13/angular-animate.min.js similarity index 100% rename from testapp/lib/angular_v1.3.13/angular-animate.min.js rename to testapp/ng1/lib/angular_v1.3.13/angular-animate.min.js diff --git a/testapp/lib/angular_v1.3.13/angular-animate.min.js.map b/testapp/ng1/lib/angular_v1.3.13/angular-animate.min.js.map similarity index 100% rename from testapp/lib/angular_v1.3.13/angular-animate.min.js.map rename to testapp/ng1/lib/angular_v1.3.13/angular-animate.min.js.map diff --git a/testapp/lib/angular_v1.3.13/angular-aria.min.js b/testapp/ng1/lib/angular_v1.3.13/angular-aria.min.js similarity index 100% rename from testapp/lib/angular_v1.3.13/angular-aria.min.js rename to testapp/ng1/lib/angular_v1.3.13/angular-aria.min.js diff --git a/testapp/lib/angular_v1.3.13/angular-route.min.js b/testapp/ng1/lib/angular_v1.3.13/angular-route.min.js similarity index 100% rename from testapp/lib/angular_v1.3.13/angular-route.min.js rename to testapp/ng1/lib/angular_v1.3.13/angular-route.min.js diff --git a/testapp/lib/angular_v1.3.13/angular-route.min.js.map b/testapp/ng1/lib/angular_v1.3.13/angular-route.min.js.map similarity index 100% rename from testapp/lib/angular_v1.3.13/angular-route.min.js.map rename to testapp/ng1/lib/angular_v1.3.13/angular-route.min.js.map diff --git a/testapp/lib/angular_v1.3.13/angular.min.js b/testapp/ng1/lib/angular_v1.3.13/angular.min.js similarity index 100% rename from testapp/lib/angular_v1.3.13/angular.min.js rename to testapp/ng1/lib/angular_v1.3.13/angular.min.js diff --git a/testapp/lib/angular_v1.3.13/angular.min.js.map b/testapp/ng1/lib/angular_v1.3.13/angular.min.js.map similarity index 100% rename from testapp/lib/angular_v1.3.13/angular.min.js.map rename to testapp/ng1/lib/angular_v1.3.13/angular.min.js.map diff --git a/testapp/lib/angular_version.js b/testapp/ng1/lib/angular_version.js similarity index 100% rename from testapp/lib/angular_version.js rename to testapp/ng1/lib/angular_version.js diff --git a/testapp/login.html b/testapp/ng1/login.html similarity index 100% rename from testapp/login.html rename to testapp/ng1/login.html diff --git a/testapp/polling/polling.html b/testapp/ng1/polling/polling.html similarity index 100% rename from testapp/polling/polling.html rename to testapp/ng1/polling/polling.html diff --git a/testapp/polling/polling.js b/testapp/ng1/polling/polling.js similarity index 100% rename from testapp/polling/polling.js rename to testapp/ng1/polling/polling.js diff --git a/testapp/repeater/repeater.html b/testapp/ng1/repeater/repeater.html similarity index 100% rename from testapp/repeater/repeater.html rename to testapp/ng1/repeater/repeater.html diff --git a/testapp/repeater/repeater.js b/testapp/ng1/repeater/repeater.js similarity index 100% rename from testapp/repeater/repeater.js rename to testapp/ng1/repeater/repeater.js diff --git a/testapp/shadow/shadow.html b/testapp/ng1/shadow/shadow.html similarity index 100% rename from testapp/shadow/shadow.html rename to testapp/ng1/shadow/shadow.html diff --git a/testapp/shadow/shadow.js b/testapp/ng1/shadow/shadow.js similarity index 100% rename from testapp/shadow/shadow.js rename to testapp/ng1/shadow/shadow.js diff --git a/testapp/scripts/web-server.js b/testapp/scripts/web-server.js index a05f912f0..a7f00949c 100755 --- a/testapp/scripts/web-server.js +++ b/testapp/scripts/web-server.js @@ -9,7 +9,7 @@ var env = require('../../spec/environment.js'); var testApp = express(); var DEFAULT_PORT = process.env.HTTP_PORT || env.webServerDefaultPort; var testAppDir = path.resolve(__dirname, '..'); -var defaultAngular = require(path.join(testAppDir, 'lib/angular_version.js')); +var defaultAngular = require(path.join(testAppDir, 'ng1/lib/angular_version.js')); var argv = optimist.describe('port', 'port'). default('port', DEFAULT_PORT). @@ -17,7 +17,7 @@ var argv = optimist.describe('port', 'port'). default('ngversion', defaultAngular). argv; -var angularDir = path.join(testAppDir, 'lib/angular_v' + argv.ngversion); +var angularDir = path.join(testAppDir, 'ng1/lib/angular_v' + argv.ngversion); var main = function() { var port = argv.port; @@ -28,19 +28,19 @@ var main = function() { var storage = {}; var testMiddleware = function(req, res, next) { - if (req.path == '/fastcall') { + if (/ng[1-2]\/fastcall/.test(req.path)) { res.send(200, 'done'); - } else if (req.path == '/slowcall') { + } else if (/ng[1-2]\/slowcall/.test(req.path)) { setTimeout(function() { res.send(200, 'finally done'); }, 5000); - } else if (req.path == '/fastTemplateUrl') { + } else if (/ng[1-2]\/fastTemplateUrl/.test(req.path)) { res.send(200, 'fast template contents'); - } else if (req.path == '/slowTemplateUrl') { + } else if (/ng[1-2]\/slowTemplateUrl/.test(req.path)) { setTimeout(function() { res.send(200, 'slow template contents'); }, 5000); - } else if (req.path == '/chat') { + } else if (/ng[1-2]\/chat/.test(req.path)) { if (req.method === 'GET') { var value; if (req.query.q) { @@ -71,7 +71,7 @@ var testMiddleware = function(req, res, next) { }; testApp.configure(function() { - testApp.use('/lib/angular', express.static(angularDir)); + testApp.use('/ng1/lib/angular', express.static(angularDir)); testApp.use(express.static(testAppDir)); testApp.use(express.json()); testApp.use(testMiddleware); diff --git a/website/gulpfile.js b/website/gulpfile.js index 18b793250..2463c038f 100644 --- a/website/gulpfile.js +++ b/website/gulpfile.js @@ -136,15 +136,15 @@ gulp.task('testapp', function() { var stream = gulp.src('../testapp/**/*'). pipe(gulp.dest('build/testapp')); gulp.src('testapp/*'). - pipe(gulp.dest('build/testapp')); - var angular_version = require('../testapp/lib/angular_version.js'); - gulp.src('../testapp/lib/angular_v' + angular_version + '/**/*'). - pipe(gulp.dest('build/testapp/lib/angular')); + pipe(gulp.dest('build/testapp/ng1')); + var angular_version = require('../testapp/ng1/lib/angular_version.js'); + gulp.src('../testapp/ng1/lib/angular_v' + angular_version + '/**/*'). + pipe(gulp.dest('build/testapp/ng1/lib/angular')); return stream; }); gulp.task('cleanup_testapp', ['testapp'], function() { - del('build/testapp/lib/angular_v*'); + del('build/testapp/ng1/lib/angular_v*'); }); // Start a server and watch for changes. From fb10c5caffb895e909ad91d629e2192c74c8e064 Mon Sep 17 00:00:00 2001 From: Alexander Albul Date: Mon, 14 Dec 2015 13:49:31 +0100 Subject: [PATCH 053/678] feat(webdriver): Allow users to use webdriver's disableEnvironmentOverrides Fixes #2300 --- docs/referenceConf.js | 7 ++++++- lib/driverProviders/driverProvider.js | 11 +++++++---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/referenceConf.js b/docs/referenceConf.js index 7f0e79c23..f629051f5 100644 --- a/docs/referenceConf.js +++ b/docs/referenceConf.js @@ -340,5 +340,10 @@ exports.config = { // Turns off source map support. Stops protractor from registering global // variable `source-map-support`. Defaults to `false` - skipSourceMapSupport: false + skipSourceMapSupport: false, + + // Turns off WebDriver's environment variables overrides to ignore any + // environment variable and to only use the configuration in this file. + // Defaults to `true` + environmentOverrides: true }; diff --git a/lib/driverProviders/driverProvider.js b/lib/driverProviders/driverProvider.js index d873b20ef..6d6a1176d 100644 --- a/lib/driverProviders/driverProvider.js +++ b/lib/driverProviders/driverProvider.js @@ -32,10 +32,13 @@ DriverProvider.prototype.getExistingDrivers = function() { * @return webdriver instance */ DriverProvider.prototype.getNewDriver = function() { - var newDriver = new webdriver.Builder(). - usingServer(this.config_.seleniumAddress). - withCapabilities(this.config_.capabilities). - build(); + var builder = new webdriver.Builder(). + usingServer(this.config_.seleniumAddress). + withCapabilities(this.config_.capabilities); + if (this.config_.environmentOverrides === false) { + builder.disableEnvironmentOverrides(); + } + var newDriver = builder.build(); this.drivers_.push(newDriver); return newDriver; }; From dd4ef900867ab72a5e58b2f34fdeb3fda94788cc Mon Sep 17 00:00:00 2001 From: Andres Dominguez Date: Mon, 18 Jan 2016 15:24:02 -0500 Subject: [PATCH 054/678] docs(style-guide): Add initial version of style guide --- docs/style-guide.md | 571 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 571 insertions(+) create mode 100644 docs/style-guide.md diff --git a/docs/style-guide.md b/docs/style-guide.md new file mode 100644 index 000000000..3da8a14ac --- /dev/null +++ b/docs/style-guide.md @@ -0,0 +1,571 @@ +Protractor style guide +====================== + +This style guide was originally created by +[Carmen Popoviciu](https://github.com/CarmenPopoviciu) and +[Andres Dominguez](https://github.com/andresdominguez). It is based on Carmen's +Protractor +[style guide](https://github.com/CarmenPopoviciu/protractor-styleguide) and +Google's Protractor style guide. + +## Video + +Carmen and Andres gave a talk about this style guide at +[AngularConnect](http://angularconnect.com/) in London. Here's the video in +case you want to watch it. + +Protractor styleguide @AngularConnect + +## Table of contents + +* [Test suites](#test-suites) +* [Locator strategies](#locator-strategies) +* [Page objects](#page-objects) +* [Project structure](#project-structure) + +# Test suites + +### Don't e2e test what’s been unit tested + +**Why?** +* Unit tests are much faster than e2e tests +* Avoid duplicate tests + +### Make your tests independent at least at the file level + +* Protractor can run your tests in parallel when you enable sharding. The files + are executed across different browsers as they become available. +* Make your tests independent at the file level because the order in which + they run is not guaranteed and it's easier to run a test in isolation. + +### Do not add logic to your test + +* Avoid using if statements and for loops. When you add logic your test may + pass without testing anything, or may run very slowly. + +### Don't mock unless you need to + +This rule is a bit controversial, in the sense that opinions are very divided +when it comes to what the best practice is. Some developers argue that e2e +tests should use mocks for everything in order to avoid external network calls +and have a second set of integration tests to test the APIs and database. Other +developers argue that e2e tests should operate on the entire system and be as +close to the 'real deal' as possible. + +**Why?** +* Using the real application with all the dependencies gives you high confidence +* Helps you spot some corner cases you might have overlooked + +### Use Jasmine2 + +**Why?** +* Jasmine is well documented +* It is supported by Protractor out of the box +* You can use `beforeAll` and `afterAll` + +### Make your tests independent from each other + +This rule holds true unless the operations performed to initialize the state of +the tests are too expensive. For example, if your e2e tests would require that +you create a new user before each spec is executed, you might end up with too +high test run times. However, this does not mean you should make tests directly +depend on one another. So, instead of creating a user in one of your tests and +expect that record to be there for all other subsequent tests, you could harvest +the power of jasmine's beforeAll (since Jasmine 2.1) to create the user. + +```javascript +/* avoid */ + +it('should create user', function() { + browser.get('#/user-list'); + userList.newButton.click(); + + userProperties.name.sendKeys('Teddy B'); + userProperties.saveButton.click(); + + browser.get('#/user-list'); + userList.search('Teddy B'); + expect(userList.getNames()).toEqual(['Teddy B']); +}); + +it('should update user', function() { + browser.get('#/user-list'); + userList.clickOn('Teddy B'); + + userProperties.name.clear().sendKeys('Teddy C'); + userProperties.saveButton.click(); + + browser.get('#/user-list'); + userList.search('Teddy C'); + expect(userList.getNames()).toEqual(['Teddy C']); +}); +``` + +```javascript +/* recommended */ + +describe('when the user Teddy B is created', function(){ + + beforeAll(function() { + browser.get('#/user-list'); + userList.newButton.click(); + + userProperties.name.sendKeys('Teddy B'); + userProperties.saveButton.click(); + browser.get('#/user-list'); + }); + + it('should exist', function() { + userList.search('Teddy B'); + expect(userList.getNames()).toEqual(['Teddy B']); + userList.clear(); + }); + + describe('and gets updated to Teddy C', function() { + beforeAll(function() { + userList.clickOn('Teddy B'); + userProperties.name.clear().sendKeys('Teddy C'); + userProperties.saveButton.click(); + + browser.get('#/user-list'); + }); + + it('should be Teddy C', function() { + userList.search('Teddy C'); + expect(userList.getNames()).toEqual(['Teddy C']); + userList.clear(); + }); + }); +}); +``` + +**Why?** +* You can run tests in parallel with sharding +* The execution order is not guaranteed +* You can run suites in isolation +* You can debug your tests (ddescribe/fdescribe/xdescribe/iit/fit/xit) + +### Navigate to the page under test before each test + +**Why?** +* Assures you that the page under test is in a clean state + +### Have a suite that navigates through the major routes of the app + +**Why?** +* Makes sure the major parts of the application are correctly connected +* Users usually don’t navigate by manually entering urls +* Gives confidence about permissions + +# Locator strategies + +### NEVER use xpath + +**Why?** +* It's the slowest and most brittle locator strategy of all +* Markup is very easily subject to change and therefore xpath locators require + a lot of maintenance +* xpath expressions are unreadable and very hard to debug + +```javascript +/* avoid */ + +var elem = element(by.xpath('/*/p[2]/b[2]/following-sibling::node()' + + '[count(.|/*/p[2]/b[2]/following-sibling::br[1]/preceding-sibling::node())' + + '=' + + ' count((/*/p[2]/b[2]/following-sibling::br[1]/preceding-sibling::node()))' + + ']')); +``` + +### Prefer protractor locator strategies when possible + +* Prefer protractor-specific locators such as `by.model` and `by.binding`. + +```html +
      +
    • {{color.name}}
    • +
    • {{color.shade}}
    • +
    • {{color.code}}
    • +
    + +
    +
    + +
    +
    +``` + +```js +/* avoid */ + +var nameElement = element.all(by.css('.red li')).get(0); +var personName = element(by.css('.details .personal input')); + +/* recommended */ + +var nameElement = element(by.binding('color.name')); +var personName = element(by.model('person.name')); +``` + +**Why?** +* These locators are usually specific, short, and easy to read. +* It is easier to write your locator +* The code is less likely to change than other markup + +### Prefer by.id and by.css when no Protractor locators are available + +**Why?** +* Both are very performant and readable locators +* Access elements easier + +### Avoid text locators for text that changes frequently + +* Try to avoid text-based locators such as `by.linkText`, `by.buttonText`, + `by.cssContainingText`. + +**Why?** +* Text for buttons, links, and labels tends to change over time +* Your tests should not break when you make minor text changes + +# Page objects + +Page Objects help you write cleaner tests by encapsulating information about +the elements on your application page. A page object can be reused across +multiple tests, and if the template of your application changes, you only need +to update the page object. + +### Use Page Objects to interact with page under test + +**Why?** +* Encapsulate information about the elements on the page under test +* They can be reused across multiple tests +* Decouple the test logic from implementation details + +```javascript +/* avoid */ + +/* question-spec.js */ +describe('Question page', function() { + it('should answer any question', function() { + var question = element(by.model('question.text')); + var answer = element(by.binding('answer')); + var button = element(by.css('.question-button')); + + question.sendKeys('What is the purpose of life?'); + button.click(); + expect(answer.getText()).toEqual("Chocolate!"); + }); +}); +``` + +```javascript +/* recommended */ + +/* question-spec.js */ +var QuestionPage = require('./question-page'); + +describe('Question page', function() { + var question = new QuestionPage(); + + it('should ask any question', function() { + question.ask('What is the purpose of meaning?'); + expect(question.answer.getText()).toEqual('Chocolate'); + }); +}); + +/* recommended */ + +/* question-page.js */ +var QuestionPage = function() { + this.question = element(by.model('question.text')); + this.answer = element(by.binding('answer')); + this.button = element(by.className('question-button')); + + this.ask = function(question) { + this.question.sendKeys(question); + this.button.click(); + }; +}; + +module.exports = QuestionPage; +``` + +### Declare one page object per file + +**Why?** +* Each page object should be defined in its own file. +* Why? Keeps code clean and makes things easy to find. + +### Use a single module.exports at the end of the page object file + +**Why?** +* Each page object should declare a single class. You only need to export one + class. + +```js +/* avoid */ + +var UserProfilePage = function() {}; +var UserSettingsPage = function() {}; + +module.exports = UserPropertiesPage; +module.exports = UserSettingsPage; +``` + +```javascript +/* recommended */ + +/** @constructor */ +var UserPropertiesPage = function() {}; + +module.exports = UserPropertiesPage; +``` + +* Why? One page object per file means there's only one class to export. + +### Require all the modules at the top + +* You should declare all the required modules at the top of your page object, + test, or helper module. + +```js +var UserPage = require('./user-properties-page'); +var MenuPage = require('./menu-page'); +var FooterPage = require('./footer-page'); + +describe('User properties page', function() { + ... +}); +``` + +**Why?** +* The module dependencies should be clear and easy to find. + +### Instantiate all page objects at the beginning of the test suite + +* Create new instances of the page object at the top of your top-level describe. +* Use upper case for the constructor name; lowercase for the instance name. + +```js +var UserPropertiesPage = require('./user-properties-page'); +var MenuPage = require('./menu-page'); +var FooterPage = require('./footer-page'); + +describe('User properties page', function() { + var userProperties = new UserPropertiesPage(); + var menu = new MenuPage(); + var footer = new FooterPage(); + + // specs +}); +``` + +**Why?** +* Separates dependencies from the test code. +* Makes the dependencies available to all specs of the suite. + + +### Declare all the page object public elements in the constructor + +* All the elements that will be visible to the test should be declared in the + constructor. + +```html +
    + Name: + E-mail: + +
    +``` + +```javascript +/** @constructor */ +var UserPropertiesPage = function() { + // List all public elements here. + this.name = element(by.model('ctrl.user.name')); + this.email = element(by.model('ctrl.user.email')); + this.saveButton = $('#save-button'); +}; +``` + +**Why?** +* The user of the page object should have quick access to the available + elements on a page + + +### Declare page object functions for operations that require more than one step + +```javascript +/** + * Page object for the user properties view. + * @constructor + */ +var UserPropertiesPage = function() { + this.newPhoneButton = $('button.new-phone'); + + /** + * Encapsulate complex operations in a function. + * @param {string} phone Phone number. + * @param {string} contactType Phone type (work, home, etc.). + */ + this.addContactPhone = function(phone, contactType) { + this.newPhoneButton.click(); + $$('#phone-list .phone-row').first().then(function(row) { + row.element(by.model('item.phoneNumber')).sendKeys(phone); + row.element(by.model('item.contactType')).sendKeys(contactType); + }); + }; +}; +``` + +**Why?** +* Most elements are already exposed by the page object and can be used + directly in the test. +* Doing otherwise will not have any added value + +### Avoid using expect() in page objects + +* Don't make any assertions in your page objects. + +**Why?** +* It is the responsibility of the test to do all the assertions. +* A reader of the test should be able to understand the behavior of the + application by looking at the test only + +### Add page object wrappers for directives, dialogs, and common elements + +* Some directives render complex HTML or they change frequently. Avoid code + duplication by writing wrappers to interact with complex directives. +* Dialogs or modals are frequently used across multiple views. +* When the directive changes you only need to change the wrapper once. + +For example, the Protractor website has navigation bar with multiple dropdown +menus. Each menu has multiple options. A page object for the menu would look +like this: + +```js +/** + * Page object for Protractor website menu. + * @constructor + */ +var MenuPage = function() { + this.dropdown = function(dropdownName) { + /** + * Dropdown api. Used to click on an element under a dropdown. + * @param {string} dropdownName + * @return {{option: Function}} + */ + var openDropdown = function() { + element(by.css('.navbar-nav')) + .element(by.linkText(dropdownName)) + .click(); + }; + + return { + /** + * Get an option element under a dropdown. + * @param {string} optionName + * @return {ElementFinder} + */ + option: function(optionName) { + openDropdown(); + return element(by.css('.dropdown.open')) + .element(by.linkText(optionName)); + } + } + }; +}; + +module.exports = MenuPage; +``` + +```js +var Menu = require('./menu'); + +describe('protractor website', function() { + + var menu = new Menu(); + + it('should navigate to API view', function() { + browser.get('http://www.protractortest.org/#/'); + + menu.dropdown('Reference').option('Protractor API').click(); + + expect(browser.getCurrentUrl()) + .toBe('http://www.protractortest.org/#/api'); + }); +}); +``` + +**Why?** +* When you have a large team and multiple e2e tests people tend to write + their own custom locators for the same directives. + +# Project structure + +### Group your e2e tests in a structure that makes sense to the structure of your project + +**Why?** +* Finding your e2e related files should be intuitive and easy +* Makes the folder structure more readable +* Clearly separates e2e tests from unit tests + +``` +/* avoid */ + +|-- project-folder + |-- app + |-- css + |-- img + |-- partials + home.html + profile.html + contacts.html + |-- js + |-- controllers + |-- directives + |-- services + app.js + ... + index.html + |-- test + |-- unit + |-- e2e + home-page.js + home-spec.js + profile-page.js + profile-spec.js + contacts-page.js + contacts-spec.js + +/* recommended */ + +|-- project-folder + |-- app + |-- css + |-- img + |-- partials + home.html + profile.html + contacts.html + |-- js + |-- controllers + |-- directives + |-- services + app.js + ... + index.html + |-- test + |-- unit + |-- e2e + |-- page-objects + home-page.js + profile-page.js + contacts-page.js + home-spec.js + profile-spec.js + contacts-spec.js +``` From 05fd60d48d128b04f86856b10c9f37bd1842f10f Mon Sep 17 00:00:00 2001 From: Christopher M Hogan Date: Thu, 21 Jan 2016 09:52:09 -0600 Subject: [PATCH 055/678] docs(filter): fix ElementArrayFinder#filter example docs --- lib/element.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/lib/element.js b/lib/element.js index 80b2e9630..7f07845f8 100644 --- a/lib/element.js +++ b/lib/element.js @@ -181,9 +181,7 @@ ElementArrayFinder.prototype.all = function(locator) { * return elem.getText().then(function(text) { * return text === 'Third'; * }); - * }).then(function(filteredElements) { - * filteredElements[0].click(); - * }); + * }).first().click(); * * @param {function(ElementFinder, number): webdriver.WebElement.Promise} filterFn * Filter function that will test if an element should be returned. From 3c94d723f400c5dfabeb71d40ac57624474ceb28 Mon Sep 17 00:00:00 2001 From: Bijan Date: Wed, 6 Jan 2016 11:58:58 -0500 Subject: [PATCH 056/678] docs(launcher): fix launcher.js typo from capabilites to capabilities Noticed this while Googling an error message and seeing that Google recommended the correct spelling. --- lib/launcher.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/launcher.js b/lib/launcher.js index dfb4b723e..60297f874 100644 --- a/lib/launcher.js +++ b/lib/launcher.js @@ -119,7 +119,7 @@ var init = function(configFile, additionalConfig) { if (config.getMultiCapabilities && typeof config.getMultiCapabilities === 'function') { if (config.multiCapabilities.length || config.capabilities) { - log.warn('getMultiCapabilities() will override both capabilites ' + + log.warn('getMultiCapabilities() will override both capabilities ' + 'and multiCapabilities'); } // If getMultiCapabilities is defined and a function, use this. @@ -131,11 +131,11 @@ var init = function(configFile, additionalConfig) { resolve(); } }).then(function() { - // 2) Set `multicapabilities` using `capabilities`, `multicapabilites`, + // 2) Set `multicapabilities` using `capabilities`, `multicapabilities`, // or default if (config.capabilities) { if (config.multiCapabilities.length) { - log.warn('You have specified both capabilites and ' + + log.warn('You have specified both capabilities and ' + 'multiCapabilities. This will result in capabilities being ' + 'ignored'); } else { From 5930d1444aef2f053c132eb437d07f9b000d7803 Mon Sep 17 00:00:00 2001 From: evilaliv3 Date: Fri, 8 Jan 2016 16:01:58 +0100 Subject: [PATCH 057/678] chore(deps): update various npm dependencies to latest stable releases --- package.json | 27 ++++++++++++++------------- testapp/scripts/web-server.js | 32 +++++++++++++++----------------- 2 files changed, 29 insertions(+), 30 deletions(-) diff --git a/package.json b/package.json index a93576817..1d8c0cee7 100644 --- a/package.json +++ b/package.json @@ -12,25 +12,26 @@ ], "author": "Julie Ralph ", "dependencies": { - "request": "~2.57.0", + "request": "~2.67.0", "selenium-webdriver": "2.48.2", "jasminewd2": "0.0.6", - "jasmine": "2.3.2", + "jasmine": "2.4.1", "saucelabs": "~1.0.1", - "glob": "~3.2", - "adm-zip": "0.4.4", + "glob": "~6.0", + "adm-zip": "0.4.7", "optimist": "~0.6.0", - "q": "1.0.0", - "source-map-support": "~0.3.2" + "q": "1.4.1", + "source-map-support": "~0.4.0" }, "devDependencies": { - "expect.js": "~0.2.0", - "chai": "~3.3.0", - "chai-as-promised": "~5.1.0", - "jshint": "2.5.0", - "mocha": "2.3.3", - "express": "~3.3.4", - "rimraf": "~2.2.6" + "expect.js": "~0.3.1", + "chai": "~3.4.1", + "chai-as-promised": "~5.2.0", + "jshint": "2.9.1", + "mocha": "2.3.4", + "express": "~4.13.3", + "body-parser": "1.14.2", + "rimraf": "~2.5.0" }, "repository": { "type": "git", diff --git a/testapp/scripts/web-server.js b/testapp/scripts/web-server.js index a7f00949c..8eb61644e 100755 --- a/testapp/scripts/web-server.js +++ b/testapp/scripts/web-server.js @@ -1,6 +1,7 @@ #!/usr/bin/env node var express = require('express'); +var bodyParser = require('body-parser') var optimist = require('optimist'); var util = require('util'); var path = require('path'); @@ -21,6 +22,10 @@ var angularDir = path.join(testAppDir, 'ng1/lib/angular_v' + argv.ngversion); var main = function() { var port = argv.port; + testApp.use('/ng1/lib/angular', express.static(angularDir)); + testApp.use(express.static(testAppDir)); + testApp.use(bodyParser.json()); + testApp.use(testMiddleware); testApp.listen(port); util.puts(["Starting express web server in", testAppDir ,"on port", port]. join(" ")); @@ -29,25 +34,25 @@ var main = function() { var storage = {}; var testMiddleware = function(req, res, next) { if (/ng[1-2]\/fastcall/.test(req.path)) { - res.send(200, 'done'); + res.status(200).send('done'); } else if (/ng[1-2]\/slowcall/.test(req.path)) { setTimeout(function() { - res.send(200, 'finally done'); + res.status(200).send('finally done'); }, 5000); } else if (/ng[1-2]\/fastTemplateUrl/.test(req.path)) { - res.send(200, 'fast template contents'); + res.status(200).send('fast template contents'); } else if (/ng[1-2]\/slowTemplateUrl/.test(req.path)) { setTimeout(function() { - res.send(200, 'slow template contents'); + res.status(200).send('slow template contents'); }, 5000); } else if (/ng[1-2]\/chat/.test(req.path)) { if (req.method === 'GET') { var value; if (req.query.q) { value = storage[req.query.q]; - res.send(200, value); + res.status(200).send(value); } else { - res.send(400, 'must specify query'); + res.status(400).send('must specify query'); } } else if (req.method === 'POST') { if (req.body.key == 'newChatMessage') { @@ -55,26 +60,19 @@ var testMiddleware = function(req, res, next) { storage['chatMessages'] = []; } storage['chatMessages'].push(req.body.value); - res.send(200); + res.sendStatus(200); } else if (req.body.key == 'clearChatMessages') { storage['chatMessages'] = []; - res.send(200); + res.sendStatus(200); } else { - res.send(400, 'Unknown command'); + res.status(400).send('Unknown command'); } } else { - res.send(400, 'only accepts GET/POST'); + res.status(400).send('only accepts GET/POST'); } } else { return next(); } }; -testApp.configure(function() { - testApp.use('/ng1/lib/angular', express.static(angularDir)); - testApp.use(express.static(testAppDir)); - testApp.use(express.json()); - testApp.use(testMiddleware); -}); - main(); From 80a64ffab81ba16f15052421f948361c217ffcae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Go=C5=82=C4=99biowski?= Date: Thu, 19 Nov 2015 12:06:50 +0100 Subject: [PATCH 058/678] chore(ci): Install g++ 4.8 on Travis to prevent compilation errors Node.js 4 and newer require g++ newer than the one included in Travis by default. Using the default g++ causes `npm install` to fail on compiled dependencies - currently every such dependency of Protractor is optional so the whole build doesn't fail but it still causes errors & excessive logging. If the number of compiled dependencies grows, install logs might become so big that Travis stops - Karma has been hit by this problem recently. Refs karma-runner/karma#1672 --- .travis.yml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.travis.yml b/.travis.yml index abd7a1aa0..1cf2ba46f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,6 +12,7 @@ env: - BROWSER_STACK_ACCESS_KEY=BWCd4SynLzdDcv8xtzsB - LOGS_DIR=/tmp/protractor-build/logs - BROWSER_PROVIDER_READY_FILE=/tmp/sauce-connect-ready + - CXX=g++-4.8 matrix: - JOB=full - JOB=smoke @@ -27,6 +28,15 @@ matrix: - env: JOB=bstack node_js: "5" +addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - g++-4.8 + +before_install: + - g++-4.8 --version before_script: - npm run pretest From ff3dff7a2b45402c6a62cf666fe5d3caa661c0ad Mon Sep 17 00:00:00 2001 From: Julie Ralph Date: Fri, 22 Jan 2016 15:14:38 -0800 Subject: [PATCH 059/678] fix(config): fix environmentOverrides to disableEnvironmentOverrides Closes #2783 --- docs/referenceConf.js | 4 ++-- lib/driverProviders/driverProvider.js | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/referenceConf.js b/docs/referenceConf.js index f629051f5..27e141db7 100644 --- a/docs/referenceConf.js +++ b/docs/referenceConf.js @@ -344,6 +344,6 @@ exports.config = { // Turns off WebDriver's environment variables overrides to ignore any // environment variable and to only use the configuration in this file. - // Defaults to `true` - environmentOverrides: true + // Defaults to `false` + disableEnvironmentOverrides: false }; diff --git a/lib/driverProviders/driverProvider.js b/lib/driverProviders/driverProvider.js index 6d6a1176d..55f4785b4 100644 --- a/lib/driverProviders/driverProvider.js +++ b/lib/driverProviders/driverProvider.js @@ -35,7 +35,7 @@ DriverProvider.prototype.getNewDriver = function() { var builder = new webdriver.Builder(). usingServer(this.config_.seleniumAddress). withCapabilities(this.config_.capabilities); - if (this.config_.environmentOverrides === false) { + if (this.config_.disableEnvironmentOverrides === true) { builder.disableEnvironmentOverrides(); } var newDriver = builder.build(); From 1dd6e33c518c8125ba65ccbb35d82cbedb735cbf Mon Sep 17 00:00:00 2001 From: Craig Nishina Date: Fri, 22 Jan 2016 14:07:16 -0800 Subject: [PATCH 060/678] chore(test): angular2 testapp --- scripts/test.js | 1 + scripts/test_on_travis.sh | 3 + spec/angular2Conf.js | 4 +- spec/ciNg2Conf.js | 18 + spec/ng2/async_spec.js | 27 +- testapp/ng2/app/app-router.html | 8 + testapp/ng2/app/app.router.js | 49 + testapp/ng2/app/app.router.js.map | 1 + testapp/ng2/app/app.router.ts | 17 + testapp/ng2/app/async/async-component.html | 24 + testapp/ng2/app/async/async.component.js | 102 + testapp/ng2/app/async/async.component.js.map | 1 + testapp/ng2/app/async/async.component.ts | 72 + testapp/ng2/app/boot.js | 22 + testapp/ng2/app/boot.js.map | 1 + testapp/ng2/app/boot.ts | 7 + testapp/ng2/app/home/home-component.html | 1 + testapp/ng2/app/home/home.component.js | 34 + testapp/ng2/app/home/home.component.js.map | 1 + testapp/ng2/app/home/home.component.ts | 8 + testapp/ng2/index.html | 45 + .../bundles/angular2-polyfills.js | 3284 + .../bundles/angular2.dev.js | 25074 ++++++++ .../lib/angular2.0.0-beta.0/bundles/router.js | 2972 + testapp/ng2/lib/es6-shim/es6-shim.min.js | 12 + testapp/ng2/lib/rxjs/bundles/Rx.js | 10218 ++++ .../ng2/lib/systemjs/dist/system-polyfills.js | 5 + testapp/ng2/lib/systemjs/dist/system.js | 6 + testapp/ng2/lib/typescript/lib/typescript.js | 50335 ++++++++++++++++ testapp/ng2/styles.css | 10 + 30 files changed, 92357 insertions(+), 5 deletions(-) create mode 100644 spec/ciNg2Conf.js create mode 100644 testapp/ng2/app/app-router.html create mode 100644 testapp/ng2/app/app.router.js create mode 100644 testapp/ng2/app/app.router.js.map create mode 100644 testapp/ng2/app/app.router.ts create mode 100644 testapp/ng2/app/async/async-component.html create mode 100644 testapp/ng2/app/async/async.component.js create mode 100644 testapp/ng2/app/async/async.component.js.map create mode 100644 testapp/ng2/app/async/async.component.ts create mode 100644 testapp/ng2/app/boot.js create mode 100644 testapp/ng2/app/boot.js.map create mode 100644 testapp/ng2/app/boot.ts create mode 100644 testapp/ng2/app/home/home-component.html create mode 100644 testapp/ng2/app/home/home.component.js create mode 100644 testapp/ng2/app/home/home.component.js.map create mode 100644 testapp/ng2/app/home/home.component.ts create mode 100644 testapp/ng2/index.html create mode 100644 testapp/ng2/lib/angular2.0.0-beta.0/bundles/angular2-polyfills.js create mode 100644 testapp/ng2/lib/angular2.0.0-beta.0/bundles/angular2.dev.js create mode 100644 testapp/ng2/lib/angular2.0.0-beta.0/bundles/router.js create mode 100644 testapp/ng2/lib/es6-shim/es6-shim.min.js create mode 100644 testapp/ng2/lib/rxjs/bundles/Rx.js create mode 100644 testapp/ng2/lib/systemjs/dist/system-polyfills.js create mode 100644 testapp/ng2/lib/systemjs/dist/system.js create mode 100644 testapp/ng2/lib/typescript/lib/typescript.js create mode 100644 testapp/ng2/styles.css diff --git a/scripts/test.js b/scripts/test.js index f35b59ffb..0df3988c0 100755 --- a/scripts/test.js +++ b/scripts/test.js @@ -31,6 +31,7 @@ var passingTests = [ 'node lib/cli.js spec/getCapabilitiesConf.js', 'node lib/cli.js spec/controlLockConf.js', 'node lib/cli.js spec/customFramework.js', + 'node lib/cli.js spec/angular2Conf.js', 'node scripts/interactive_tests/interactive_test.js', 'node scripts/interactive_tests/with_base_url.js', // Unit tests diff --git a/scripts/test_on_travis.sh b/scripts/test_on_travis.sh index c5e0cc51e..d19136d66 100755 --- a/scripts/test_on_travis.sh +++ b/scripts/test_on_travis.sh @@ -5,6 +5,9 @@ if [ $JOB = "smoke" ]; then node bin/protractor spec/ciSmokeConf.js elif [ $JOB = "full" ]; then node bin/protractor spec/ciFullConf.js + if [ $? = "0" ]; then + node bin/protractor spec/ciNg2Conf.js + fi elif [ $JOB = "bstack" ]; then node bin/protractor spec/ciBStackConf.js else diff --git a/spec/angular2Conf.js b/spec/angular2Conf.js index 22200e94b..e9be73cb3 100644 --- a/spec/angular2Conf.js +++ b/spec/angular2Conf.js @@ -10,8 +10,6 @@ var env = require('./environment.js'); // See https://github.com/angular/angular/blob/master/DEVELOPER.md for // setup instructions. // -// TODO: when Angular2 is beta, include a test application in the -// Protractor repository. exports.config = { seleniumAddress: env.seleniumAddress, @@ -23,7 +21,7 @@ exports.config = { capabilities: env.capabilities, - baseUrl: 'http://localhost:8000', + baseUrl: 'http://localhost:8081', // Special option for Angular2, to test against all Angular2 applications // on the page. This means that Protractor will wait for every app to be diff --git a/spec/ciNg2Conf.js b/spec/ciNg2Conf.js new file mode 100644 index 000000000..54b14b423 --- /dev/null +++ b/spec/ciNg2Conf.js @@ -0,0 +1,18 @@ +exports.config = require('./angular2Conf.js').config; + +exports.config.sauceUser = process.env.SAUCE_USERNAME; +exports.config.sauceKey = process.env.SAUCE_ACCESS_KEY; +exports.config.seleniumAddress = undefined; + +// TODO: add in firefox when issue #2784 is fixed +exports.config.multiCapabilities = [{ + 'browserName': 'chrome', + 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, + 'build': process.env.TRAVIS_BUILD_NUMBER, + 'name': 'Protractor suite tests', + 'version': '46', + 'selenium-version': '2.48.2', + 'chromedriver-version': '2.19', + 'platform': 'OS X 10.9' + }]; +exports.config.capabilities = undefined; diff --git a/spec/ng2/async_spec.js b/spec/ng2/async_spec.js index 6253dcb27..c4c91a01c 100644 --- a/spec/ng2/async_spec.js +++ b/spec/ng2/async_spec.js @@ -1,5 +1,5 @@ describe('async angular2 application', function() { - var URL = 'examples/src/async/index.html'; + var URL = '/ng2/#/async'; beforeEach(function() { browser.get(URL); @@ -44,7 +44,7 @@ describe('async angular2 application', function() { }); it('should wait for a series of asynchronous actions', function() { - var timeout = $('#multiDelayedIncrements'); + var timeout = $('#chainedDelayedIncrements'); // At this point, the async action is still pending, so the count should // still be 0. @@ -54,4 +54,27 @@ describe('async angular2 application', function() { expect(timeout.$('.val').getText()).toEqual('10'); }); + + it('should wait for a series of periodic increments', function() { + var timeout = $('#periodicIncrement'); + + // Waits for the val to count to 1 and 2. + var EC = protractor.ExpectedConditions; + timeout.$('.action').click(); + browser.wait(EC.textToBePresentInElement(timeout.$('.val'), '1'), 3000); + timeout.$('.cancel').click(); + + var text = timeout.$('.val').getText(); + browser.driver.sleep(3000); + expect(timeout.$('.val').getText()).toEqual(text); + + timeout.$('.action').click(); + browser.wait(EC.textToBePresentInElement(timeout.$('.val'), '3'), 6000); + timeout.$('.cancel').click(); + + text = timeout.$('.val').getText(); + browser.driver.sleep(3000); + expect(timeout.$('.val').getText()).toEqual(text); + + }); }); diff --git a/testapp/ng2/app/app-router.html b/testapp/ng2/app/app-router.html new file mode 100644 index 000000000..8a6eeac32 --- /dev/null +++ b/testapp/ng2/app/app-router.html @@ -0,0 +1,8 @@ +
    +

    Test App for Angular 2

    + + +
    diff --git a/testapp/ng2/app/app.router.js b/testapp/ng2/app/app.router.js new file mode 100644 index 000000000..37771d518 --- /dev/null +++ b/testapp/ng2/app/app.router.js @@ -0,0 +1,49 @@ +System.register(['angular2/core', 'angular2/router', './home/home.component', './async/async.component'], function(exports_1) { + var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); + }; + var core_1, router_1, home_component_1, async_component_1; + var AppRouter; + return { + setters:[ + function (core_1_1) { + core_1 = core_1_1; + }, + function (router_1_1) { + router_1 = router_1_1; + }, + function (home_component_1_1) { + home_component_1 = home_component_1_1; + }, + function (async_component_1_1) { + async_component_1 = async_component_1_1; + }], + execute: function() { + AppRouter = (function () { + function AppRouter() { + } + AppRouter = __decorate([ + core_1.Component({ + selector: 'my-app', + templateUrl: 'app/app-router.html', + directives: [router_1.ROUTER_DIRECTIVES] + }), + router_1.RouteConfig([ + { path: '/', name: 'Home', component: home_component_1.HomeComponent }, + { path: '/async', name: 'Async', component: async_component_1.AsyncComponent }, + ]), + __metadata('design:paramtypes', []) + ], AppRouter); + return AppRouter; + })(); + exports_1("AppRouter", AppRouter); + } + } +}); +//# sourceMappingURL=app.router.js.map \ No newline at end of file diff --git a/testapp/ng2/app/app.router.js.map b/testapp/ng2/app/app.router.js.map new file mode 100644 index 000000000..f1a7785c6 --- /dev/null +++ b/testapp/ng2/app/app.router.js.map @@ -0,0 +1 @@ +{"version":3,"file":"app.router.js","sourceRoot":"","sources":["app.router.ts"],"names":["AppRouter","AppRouter.constructor"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;YAMA;gBAAAA;gBAUAC,CAACA;gBAVDD;oBAACA,gBAASA,CAACA;wBACTA,QAAQA,EAAEA,QAAQA;wBAClBA,WAAWA,EAAEA,qBAAqBA;wBAClCA,UAAUA,EAAEA,CAACA,0BAAiBA,CAACA;qBAChCA,CAACA;oBACDA,oBAAWA,CAACA;wBACXA,EAACA,IAAIA,EAACA,GAAGA,EAAEA,IAAIA,EAAEA,MAAMA,EAAEA,SAASA,EAAEA,8BAAaA,EAACA;wBAClDA,EAACA,IAAIA,EAACA,QAAQA,EAAEA,IAAIA,EAAEA,OAAOA,EAAEA,SAASA,EAAEA,gCAAcA,EAACA;qBAC1DA,CAACA;;8BAEDA;gBAADA,gBAACA;YAADA,CAACA,AAVD,IAUC;YAVD,iCAUC,CAAA"} \ No newline at end of file diff --git a/testapp/ng2/app/app.router.ts b/testapp/ng2/app/app.router.ts new file mode 100644 index 000000000..9de8245a0 --- /dev/null +++ b/testapp/ng2/app/app.router.ts @@ -0,0 +1,17 @@ +import {Component} from 'angular2/core'; +import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router'; + +import {HomeComponent} from './home/home.component'; +import {AsyncComponent} from './async/async.component'; + +@Component({ + selector: 'my-app', + templateUrl: 'app/app-router.html', + directives: [ROUTER_DIRECTIVES] +}) +@RouteConfig([ + {path:'/', name: 'Home', component: HomeComponent}, + {path:'/async', name: 'Async', component: AsyncComponent}, +]) +export class AppRouter { +} diff --git a/testapp/ng2/app/async/async-component.html b/testapp/ng2/app/async/async-component.html new file mode 100644 index 000000000..69e4e2d1d --- /dev/null +++ b/testapp/ng2/app/async/async-component.html @@ -0,0 +1,24 @@ +
    + {{val1}} + +
    +
    + {{val2}} + + +
    +
    + {{val3}} + + +
    +
    + {{val4}} + + +
    diff --git a/testapp/ng2/app/async/async.component.js b/testapp/ng2/app/async/async.component.js new file mode 100644 index 000000000..ccf898282 --- /dev/null +++ b/testapp/ng2/app/async/async.component.js @@ -0,0 +1,102 @@ +System.register(['angular2/core', 'angular2/common', 'angular2/src/facade/async'], function(exports_1) { + var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); + }; + var core_1, common_1, async_1; + var AsyncComponent; + return { + setters:[ + function (core_1_1) { + core_1 = core_1_1; + }, + function (common_1_1) { + common_1 = common_1_1; + }, + function (async_1_1) { + async_1 = async_1_1; + }], + execute: function() { + AsyncComponent = (function () { + function AsyncComponent() { + this.val1 = 0; + this.val2 = 0; + this.val3 = 0; + this.val4 = 0; + this.timeoutId = null; + this.multiTimeoutId = null; + this.intervalId = null; + } + AsyncComponent.prototype.increment = function () { this.val1++; }; + ; + AsyncComponent.prototype.delayedIncrement = function () { + var _this = this; + this.cancelDelayedIncrement(); + this.timeoutId = async_1.TimerWrapper.setTimeout(function () { + _this.val2++; + _this.timeoutId = null; + }, 2000); + }; + ; + AsyncComponent.prototype.multiDelayedIncrements = function (i) { + this.cancelMultiDelayedIncrements(); + var self = this; + function helper(_i) { + if (_i <= 0) { + self.multiTimeoutId = null; + return; + } + self.multiTimeoutId = async_1.TimerWrapper.setTimeout(function () { + self.val3++; + helper(_i - 1); + }, 500); + } + helper(i); + }; + ; + AsyncComponent.prototype.periodicIncrement = function () { + var _this = this; + this.cancelPeriodicIncrement(); + this.intervalId = async_1.TimerWrapper.setInterval(function () { _this.val4++; }, 2000); + }; + ; + AsyncComponent.prototype.cancelDelayedIncrement = function () { + if (this.timeoutId != null) { + async_1.TimerWrapper.clearTimeout(this.timeoutId); + this.timeoutId = null; + } + }; + ; + AsyncComponent.prototype.cancelMultiDelayedIncrements = function () { + if (this.multiTimeoutId != null) { + async_1.TimerWrapper.clearTimeout(this.multiTimeoutId); + this.multiTimeoutId = null; + } + }; + ; + AsyncComponent.prototype.cancelPeriodicIncrement = function () { + if (this.intervalId != null) { + async_1.TimerWrapper.clearInterval(this.intervalId); + this.intervalId = null; + } + }; + ; + AsyncComponent = __decorate([ + core_1.Component({ + templateUrl: 'app/async/async-component.html', + directives: [common_1.NgIf] + }), + __metadata('design:paramtypes', []) + ], AsyncComponent); + return AsyncComponent; + })(); + exports_1("AsyncComponent", AsyncComponent); + } + } +}); +//# sourceMappingURL=async.component.js.map \ No newline at end of file diff --git a/testapp/ng2/app/async/async.component.js.map b/testapp/ng2/app/async/async.component.js.map new file mode 100644 index 000000000..dfdfa1f93 --- /dev/null +++ b/testapp/ng2/app/async/async.component.js.map @@ -0,0 +1 @@ +{"version":3,"file":"async.component.js","sourceRoot":"","sources":["async.component.ts"],"names":["AsyncComponent","AsyncComponent.constructor","AsyncComponent.increment","AsyncComponent.delayedIncrement","AsyncComponent.multiDelayedIncrements","AsyncComponent.multiDelayedIncrements.helper","AsyncComponent.periodicIncrement","AsyncComponent.cancelDelayedIncrement","AsyncComponent.cancelMultiDelayedIncrements","AsyncComponent.cancelPeriodicIncrement"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;YAKA;gBAAAA;oBAKEC,SAAIA,GAAWA,CAACA,CAACA;oBACjBA,SAAIA,GAAWA,CAACA,CAACA;oBACjBA,SAAIA,GAAWA,CAACA,CAACA;oBACjBA,SAAIA,GAAWA,CAACA,CAACA;oBACjBA,cAASA,GAAGA,IAAIA,CAACA;oBACjBA,mBAAcA,GAAGA,IAAIA,CAACA;oBACtBA,eAAUA,GAAGA,IAAIA,CAACA;gBAuDpBA,CAACA;gBArDCD,kCAASA,GAATA,cAAoBE,IAAIA,CAACA,IAAIA,EAAEA,CAACA,CAACA,CAACA;;gBAElCF,yCAAgBA,GAAhBA;oBAAAG,iBAMCA;oBALCA,IAAIA,CAACA,sBAAsBA,EAAEA,CAACA;oBAC9BA,IAAIA,CAACA,SAASA,GAAGA,oBAAYA,CAACA,UAAUA,CAACA;wBACvCA,KAAIA,CAACA,IAAIA,EAAEA,CAACA;wBACZA,KAAIA,CAACA,SAASA,GAAGA,IAAIA,CAACA;oBACxBA,CAACA,EAAEA,IAAIA,CAACA,CAACA;gBACXA,CAACA;;gBAEDH,+CAAsBA,GAAtBA,UAAuBA,CAASA;oBAC9BI,IAAIA,CAACA,4BAA4BA,EAAEA,CAACA;oBAEpCA,IAAIA,IAAIA,GAAGA,IAAIA,CAACA;oBAChBA,gBAAgBA,EAAEA;wBAChBC,EAAEA,CAACA,CAACA,EAAEA,IAAIA,CAACA,CAACA,CAACA,CAACA;4BACZA,IAAIA,CAACA,cAAcA,GAAGA,IAAIA,CAACA;4BAC3BA,MAAMA,CAACA;wBACTA,CAACA;wBAEDA,IAAIA,CAACA,cAAcA,GAAGA,oBAAYA,CAACA,UAAUA,CAACA;4BAC5CA,IAAIA,CAACA,IAAIA,EAAEA,CAACA;4BACZA,MAAMA,CAACA,EAAEA,GAAGA,CAACA,CAACA,CAACA;wBACjBA,CAACA,EAAEA,GAAGA,CAACA,CAACA;oBACVA,CAACA;oBACDD,MAAMA,CAACA,CAACA,CAACA,CAACA;gBACZA,CAACA;;gBAEDJ,0CAAiBA,GAAjBA;oBAAAM,iBAGCA;oBAFCA,IAAIA,CAACA,uBAAuBA,EAAEA,CAACA;oBAC/BA,IAAIA,CAACA,UAAUA,GAAGA,oBAAYA,CAACA,WAAWA,CAACA,cAAQA,KAAIA,CAACA,IAAIA,EAAEA,CAACA,CAACA,CAACA,EAAEA,IAAIA,CAACA,CAAAA;gBAC1EA,CAACA;;gBAEDN,+CAAsBA,GAAtBA;oBACEO,EAAEA,CAACA,CAACA,IAAIA,CAACA,SAASA,IAAIA,IAAIA,CAACA,CAACA,CAACA;wBAC3BA,oBAAYA,CAACA,YAAYA,CAACA,IAAIA,CAACA,SAASA,CAACA,CAACA;wBAC1CA,IAAIA,CAACA,SAASA,GAAGA,IAAIA,CAACA;oBACxBA,CAACA;gBACHA,CAACA;;gBAEDP,qDAA4BA,GAA5BA;oBACEQ,EAAEA,CAACA,CAACA,IAAIA,CAACA,cAAcA,IAAIA,IAAIA,CAACA,CAACA,CAACA;wBAChCA,oBAAYA,CAACA,YAAYA,CAACA,IAAIA,CAACA,cAAcA,CAACA,CAACA;wBAC/CA,IAAIA,CAACA,cAAcA,GAAGA,IAAIA,CAACA;oBAC7BA,CAACA;gBACHA,CAACA;;gBAEDR,gDAAuBA,GAAvBA;oBACES,EAAEA,CAACA,CAACA,IAAIA,CAACA,UAAUA,IAAIA,IAAIA,CAACA,CAACA,CAACA;wBAC5BA,oBAAYA,CAACA,aAAaA,CAACA,IAAIA,CAACA,UAAUA,CAACA,CAACA;wBAC5CA,IAAIA,CAACA,UAAUA,GAAGA,IAAIA,CAACA;oBACzBA,CAACA;gBACHA,CAACA;;gBAjEHT;oBAACA,gBAASA,CAACA;wBACTA,WAAWA,EAAEA,gCAAgCA;wBAC7CA,UAAUA,EAAEA,CAACA,aAAIA,CAACA;qBACnBA,CAACA;;mCA+DDA;gBAADA,qBAACA;YAADA,CAACA,AAlED,IAkEC;YAlED,2CAkEC,CAAA"} \ No newline at end of file diff --git a/testapp/ng2/app/async/async.component.ts b/testapp/ng2/app/async/async.component.ts new file mode 100644 index 000000000..ad76d2fe1 --- /dev/null +++ b/testapp/ng2/app/async/async.component.ts @@ -0,0 +1,72 @@ +import {bootstrap} from 'angular2/bootstrap'; +import {Component} from 'angular2/core'; +import {NgIf} from 'angular2/common'; +import {TimerWrapper} from 'angular2/src/facade/async'; + +@Component({ + templateUrl: 'app/async/async-component.html', + directives: [NgIf] +}) +export class AsyncComponent { + val1: number = 0; + val2: number = 0; + val3: number = 0; + val4: number = 0; + timeoutId = null; + chainedTimeoutId = null; + intervalId = null; + + increment(): void { this.val1++; }; + + delayedIncrement(): void { + this.cancelDelayedIncrement(); + this.timeoutId = TimerWrapper.setTimeout(() => { + this.val2++; + this.timeoutId = null; + }, 2000); + }; + + chainedDelayedIncrements(i: number): void { + this.cancelChainedDelayedIncrements(); + + var self = this; + function helper(_i) { + if (_i <= 0) { + self.chainedTimeoutId = null; + return; + } + + self.chainedTimeoutId = TimerWrapper.setTimeout(() => { + self.val3++; + helper(_i - 1); + }, 500); + } + helper(i); + }; + + periodicIncrement(): void { + this.cancelPeriodicIncrement(); + this.intervalId = TimerWrapper.setInterval(() => { this.val4++; }, 2000) + }; + + cancelDelayedIncrement(): void { + if (this.timeoutId != null) { + TimerWrapper.clearTimeout(this.timeoutId); + this.timeoutId = null; + } + }; + + cancelChainedDelayedIncrements(): void { + if (this.chainedTimeoutId != null) { + TimerWrapper.clearTimeout(this.chainedTimeoutId); + this.chainedTimeoutId = null; + } + }; + + cancelPeriodicIncrement(): void { + if (this.intervalId != null) { + TimerWrapper.clearInterval(this.intervalId); + this.intervalId = null; + } + }; +} diff --git a/testapp/ng2/app/boot.js b/testapp/ng2/app/boot.js new file mode 100644 index 000000000..69be33654 --- /dev/null +++ b/testapp/ng2/app/boot.js @@ -0,0 +1,22 @@ +System.register(['angular2/core', 'angular2/platform/browser', 'angular2/router', './app.router'], function(exports_1) { + var core_1, browser_1, router_1, app_router_1; + return { + setters:[ + function (core_1_1) { + core_1 = core_1_1; + }, + function (browser_1_1) { + browser_1 = browser_1_1; + }, + function (router_1_1) { + router_1 = router_1_1; + }, + function (app_router_1_1) { + app_router_1 = app_router_1_1; + }], + execute: function() { + browser_1.bootstrap(app_router_1.AppRouter, [router_1.ROUTER_PROVIDERS, core_1.provide(router_1.LocationStrategy, { useClass: router_1.HashLocationStrategy })]); + } + } +}); +//# sourceMappingURL=boot.js.map \ No newline at end of file diff --git a/testapp/ng2/app/boot.js.map b/testapp/ng2/app/boot.js.map new file mode 100644 index 000000000..efde64732 --- /dev/null +++ b/testapp/ng2/app/boot.js.map @@ -0,0 +1 @@ +{"version":3,"file":"boot.js","sourceRoot":"","sources":["boot.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;YAMA,mBAAS,CAAC,sBAAS,EAAE,CAAC,yBAAgB,EAAE,cAAO,CAAC,yBAAgB,EAAE,EAAC,QAAQ,EAAE,6BAAoB,EAAC,CAAC,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/testapp/ng2/app/boot.ts b/testapp/ng2/app/boot.ts new file mode 100644 index 000000000..078599b5f --- /dev/null +++ b/testapp/ng2/app/boot.ts @@ -0,0 +1,7 @@ +import {provide} from 'angular2/core'; +import {bootstrap} from 'angular2/platform/browser'; +import {ROUTER_PROVIDERS, HashLocationStrategy, LocationStrategy} from 'angular2/router'; + +import {AppRouter} from './app.router'; + +bootstrap(AppRouter, [ROUTER_PROVIDERS, provide(LocationStrategy, {useClass: HashLocationStrategy})]); diff --git a/testapp/ng2/app/home/home-component.html b/testapp/ng2/app/home/home-component.html new file mode 100644 index 000000000..35e708ddd --- /dev/null +++ b/testapp/ng2/app/home/home-component.html @@ -0,0 +1 @@ +this is the home diff --git a/testapp/ng2/app/home/home.component.js b/testapp/ng2/app/home/home.component.js new file mode 100644 index 000000000..f6bea41d2 --- /dev/null +++ b/testapp/ng2/app/home/home.component.js @@ -0,0 +1,34 @@ +System.register(['angular2/core'], function(exports_1) { + var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); + }; + var core_1; + var HomeComponent; + return { + setters:[ + function (core_1_1) { + core_1 = core_1_1; + }], + execute: function() { + HomeComponent = (function () { + function HomeComponent() { + } + HomeComponent = __decorate([ + core_1.Component({ + templateUrl: 'app/home/home-component.html' + }), + __metadata('design:paramtypes', []) + ], HomeComponent); + return HomeComponent; + })(); + exports_1("HomeComponent", HomeComponent); + } + } +}); +//# sourceMappingURL=home.component.js.map \ No newline at end of file diff --git a/testapp/ng2/app/home/home.component.js.map b/testapp/ng2/app/home/home.component.js.map new file mode 100644 index 000000000..327f414f2 --- /dev/null +++ b/testapp/ng2/app/home/home.component.js.map @@ -0,0 +1 @@ +{"version":3,"file":"home.component.js","sourceRoot":"","sources":["home.component.ts"],"names":["HomeComponent","HomeComponent.constructor"],"mappings":";;;;;;;;;;;;;;;;;;YAEA;gBAAAA;gBAKAC,CAACA;gBALDD;oBAACA,gBAASA,CAACA;wBACTA,WAAWA,EAAEA,8BAA8BA;qBAC5CA,CAACA;;kCAGDA;gBAADA,oBAACA;YAADA,CAACA,AALD,IAKC;YALD,yCAKC,CAAA"} \ No newline at end of file diff --git a/testapp/ng2/app/home/home.component.ts b/testapp/ng2/app/home/home.component.ts new file mode 100644 index 000000000..62c5b74f2 --- /dev/null +++ b/testapp/ng2/app/home/home.component.ts @@ -0,0 +1,8 @@ +import {Component} from 'angular2/core'; + +@Component({ + templateUrl: 'app/home/home-component.html' +}) +export class HomeComponent { + +} diff --git a/testapp/ng2/index.html b/testapp/ng2/index.html new file mode 100644 index 000000000..384c02e43 --- /dev/null +++ b/testapp/ng2/index.html @@ -0,0 +1,45 @@ + + + + + + + Test App + + + + + + + + + + + + + + + + + + + + loading... + + + + + + diff --git a/testapp/ng2/lib/angular2.0.0-beta.0/bundles/angular2-polyfills.js b/testapp/ng2/lib/angular2.0.0-beta.0/bundles/angular2-polyfills.js new file mode 100644 index 000000000..b07de2a7a --- /dev/null +++ b/testapp/ng2/lib/angular2.0.0-beta.0/bundles/angular2-polyfills.js @@ -0,0 +1,3284 @@ +/** + @license +Copyright 2014-2015 Google, Inc. http://angularjs.org + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + */ + +(function 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; + +var resolvedPromise; + +// TODO(vicb): remove '!isFirefox' when the bug gets fixed: +// https://bugzilla.mozilla.org/show_bug.cgi?id=1162013 +if (hasNativePromise && !isFirefox) { + // When available use a native Promise to schedule microtasks. + // When not available, es6-promise fallback will be used + resolvedPromise = Promise.resolve(); +} + +var es6Promise = require('es6-promise').Promise; + +if (resolvedPromise) { + es6Promise._setScheduler(function(fn) { + resolvedPromise.then(fn); + }); +} + +// es6-promise asap should schedule microtasks via zone.scheduleMicrotask so that any +// user defined hooks are triggered +es6Promise._setAsap(function(fn, arg) { + global.zone.scheduleMicrotask(function() { + fn(arg); + }); +}); + +// The default implementation of scheduleMicrotask use the original es6-promise implementation +// to schedule a microtask +function scheduleMicrotask(fn) { + es6Promise._asap(this.bind(fn)); +} + +function addMicrotaskSupport(zoneClass) { + zoneClass.prototype.scheduleMicrotask = scheduleMicrotask; + return zoneClass; +} + +module.exports = { + addMicrotaskSupport: addMicrotaskSupport +}; + + + + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"es6-promise":17}],5:[function(require,module,exports){ +(function (global){ +'use strict'; + +var fnPatch = require('./functions'); +var promisePatch = require('./promise'); +var mutationObserverPatch = require('./mutation-observer'); +var definePropertyPatch = require('./define-property'); +var registerElementPatch = require('./register-element'); +var webSocketPatch = require('./websocket'); +var eventTargetPatch = require('./event-target'); +var propertyDescriptorPatch = require('./property-descriptor'); +var geolocationPatch = require('./geolocation'); +var fileReaderPatch = require('./file-reader'); + +function apply() { + fnPatch.patchSetClearFunction(global, [ + 'timeout', + 'interval', + 'immediate' + ]); + + fnPatch.patchRequestAnimationFrame(global, [ + 'requestAnimationFrame', + 'mozRequestAnimationFrame', + 'webkitRequestAnimationFrame' + ]); + + fnPatch.patchFunction(global, [ + 'alert', + 'prompt' + ]); + + eventTargetPatch.apply(); + + propertyDescriptorPatch.apply(); + + promisePatch.apply(); + + mutationObserverPatch.patchClass('MutationObserver'); + mutationObserverPatch.patchClass('WebKitMutationObserver'); + + definePropertyPatch.apply(); + + registerElementPatch.apply(); + + geolocationPatch.apply(); + + fileReaderPatch.apply(); +} + +module.exports = { + apply: apply +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./define-property":6,"./event-target":7,"./file-reader":8,"./functions":9,"./geolocation":10,"./mutation-observer":11,"./promise":12,"./property-descriptor":13,"./register-element":14,"./websocket":15}],6:[function(require,module,exports){ +'use strict'; + +var keys = require('../keys'); + +// might need similar for object.freeze +// i regret nothing + +var _defineProperty = Object.defineProperty; +var _getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; +var _create = Object.create; +var unconfigurablesKey = keys.create('unconfigurables'); + +function apply() { + Object.defineProperty = function (obj, prop, desc) { + if (isUnconfigurable(obj, prop)) { + throw new TypeError('Cannot assign to read only property \'' + prop + '\' of ' + obj); + } + if (prop !== 'prototype') { + desc = rewriteDescriptor(obj, prop, desc); + } + return _defineProperty(obj, prop, desc); + }; + + Object.defineProperties = function (obj, props) { + Object.keys(props).forEach(function (prop) { + Object.defineProperty(obj, prop, props[prop]); + }); + return obj; + }; + + Object.create = function (obj, proto) { + if (typeof proto === 'object') { + Object.keys(proto).forEach(function (prop) { + proto[prop] = rewriteDescriptor(obj, prop, proto[prop]); + }); + } + return _create(obj, proto); + }; + + Object.getOwnPropertyDescriptor = function (obj, prop) { + var desc = _getOwnPropertyDescriptor(obj, prop); + if (isUnconfigurable(obj, prop)) { + desc.configurable = false; + } + return desc; + }; +}; + +function _redefineProperty(obj, prop, desc) { + desc = rewriteDescriptor(obj, prop, desc); + return _defineProperty(obj, prop, desc); +}; + +function isUnconfigurable (obj, prop) { + return obj && obj[unconfigurablesKey] && obj[unconfigurablesKey][prop]; +} + +function rewriteDescriptor (obj, prop, desc) { + desc.configurable = true; + if (!desc.configurable) { + if (!obj[unconfigurablesKey]) { + _defineProperty(obj, unconfigurablesKey, { writable: true, value: {} }); + } + obj[unconfigurablesKey][prop] = true; + } + return desc; +} + +module.exports = { + apply: apply, + _redefineProperty: _redefineProperty +}; + + + +},{"../keys":3}],7:[function(require,module,exports){ +(function (global){ +'use strict'; + +var utils = require('../utils'); + +function apply() { + // patched properties depend on addEventListener, so this needs to come first + if (global.EventTarget) { + utils.patchEventTargetMethods(global.EventTarget.prototype); + + // Note: EventTarget is not available in all browsers, + // if it's not available, we instead patch the APIs in the IDL that inherit from EventTarget + } else { + var apis = [ + 'ApplicationCache', + 'EventSource', + 'FileReader', + 'InputMethodContext', + 'MediaController', + 'MessagePort', + 'Node', + 'Performance', + 'SVGElementInstance', + 'SharedWorker', + 'TextTrack', + 'TextTrackCue', + 'TextTrackList', + 'WebKitNamedFlow', + 'Worker', + 'WorkerGlobalScope', + 'XMLHttpRequest', + 'XMLHttpRequestEventTarget', + 'XMLHttpRequestUpload' + ]; + + apis.forEach(function(api) { + var proto = global[api] && global[api].prototype; + + // Some browsers e.g. Android 4.3's don't actually implement + // the EventTarget methods for all of these e.g. FileReader. + // In this case, there is nothing to patch. + if (proto && proto.addEventListener) { + utils.patchEventTargetMethods(proto); + } + }); + + // Patch the methods on `window` instead of `Window.prototype` + // `Window` is not accessible on Android 4.3 + if (typeof(window) !== 'undefined') { + utils.patchEventTargetMethods(window); + } + } +} + +module.exports = { + apply: apply +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../utils":16}],8:[function(require,module,exports){ +'use strict'; + +var utils = require('../utils'); + +function apply() { + utils.patchClass('FileReader'); +} + +module.exports = { + apply: apply +}; +},{"../utils":16}],9:[function(require,module,exports){ +(function (global){ +'use strict'; + +var utils = require('../utils'); + +function patchSetClearFunction(obj, fnNames) { + fnNames.map(function (name) { + return name[0].toUpperCase() + name.substr(1); + }).forEach(function (name) { + var setName = 'set' + name; + var delegate = obj[setName]; + + if (delegate) { + var clearName = 'clear' + name; + var ids = {}; + + var bindArgs = setName === 'setInterval' ? utils.bindArguments : utils.bindArgumentsOnce; + + global.zone[setName] = function (fn) { + var id, fnRef = fn; + arguments[0] = function () { + delete ids[id]; + return fnRef.apply(this, arguments); + }; + var args = bindArgs(arguments); + id = delegate.apply(obj, args); + ids[id] = true; + return id; + }; + + obj[setName] = function () { + return global.zone[setName].apply(this, arguments); + }; + + var clearDelegate = obj[clearName]; + + global.zone[clearName] = function (id) { + if (ids[id]) { + delete ids[id]; + global.zone.dequeueTask(); + } + return clearDelegate.apply(this, arguments); + }; + + obj[clearName] = function () { + return global.zone[clearName].apply(this, arguments); + }; + } + }); +}; + + +/** + * requestAnimationFrame is typically recursively called from within the callback function + * that it executes. To handle this case, only fork a zone if this is executed + * within the root zone. + */ +function patchRequestAnimationFrame(obj, fnNames) { + fnNames.forEach(function (name) { + var delegate = obj[name]; + if (delegate) { + global.zone[name] = function (fn) { + var callZone = global.zone.isRootZone() ? global.zone.fork() : global.zone; + if (fn) { + arguments[0] = function () { + return callZone.run(fn, this, arguments); + }; + } + return delegate.apply(obj, arguments); + }; + + obj[name] = function () { + return global.zone[name].apply(this, arguments); + }; + } + }); +}; + +function patchSetFunction(obj, fnNames) { + fnNames.forEach(function (name) { + var delegate = obj[name]; + + if (delegate) { + global.zone[name] = function (fn) { + arguments[0] = function () { + return fn.apply(this, arguments); + }; + var args = utils.bindArgumentsOnce(arguments); + return delegate.apply(obj, args); + }; + + obj[name] = function () { + return zone[name].apply(this, arguments); + }; + } + }); +}; + +function patchFunction(obj, fnNames) { + fnNames.forEach(function (name) { + var delegate = obj[name]; + global.zone[name] = function () { + return delegate.apply(obj, arguments); + }; + + obj[name] = function () { + return global.zone[name].apply(this, arguments); + }; + }); +}; + + +module.exports = { + patchSetClearFunction: patchSetClearFunction, + patchSetFunction: patchSetFunction, + patchRequestAnimationFrame: patchRequestAnimationFrame, + patchFunction: patchFunction +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../utils":16}],10:[function(require,module,exports){ +(function (global){ +'use strict'; + +var utils = require('../utils'); + +function apply() { + if (global.navigator && global.navigator.geolocation) { + utils.patchPrototype(global.navigator.geolocation, [ + 'getCurrentPosition', + 'watchPosition' + ]); + } +} + +module.exports = { + apply: apply +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../utils":16}],11:[function(require,module,exports){ +(function (global){ +'use strict'; + +var keys = require('../keys'); + +var originalInstanceKey = keys.create('originalInstance'); +var creationZoneKey = keys.create('creationZone'); +var isActiveKey = keys.create('isActive'); + +// wrap some native API on `window` +function patchClass(className) { + var OriginalClass = global[className]; + if (!OriginalClass) return; + + global[className] = function (fn) { + this[originalInstanceKey] = new OriginalClass(global.zone.bind(fn, true)); + // Remember where the class was instantiate to execute the enqueueTask and dequeueTask hooks + this[creationZoneKey] = global.zone; + }; + + var instance = new OriginalClass(function () {}); + + global[className].prototype.disconnect = function () { + var result = this[originalInstanceKey].disconnect.apply(this[originalInstanceKey], arguments); + if (this[isActiveKey]) { + this[creationZoneKey].dequeueTask(); + this[isActiveKey] = false; + } + return result; + }; + + global[className].prototype.observe = function () { + if (!this[isActiveKey]) { + this[creationZoneKey].enqueueTask(); + this[isActiveKey] = true; + } + return this[originalInstanceKey].observe.apply(this[originalInstanceKey], arguments); + }; + + var prop; + for (prop in instance) { + (function (prop) { + if (typeof global[className].prototype !== 'undefined') { + return; + } + if (typeof instance[prop] === 'function') { + global[className].prototype[prop] = function () { + return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments); + }; + } else { + Object.defineProperty(global[className].prototype, prop, { + set: function (fn) { + if (typeof fn === 'function') { + this[originalInstanceKey][prop] = global.zone.bind(fn); + } else { + this[originalInstanceKey][prop] = fn; + } + }, + get: function () { + return this[originalInstanceKey][prop]; + } + }); + } + }(prop)); + } +}; + +module.exports = { + patchClass: patchClass +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../keys":3}],12:[function(require,module,exports){ +(function (global){ +'use strict'; + +var utils = require('../utils'); + +/* + * Patches a function that returns a Promise-like instance. + * + * This function must be used when either: + * - Native Promises are not available, + * - The function returns a Promise-like object. + * + * This is required because zones rely on a Promise monkey patch that could not be applied when + * Promise is not natively available or when the returned object is not an instance of Promise. + * + * Note that calling `bindPromiseFn` on a function that returns a native Promise will also work + * with minimal overhead. + * + * ``` + * var boundFunction = bindPromiseFn(FunctionReturningAPromise); + * + * boundFunction.then(successHandler, errorHandler); + * ``` + */ +var bindPromiseFn; + +if (global.Promise) { + bindPromiseFn = function (delegate) { + return function() { + var delegatePromise = delegate.apply(this, arguments); + + // if the delegate returned an instance of Promise, forward it. + if (delegatePromise instanceof Promise) { + return delegatePromise; + } + + // Otherwise wrap the Promise-like in a global Promise + return new Promise(function(resolve, reject) { + delegatePromise.then(resolve, reject); + }); + }; + }; +} else { + bindPromiseFn = function (delegate) { + return function () { + return _patchThenable(delegate.apply(this, arguments)); + }; + }; +} + + +function _patchPromiseFnsOnObject(objectPath, fnNames) { + var obj = global; + + var exists = objectPath.every(function (segment) { + obj = obj[segment]; + return obj; + }); + + if (!exists) { + return; + } + + fnNames.forEach(function (name) { + var fn = obj[name]; + if (fn) { + obj[name] = bindPromiseFn(fn); + } + }); +} + +function _patchThenable(thenable) { + var then = thenable.then; + thenable.then = function () { + var args = utils.bindArguments(arguments); + var nextThenable = then.apply(thenable, args); + return _patchThenable(nextThenable); + }; + + var ocatch = thenable.catch; + thenable.catch = function () { + var args = utils.bindArguments(arguments); + var nextThenable = ocatch.apply(thenable, args); + return _patchThenable(nextThenable); + }; + + return thenable; +} + + +function apply() { + // Patch .then() and .catch() on native Promises to execute callbacks in the zone where + // those functions are called. + if (global.Promise) { + utils.patchPrototype(Promise.prototype, [ + 'then', + 'catch' + ]); + + // Patch browser APIs that return a Promise + var patchFns = [ + // fetch + [[], ['fetch']], + [['Response', 'prototype'], ['arrayBuffer', 'blob', 'json', 'text']] + ]; + + patchFns.forEach(function(objPathAndFns) { + _patchPromiseFnsOnObject(objPathAndFns[0], objPathAndFns[1]); + }); + } +} + +module.exports = { + apply: apply, + bindPromiseFn: bindPromiseFn +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../utils":16}],13:[function(require,module,exports){ +(function (global){ +'use strict'; + +var webSocketPatch = require('./websocket'); +var utils = require('../utils'); +var keys = require('../keys'); + +var eventNames = 'copy cut paste abort blur focus canplay canplaythrough change click contextmenu dblclick drag dragend dragenter dragleave dragover dragstart drop durationchange emptied ended input invalid keydown keypress keyup load loadeddata loadedmetadata loadstart message mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup pause play playing progress ratechange reset scroll seeked seeking select show stalled submit suspend timeupdate volumechange waiting mozfullscreenchange mozfullscreenerror mozpointerlockchange mozpointerlockerror error webglcontextrestored webglcontextlost webglcontextcreationerror'.split(' '); + +function apply() { + if (utils.isWebWorker()){ + // on WebWorker so don't apply patch + return; + } + + var supportsWebSocket = typeof WebSocket !== 'undefined'; + if (canPatchViaPropertyDescriptor()) { + // for browsers that we can patch the descriptor: Chrome & Firefox + var onEventNames = eventNames.map(function (property) { + return 'on' + property; + }); + utils.patchProperties(HTMLElement.prototype, onEventNames); + utils.patchProperties(XMLHttpRequest.prototype); + if (supportsWebSocket) { + utils.patchProperties(WebSocket.prototype); + } + } else { + // Safari, Android browsers (Jelly Bean) + patchViaCapturingAllTheEvents(); + utils.patchClass('XMLHttpRequest'); + if (supportsWebSocket) { + webSocketPatch.apply(); + } + } +} + +function canPatchViaPropertyDescriptor() { + if (!Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onclick') && typeof Element !== 'undefined') { + // WebKit https://bugs.webkit.org/show_bug.cgi?id=134364 + // IDL interface attributes are not configurable + var desc = Object.getOwnPropertyDescriptor(Element.prototype, 'onclick'); + if (desc && !desc.configurable) return false; + } + + Object.defineProperty(HTMLElement.prototype, 'onclick', { + get: function () { + return true; + } + }); + var elt = document.createElement('div'); + var result = !!elt.onclick; + Object.defineProperty(HTMLElement.prototype, 'onclick', {}); + return result; +}; + +var unboundKey = keys.create('unbound'); + +// Whenever any event fires, we check the event target and all parents +// for `onwhatever` properties and replace them with zone-bound functions +// - Chrome (for now) +function patchViaCapturingAllTheEvents() { + eventNames.forEach(function (property) { + var onproperty = 'on' + property; + document.addEventListener(property, function (event) { + var elt = event.target, bound; + while (elt) { + if (elt[onproperty] && !elt[onproperty][unboundKey]) { + bound = global.zone.bind(elt[onproperty]); + bound[unboundKey] = elt[onproperty]; + elt[onproperty] = bound; + } + elt = elt.parentElement; + } + }, true); + }); +}; + +module.exports = { + apply: apply +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../keys":3,"../utils":16,"./websocket":15}],14:[function(require,module,exports){ +(function (global){ +'use strict'; + +var _redefineProperty = require('./define-property')._redefineProperty; +var utils = require("../utils"); + +function apply() { + if (utils.isWebWorker() || !('registerElement' in global.document)) { + return; + } + + var _registerElement = document.registerElement; + var callbacks = [ + 'createdCallback', + 'attachedCallback', + 'detachedCallback', + 'attributeChangedCallback' + ]; + + document.registerElement = function (name, opts) { + if (opts && opts.prototype) { + callbacks.forEach(function (callback) { + if (opts.prototype.hasOwnProperty(callback)) { + var descriptor = Object.getOwnPropertyDescriptor(opts.prototype, callback); + if (descriptor && descriptor.value) { + descriptor.value = global.zone.bind(descriptor.value); + _redefineProperty(opts.prototype, callback, descriptor); + } else { + opts.prototype[callback] = global.zone.bind(opts.prototype[callback]); + } + } else if (opts.prototype[callback]) { + opts.prototype[callback] = global.zone.bind(opts.prototype[callback]); + } + }); + } + + return _registerElement.apply(document, [name, opts]); + }; +} + +module.exports = { + apply: apply +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../utils":16,"./define-property":6}],15:[function(require,module,exports){ +(function (global){ +'use strict'; + +var utils = require('../utils'); + +// we have to patch the instance since the proto is non-configurable +function apply() { + var WS = global.WebSocket; + utils.patchEventTargetMethods(WS.prototype); + global.WebSocket = function(a, b) { + var socket = arguments.length > 1 ? new WS(a, b) : new WS(a); + var proxySocket; + + // Safari 7.0 has non-configurable own 'onmessage' and friends properties on the socket instance + var onmessageDesc = Object.getOwnPropertyDescriptor(socket, 'onmessage'); + if (onmessageDesc && onmessageDesc.configurable === false) { + proxySocket = Object.create(socket); + ['addEventListener', 'removeEventListener', 'send', 'close'].forEach(function(propName) { + proxySocket[propName] = function() { + return socket[propName].apply(socket, arguments); + }; + }); + } else { + // we can patch the real socket + proxySocket = socket; + } + + utils.patchProperties(proxySocket, ['onclose', 'onerror', 'onmessage', 'onopen']); + + return proxySocket; + }; +} + +module.exports = { + apply: apply +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../utils":16}],16:[function(require,module,exports){ +(function (global){ +'use strict'; + +var keys = require('./keys'); + +function bindArguments(args) { + for (var i = args.length - 1; i >= 0; i--) { + if (typeof args[i] === 'function') { + args[i] = global.zone.bind(args[i]); + } + } + return args; +}; + +function bindArgumentsOnce(args) { + for (var i = args.length - 1; i >= 0; i--) { + if (typeof args[i] === 'function') { + args[i] = global.zone.bindOnce(args[i]); + } + } + return args; +}; + +function patchPrototype(obj, fnNames) { + fnNames.forEach(function (name) { + var delegate = obj[name]; + if (delegate) { + obj[name] = function () { + return delegate.apply(this, bindArguments(arguments)); + }; + } + }); +}; + +function isWebWorker() { + return (typeof document === "undefined"); +} + +function patchProperty(obj, prop) { + var desc = Object.getOwnPropertyDescriptor(obj, prop) || { + enumerable: true, + configurable: true + }; + + // A property descriptor cannot have getter/setter and be writable + // deleting the writable and value properties avoids this error: + // + // TypeError: property descriptors must not specify a value or be writable when a + // getter or setter has been specified + delete desc.writable; + delete desc.value; + + // substr(2) cuz 'onclick' -> 'click', etc + var eventName = prop.substr(2); + var _prop = '_' + prop; + + desc.set = function (fn) { + if (this[_prop]) { + this.removeEventListener(eventName, this[_prop]); + } + + if (typeof fn === 'function') { + this[_prop] = fn; + this.addEventListener(eventName, fn, false); + } else { + this[_prop] = null; + } + }; + + desc.get = function () { + return this[_prop]; + }; + + Object.defineProperty(obj, prop, desc); +}; + +function patchProperties(obj, properties) { + (properties || (function () { + var props = []; + for (var prop in obj) { + props.push(prop); + } + return props; + }()). + filter(function (propertyName) { + return propertyName.substr(0,2) === 'on'; + })). + forEach(function (eventName) { + patchProperty(obj, eventName); + }); +}; + +var originalFnKey = keys.create('originalFn'); +var boundFnsKey = keys.create('boundFns'); + +function patchEventTargetMethods(obj) { + // This is required for the addEventListener hook on the root zone. + obj[keys.common.addEventListener] = obj.addEventListener; + obj.addEventListener = function (eventName, handler, useCapturing) { + //Ignore special listeners of IE11 & Edge dev tools, see https://github.com/angular/zone.js/issues/150 + if (handler && handler.toString() !== "[object FunctionWrapper]") { + var eventType = eventName + (useCapturing ? '$capturing' : '$bubbling'); + var fn; + if (handler.handleEvent) { + // Have to pass in 'handler' reference as an argument here, otherwise it gets clobbered in + // IE9 by the arguments[1] assignment at end of this function. + fn = (function(handler) { + return function() { + handler.handleEvent.apply(handler, arguments); + }; + })(handler); + } else { + fn = handler; + } + + handler[originalFnKey] = fn; + handler[boundFnsKey] = handler[boundFnsKey] || {}; + handler[boundFnsKey][eventType] = handler[boundFnsKey][eventType] || zone.bind(fn); + arguments[1] = handler[boundFnsKey][eventType]; + } + + // - Inside a Web Worker, `this` is undefined, the context is `global` (= `self`) + // - When `addEventListener` is called on the global context in strict mode, `this` is undefined + // see https://github.com/angular/zone.js/issues/190 + var target = this || global; + return global.zone.addEventListener.apply(target, arguments); + }; + + // This is required for the removeEventListener hook on the root zone. + obj[keys.common.removeEventListener] = obj.removeEventListener; + obj.removeEventListener = function (eventName, handler, useCapturing) { + var eventType = eventName + (useCapturing ? '$capturing' : '$bubbling'); + if (handler && handler[boundFnsKey] && handler[boundFnsKey][eventType]) { + var _bound = handler[boundFnsKey]; + arguments[1] = _bound[eventType]; + delete _bound[eventType]; + global.zone.dequeueTask(handler[originalFnKey]); + } + + // - Inside a Web Worker, `this` is undefined, the context is `global` + // - When `addEventListener` is called on the global context in strict mode, `this` is undefined + // see https://github.com/angular/zone.js/issues/190 + var target = this || global; + var result = global.zone.removeEventListener.apply(target, arguments); + return result; + }; +}; + +var originalInstanceKey = keys.create('originalInstance'); + +// wrap some native API on `window` +function patchClass(className) { + var OriginalClass = global[className]; + if (!OriginalClass) return; + + global[className] = function () { + var a = bindArguments(arguments); + switch (a.length) { + case 0: this[originalInstanceKey] = new OriginalClass(); break; + case 1: this[originalInstanceKey] = new OriginalClass(a[0]); break; + case 2: this[originalInstanceKey] = new OriginalClass(a[0], a[1]); break; + case 3: this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]); break; + case 4: this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]); break; + default: throw new Error('what are you even doing?'); + } + }; + + var instance = new OriginalClass(); + + var prop; + for (prop in instance) { + (function (prop) { + if (typeof instance[prop] === 'function') { + global[className].prototype[prop] = function () { + return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments); + }; + } else { + Object.defineProperty(global[className].prototype, prop, { + set: function (fn) { + if (typeof fn === 'function') { + this[originalInstanceKey][prop] = global.zone.bind(fn); + } else { + this[originalInstanceKey][prop] = fn; + } + }, + get: function () { + return this[originalInstanceKey][prop]; + } + }); + } + }(prop)); + } + + for (prop in OriginalClass) { + if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) { + global[className][prop] = OriginalClass[prop]; + } + } +}; + +module.exports = { + bindArguments: bindArguments, + bindArgumentsOnce: bindArgumentsOnce, + patchPrototype: patchPrototype, + patchProperty: patchProperty, + patchProperties: patchProperties, + patchEventTargetMethods: patchEventTargetMethods, + patchClass: patchClass, + isWebWorker: isWebWorker +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./keys":3}],17:[function(require,module,exports){ +(function (process,global){ +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE + * @version 3.0.2 + */ + +(function() { + "use strict"; + function lib$es6$promise$utils$$objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); + } + + function lib$es6$promise$utils$$isFunction(x) { + return typeof x === 'function'; + } + + function lib$es6$promise$utils$$isMaybeThenable(x) { + return typeof x === 'object' && x !== null; + } + + var lib$es6$promise$utils$$_isArray; + if (!Array.isArray) { + lib$es6$promise$utils$$_isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; + } else { + lib$es6$promise$utils$$_isArray = Array.isArray; + } + + var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; + var lib$es6$promise$asap$$len = 0; + var lib$es6$promise$asap$$toString = {}.toString; + var lib$es6$promise$asap$$vertxNext; + var lib$es6$promise$asap$$customSchedulerFn; + + var lib$es6$promise$asap$$asap = function asap(callback, arg) { + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; + lib$es6$promise$asap$$len += 2; + if (lib$es6$promise$asap$$len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (lib$es6$promise$asap$$customSchedulerFn) { + lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush); + } else { + lib$es6$promise$asap$$scheduleFlush(); + } + } + } + + function lib$es6$promise$asap$$setScheduler(scheduleFn) { + lib$es6$promise$asap$$customSchedulerFn = scheduleFn; + } + + function lib$es6$promise$asap$$setAsap(asapFn) { + lib$es6$promise$asap$$asap = asapFn; + } + + var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; + var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; + var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; + var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + + // test for web worker but not in IE10 + var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; + + // node + function lib$es6$promise$asap$$useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function() { + process.nextTick(lib$es6$promise$asap$$flush); + }; + } + + // vertx + function lib$es6$promise$asap$$useVertxTimer() { + return function() { + lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); + }; + } + + function lib$es6$promise$asap$$useMutationObserver() { + var iterations = 0; + var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function() { + node.data = (iterations = ++iterations % 2); + }; + } + + // web worker + function lib$es6$promise$asap$$useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = lib$es6$promise$asap$$flush; + return function () { + channel.port2.postMessage(0); + }; + } + + function lib$es6$promise$asap$$useSetTimeout() { + return function() { + setTimeout(lib$es6$promise$asap$$flush, 1); + }; + } + + var lib$es6$promise$asap$$queue = new Array(1000); + function lib$es6$promise$asap$$flush() { + for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { + var callback = lib$es6$promise$asap$$queue[i]; + var arg = lib$es6$promise$asap$$queue[i+1]; + + callback(arg); + + lib$es6$promise$asap$$queue[i] = undefined; + lib$es6$promise$asap$$queue[i+1] = undefined; + } + + lib$es6$promise$asap$$len = 0; + } + + function lib$es6$promise$asap$$attemptVertx() { + try { + var r = require; + var vertx = r('vertx'); + lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; + return lib$es6$promise$asap$$useVertxTimer(); + } catch(e) { + return lib$es6$promise$asap$$useSetTimeout(); + } + } + + var lib$es6$promise$asap$$scheduleFlush; + // Decide what async method to use to triggering processing of queued callbacks: + if (lib$es6$promise$asap$$isNode) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); + } else if (lib$es6$promise$asap$$BrowserMutationObserver) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); + } else if (lib$es6$promise$asap$$isWorker) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); + } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx(); + } else { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); + } + + function lib$es6$promise$$internal$$noop() {} + + var lib$es6$promise$$internal$$PENDING = void 0; + var lib$es6$promise$$internal$$FULFILLED = 1; + var lib$es6$promise$$internal$$REJECTED = 2; + + var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); + } + + function lib$es6$promise$$internal$$cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); + } + + function lib$es6$promise$$internal$$getThen(promise) { + try { + return promise.then; + } catch(error) { + lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; + return lib$es6$promise$$internal$$GET_THEN_ERROR; + } + } + + function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch(e) { + return e; + } + } + + function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { + lib$es6$promise$asap$$asap(function(promise) { + var sealed = false; + var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { + if (sealed) { return; } + sealed = true; + if (thenable !== value) { + lib$es6$promise$$internal$$resolve(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + }, function(reason) { + if (sealed) { return; } + sealed = true; + + lib$es6$promise$$internal$$reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + lib$es6$promise$$internal$$reject(promise, error); + } + }, promise); + } + + function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { + if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, thenable._result); + } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, thenable._result); + } else { + lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { + lib$es6$promise$$internal$$resolve(promise, value); + }, function(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } + } + + function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) { + if (maybeThenable.constructor === promise.constructor) { + lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); + } else { + var then = lib$es6$promise$$internal$$getThen(maybeThenable); + + if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); + } else if (then === undefined) { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } else if (lib$es6$promise$utils$$isFunction(then)) { + lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); + } else { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } + } + } + + function lib$es6$promise$$internal$$resolve(promise, value) { + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment()); + } else if (lib$es6$promise$utils$$objectOrFunction(value)) { + lib$es6$promise$$internal$$handleMaybeThenable(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + } + + function lib$es6$promise$$internal$$publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + lib$es6$promise$$internal$$publish(promise); + } + + function lib$es6$promise$$internal$$fulfill(promise, value) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + + promise._result = value; + promise._state = lib$es6$promise$$internal$$FULFILLED; + + if (promise._subscribers.length !== 0) { + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise); + } + } + + function lib$es6$promise$$internal$$reject(promise, reason) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + promise._state = lib$es6$promise$$internal$$REJECTED; + promise._result = reason; + + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise); + } + + function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + parent._onerror = null; + + subscribers[length] = child; + subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; + subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; + + if (length === 0 && parent._state) { + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent); + } + } + + function lib$es6$promise$$internal$$publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { return; } + + var child, callback, detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; + } + + function lib$es6$promise$$internal$$ErrorObject() { + this.error = null; + } + + var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$tryCatch(callback, detail) { + try { + return callback(detail); + } catch(e) { + lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; + return lib$es6$promise$$internal$$TRY_CATCH_ERROR; + } + } + + function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { + var hasCallback = lib$es6$promise$utils$$isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + value = lib$es6$promise$$internal$$tryCatch(callback, detail); + + if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } + + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); + return; + } + + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== lib$es6$promise$$internal$$PENDING) { + // noop + } else if (hasCallback && succeeded) { + lib$es6$promise$$internal$$resolve(promise, value); + } else if (failed) { + lib$es6$promise$$internal$$reject(promise, error); + } else if (settled === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, value); + } else if (settled === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } + } + + function lib$es6$promise$$internal$$initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value){ + lib$es6$promise$$internal$$resolve(promise, value); + }, function rejectPromise(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } catch(e) { + lib$es6$promise$$internal$$reject(promise, e); + } + } + + function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { + var enumerator = this; + + enumerator._instanceConstructor = Constructor; + enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (enumerator._validateInput(input)) { + enumerator._input = input; + enumerator.length = input.length; + enumerator._remaining = input.length; + + enumerator._init(); + + if (enumerator.length === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } else { + enumerator.length = enumerator.length || 0; + enumerator._enumerate(); + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } + } + } else { + lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError()); + } + } + + lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) { + return lib$es6$promise$utils$$isArray(input); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { + return new Error('Array Methods must be provided an Array'); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._init = function() { + this._result = new Array(this.length); + }; + + var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; + + lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { + var enumerator = this; + + var length = enumerator.length; + var promise = enumerator.promise; + var input = enumerator._input; + + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + enumerator._eachEntry(input[i], i); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { + var enumerator = this; + var c = enumerator._instanceConstructor; + + if (lib$es6$promise$utils$$isMaybeThenable(entry)) { + if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) { + entry._onerror = null; + enumerator._settledAt(entry._state, i, entry._result); + } else { + enumerator._willSettleAt(c.resolve(entry), i); + } + } else { + enumerator._remaining--; + enumerator._result[i] = entry; + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { + var enumerator = this; + var promise = enumerator.promise; + + if (promise._state === lib$es6$promise$$internal$$PENDING) { + enumerator._remaining--; + + if (state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } else { + enumerator._result[i] = value; + } + } + + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(promise, enumerator._result); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { + var enumerator = this; + + lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { + enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); + }, function(reason) { + enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); + }); + }; + function lib$es6$promise$promise$all$$all(entries) { + return new lib$es6$promise$enumerator$$default(this, entries).promise; + } + var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; + function lib$es6$promise$promise$race$$race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (!lib$es6$promise$utils$$isArray(entries)) { + lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); + return promise; + } + + var length = entries.length; + + function onFulfillment(value) { + lib$es6$promise$$internal$$resolve(promise, value); + } + + function onRejection(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + } + + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); + } + + return promise; + } + var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; + function lib$es6$promise$promise$resolve$$resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$resolve(promise, object); + return promise; + } + var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; + function lib$es6$promise$promise$reject$$reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$reject(promise, reason); + return promise; + } + var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; + + var lib$es6$promise$promise$$counter = 0; + + function lib$es6$promise$promise$$needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + + function lib$es6$promise$promise$$needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); + } + + var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; + /** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor + */ + function lib$es6$promise$promise$$Promise(resolver) { + this._id = lib$es6$promise$promise$$counter++; + this._state = undefined; + this._result = undefined; + this._subscribers = []; + + if (lib$es6$promise$$internal$$noop !== resolver) { + if (!lib$es6$promise$utils$$isFunction(resolver)) { + lib$es6$promise$promise$$needsResolver(); + } + + if (!(this instanceof lib$es6$promise$promise$$Promise)) { + lib$es6$promise$promise$$needsNew(); + } + + lib$es6$promise$$internal$$initializePromise(this, resolver); + } + } + + lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; + lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; + lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; + lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; + lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler; + lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap; + lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap; + + lib$es6$promise$promise$$Promise.prototype = { + constructor: lib$es6$promise$promise$$Promise, + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + then: function(onFulfillment, onRejection) { + var parent = this; + var state = parent._state; + + if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { + return this; + } + + var child = new this.constructor(lib$es6$promise$$internal$$noop); + var result = parent._result; + + if (state) { + var callback = arguments[state - 1]; + lib$es6$promise$asap$$asap(function(){ + lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); + }); + } else { + lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); + } + + return child; + }, + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + 'catch': function(onRejection) { + return this.then(null, onRejection); + } + }; + function lib$es6$promise$polyfill$$polyfill() { + var local; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { + return; + } + + local.Promise = lib$es6$promise$promise$$default; + } + var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; + + var lib$es6$promise$umd$$ES6Promise = { + 'Promise': lib$es6$promise$promise$$default, + 'polyfill': lib$es6$promise$polyfill$$default + }; + + /* global define:true module:true window: true */ + if (typeof define === 'function' && define['amd']) { + define(function() { return lib$es6$promise$umd$$ES6Promise; }); + } else if (typeof module !== 'undefined' && module['exports']) { + module['exports'] = lib$es6$promise$umd$$ES6Promise; + } else if (typeof this !== 'undefined') { + this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; + } + + lib$es6$promise$polyfill$$default(); +}).call(this); + + +}).call(this,{},typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}]},{},[1]); + +(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 Reflect.defineMetadata("custom:annotation", options, target, key); + * } + * + */ + function defineMetadata(metadataKey, metadataValue, target, targetKey) { + if (!IsObject(target)) { + throw new TypeError(); + } + else if (!IsUndefined(targetKey)) { + targetKey = ToPropertyKey(targetKey); + } + return OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, targetKey); + } + Reflect.defineMetadata = defineMetadata; + /** + * Gets a value indicating whether the target object or its prototype chain has the provided metadata key defined. + * @param metadataKey A key used to store and retrieve metadata. + * @param target The target object on which the metadata is defined. + * @param targetKey (Optional) The property key for the target. + * @returns `true` if the metadata key was defined on the target object or its prototype chain; otherwise, `false`. + * @example + * + * class C { + * // property declarations are not part of ES6, though they are valid in TypeScript: + * // static staticProperty; + * // property; + * + * constructor(p) { } + * static staticMethod(p) { } + * method(p) { } + * } + * + * // constructor + * result = Reflect.hasMetadata("custom:annotation", C); + * + * // property (on constructor) + * result = Reflect.hasMetadata("custom:annotation", C, "staticProperty"); + * + * // property (on prototype) + * result = Reflect.hasMetadata("custom:annotation", C.prototype, "property"); + * + * // method (on constructor) + * result = Reflect.hasMetadata("custom:annotation", C, "staticMethod"); + * + * // method (on prototype) + * result = Reflect.hasMetadata("custom:annotation", C.prototype, "method"); + * + */ + function hasMetadata(metadataKey, target, targetKey) { + if (!IsObject(target)) { + throw new TypeError(); + } + else if (!IsUndefined(targetKey)) { + targetKey = ToPropertyKey(targetKey); + } + return OrdinaryHasMetadata(metadataKey, target, targetKey); + } + Reflect.hasMetadata = hasMetadata; + /** + * Gets a value indicating whether the target object has the provided metadata key defined. + * @param metadataKey A key used to store and retrieve metadata. + * @param target The target object on which the metadata is defined. + * @param targetKey (Optional) The property key for the target. + * @returns `true` if the metadata key was defined on the target object; otherwise, `false`. + * @example + * + * class C { + * // property declarations are not part of ES6, though they are valid in TypeScript: + * // static staticProperty; + * // property; + * + * constructor(p) { } + * static staticMethod(p) { } + * method(p) { } + * } + * + * // constructor + * result = Reflect.hasOwnMetadata("custom:annotation", C); + * + * // property (on constructor) + * result = Reflect.hasOwnMetadata("custom:annotation", C, "staticProperty"); + * + * // property (on prototype) + * result = Reflect.hasOwnMetadata("custom:annotation", C.prototype, "property"); + * + * // method (on constructor) + * result = Reflect.hasOwnMetadata("custom:annotation", C, "staticMethod"); + * + * // method (on prototype) + * result = Reflect.hasOwnMetadata("custom:annotation", C.prototype, "method"); + * + */ + function hasOwnMetadata(metadataKey, target, targetKey) { + if (!IsObject(target)) { + throw new TypeError(); + } + else if (!IsUndefined(targetKey)) { + targetKey = ToPropertyKey(targetKey); + } + return OrdinaryHasOwnMetadata(metadataKey, target, targetKey); + } + Reflect.hasOwnMetadata = hasOwnMetadata; + /** + * Gets the metadata value for the provided metadata key on the target object or its prototype chain. + * @param metadataKey A key used to store and retrieve metadata. + * @param target The target object on which the metadata is defined. + * @param targetKey (Optional) The property key for the target. + * @returns The metadata value for the metadata key if found; otherwise, `undefined`. + * @example + * + * class C { + * // property declarations are not part of ES6, though they are valid in TypeScript: + * // static staticProperty; + * // property; + * + * constructor(p) { } + * static staticMethod(p) { } + * method(p) { } + * } + * + * // constructor + * result = Reflect.getMetadata("custom:annotation", C); + * + * // property (on constructor) + * result = Reflect.getMetadata("custom:annotation", C, "staticProperty"); + * + * // property (on prototype) + * result = Reflect.getMetadata("custom:annotation", C.prototype, "property"); + * + * // method (on constructor) + * result = Reflect.getMetadata("custom:annotation", C, "staticMethod"); + * + * // method (on prototype) + * result = Reflect.getMetadata("custom:annotation", C.prototype, "method"); + * + */ + function getMetadata(metadataKey, target, targetKey) { + if (!IsObject(target)) { + throw new TypeError(); + } + else if (!IsUndefined(targetKey)) { + targetKey = ToPropertyKey(targetKey); + } + return OrdinaryGetMetadata(metadataKey, target, targetKey); + } + Reflect.getMetadata = getMetadata; + /** + * Gets the metadata value for the provided metadata key on the target object. + * @param metadataKey A key used to store and retrieve metadata. + * @param target The target object on which the metadata is defined. + * @param targetKey (Optional) The property key for the target. + * @returns The metadata value for the metadata key if found; otherwise, `undefined`. + * @example + * + * class C { + * // property declarations are not part of ES6, though they are valid in TypeScript: + * // static staticProperty; + * // property; + * + * constructor(p) { } + * static staticMethod(p) { } + * method(p) { } + * } + * + * // constructor + * result = Reflect.getOwnMetadata("custom:annotation", C); + * + * // property (on constructor) + * result = Reflect.getOwnMetadata("custom:annotation", C, "staticProperty"); + * + * // property (on prototype) + * result = Reflect.getOwnMetadata("custom:annotation", C.prototype, "property"); + * + * // method (on constructor) + * result = Reflect.getOwnMetadata("custom:annotation", C, "staticMethod"); + * + * // method (on prototype) + * result = Reflect.getOwnMetadata("custom:annotation", C.prototype, "method"); + * + */ + function getOwnMetadata(metadataKey, target, targetKey) { + if (!IsObject(target)) { + throw new TypeError(); + } + else if (!IsUndefined(targetKey)) { + targetKey = ToPropertyKey(targetKey); + } + return OrdinaryGetOwnMetadata(metadataKey, target, targetKey); + } + Reflect.getOwnMetadata = getOwnMetadata; + /** + * Gets the metadata keys defined on the target object or its prototype chain. + * @param target The target object on which the metadata is defined. + * @param targetKey (Optional) The property key for the target. + * @returns An array of unique metadata keys. + * @example + * + * class C { + * // property declarations are not part of ES6, though they are valid in TypeScript: + * // static staticProperty; + * // property; + * + * constructor(p) { } + * static staticMethod(p) { } + * method(p) { } + * } + * + * // constructor + * result = Reflect.getMetadataKeys(C); + * + * // property (on constructor) + * result = Reflect.getMetadataKeys(C, "staticProperty"); + * + * // property (on prototype) + * result = Reflect.getMetadataKeys(C.prototype, "property"); + * + * // method (on constructor) + * result = Reflect.getMetadataKeys(C, "staticMethod"); + * + * // method (on prototype) + * result = Reflect.getMetadataKeys(C.prototype, "method"); + * + */ + function getMetadataKeys(target, targetKey) { + if (!IsObject(target)) { + throw new TypeError(); + } + else if (!IsUndefined(targetKey)) { + targetKey = ToPropertyKey(targetKey); + } + return OrdinaryMetadataKeys(target, targetKey); + } + Reflect.getMetadataKeys = getMetadataKeys; + /** + * Gets the unique metadata keys defined on the target object. + * @param target The target object on which the metadata is defined. + * @param targetKey (Optional) The property key for the target. + * @returns An array of unique metadata keys. + * @example + * + * class C { + * // property declarations are not part of ES6, though they are valid in TypeScript: + * // static staticProperty; + * // property; + * + * constructor(p) { } + * static staticMethod(p) { } + * method(p) { } + * } + * + * // constructor + * result = Reflect.getOwnMetadataKeys(C); + * + * // property (on constructor) + * result = Reflect.getOwnMetadataKeys(C, "staticProperty"); + * + * // property (on prototype) + * result = Reflect.getOwnMetadataKeys(C.prototype, "property"); + * + * // method (on constructor) + * result = Reflect.getOwnMetadataKeys(C, "staticMethod"); + * + * // method (on prototype) + * result = Reflect.getOwnMetadataKeys(C.prototype, "method"); + * + */ + function getOwnMetadataKeys(target, targetKey) { + if (!IsObject(target)) { + throw new TypeError(); + } + else if (!IsUndefined(targetKey)) { + targetKey = ToPropertyKey(targetKey); + } + return OrdinaryOwnMetadataKeys(target, targetKey); + } + Reflect.getOwnMetadataKeys = getOwnMetadataKeys; + /** + * Deletes the metadata entry from the target object with the provided key. + * @param metadataKey A key used to store and retrieve metadata. + * @param target The target object on which the metadata is defined. + * @param targetKey (Optional) The property key for the target. + * @returns `true` if the metadata entry was found and deleted; otherwise, false. + * @example + * + * class C { + * // property declarations are not part of ES6, though they are valid in TypeScript: + * // static staticProperty; + * // property; + * + * constructor(p) { } + * static staticMethod(p) { } + * method(p) { } + * } + * + * // constructor + * result = Reflect.deleteMetadata("custom:annotation", C); + * + * // property (on constructor) + * result = Reflect.deleteMetadata("custom:annotation", C, "staticProperty"); + * + * // property (on prototype) + * result = Reflect.deleteMetadata("custom:annotation", C.prototype, "property"); + * + * // method (on constructor) + * result = Reflect.deleteMetadata("custom:annotation", C, "staticMethod"); + * + * // method (on prototype) + * result = Reflect.deleteMetadata("custom:annotation", C.prototype, "method"); + * + */ + function deleteMetadata(metadataKey, target, targetKey) { + if (!IsObject(target)) { + throw new TypeError(); + } + else if (!IsUndefined(targetKey)) { + targetKey = ToPropertyKey(targetKey); + } + // https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md#deletemetadata-metadatakey-p- + var metadataMap = GetOrCreateMetadataMap(target, targetKey, false); + if (IsUndefined(metadataMap)) { + return false; + } + if (!metadataMap.delete(metadataKey)) { + return false; + } + if (metadataMap.size > 0) { + return true; + } + var targetMetadata = __Metadata__.get(target); + targetMetadata.delete(targetKey); + if (targetMetadata.size > 0) { + return true; + } + __Metadata__.delete(target); + return true; + } + Reflect.deleteMetadata = deleteMetadata; + function DecorateConstructor(decorators, target) { + for (var i = decorators.length - 1; i >= 0; --i) { + var decorator = decorators[i]; + var decorated = decorator(target); + if (!IsUndefined(decorated)) { + if (!IsConstructor(decorated)) { + throw new TypeError(); + } + target = decorated; + } + } + return target; + } + function DecoratePropertyWithDescriptor(decorators, target, propertyKey, descriptor) { + for (var i = decorators.length - 1; i >= 0; --i) { + var decorator = decorators[i]; + var decorated = decorator(target, propertyKey, descriptor); + if (!IsUndefined(decorated)) { + if (!IsObject(decorated)) { + throw new TypeError(); + } + descriptor = decorated; + } + } + return descriptor; + } + function DecoratePropertyWithoutDescriptor(decorators, target, propertyKey) { + for (var i = decorators.length - 1; i >= 0; --i) { + var decorator = decorators[i]; + decorator(target, propertyKey); + } + } + // https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md#getorcreatemetadatamap--o-p-create- + function GetOrCreateMetadataMap(target, targetKey, create) { + var targetMetadata = __Metadata__.get(target); + if (!targetMetadata) { + if (!create) { + return undefined; + } + targetMetadata = new _Map(); + __Metadata__.set(target, targetMetadata); + } + var keyMetadata = targetMetadata.get(targetKey); + if (!keyMetadata) { + if (!create) { + return undefined; + } + keyMetadata = new _Map(); + targetMetadata.set(targetKey, keyMetadata); + } + return keyMetadata; + } + // https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md#ordinaryhasmetadata--metadatakey-o-p- + function OrdinaryHasMetadata(MetadataKey, O, P) { + var hasOwn = OrdinaryHasOwnMetadata(MetadataKey, O, P); + if (hasOwn) { + return true; + } + var parent = GetPrototypeOf(O); + if (parent !== null) { + return OrdinaryHasMetadata(MetadataKey, parent, P); + } + return false; + } + // https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md#ordinaryhasownmetadata--metadatakey-o-p- + function OrdinaryHasOwnMetadata(MetadataKey, O, P) { + var metadataMap = GetOrCreateMetadataMap(O, P, false); + if (metadataMap === undefined) { + return false; + } + return Boolean(metadataMap.has(MetadataKey)); + } + // https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md#ordinarygetmetadata--metadatakey-o-p- + function OrdinaryGetMetadata(MetadataKey, O, P) { + var hasOwn = OrdinaryHasOwnMetadata(MetadataKey, O, P); + if (hasOwn) { + return OrdinaryGetOwnMetadata(MetadataKey, O, P); + } + var parent = GetPrototypeOf(O); + if (parent !== null) { + return OrdinaryGetMetadata(MetadataKey, parent, P); + } + return undefined; + } + // https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md#ordinarygetownmetadata--metadatakey-o-p- + function OrdinaryGetOwnMetadata(MetadataKey, O, P) { + var metadataMap = GetOrCreateMetadataMap(O, P, false); + if (metadataMap === undefined) { + return undefined; + } + return metadataMap.get(MetadataKey); + } + // https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md#ordinarydefineownmetadata--metadatakey-metadatavalue-o-p- + function OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) { + var metadataMap = GetOrCreateMetadataMap(O, P, true); + metadataMap.set(MetadataKey, MetadataValue); + } + // https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md#ordinarymetadatakeys--o-p- + function OrdinaryMetadataKeys(O, P) { + var ownKeys = OrdinaryOwnMetadataKeys(O, P); + var parent = GetPrototypeOf(O); + if (parent === null) { + return ownKeys; + } + var parentKeys = OrdinaryMetadataKeys(parent, P); + if (parentKeys.length <= 0) { + return ownKeys; + } + if (ownKeys.length <= 0) { + return parentKeys; + } + var set = new _Set(); + var keys = []; + for (var _i = 0; _i < ownKeys.length; _i++) { + var key = ownKeys[_i]; + var hasKey = set.has(key); + if (!hasKey) { + set.add(key); + keys.push(key); + } + } + for (var _a = 0; _a < parentKeys.length; _a++) { + var key = parentKeys[_a]; + var hasKey = set.has(key); + if (!hasKey) { + set.add(key); + keys.push(key); + } + } + return keys; + } + // https://github.com/jonathandturner/decorators/blob/master/specs/metadata.md#ordinaryownmetadatakeys--o-p- + function OrdinaryOwnMetadataKeys(target, targetKey) { + var metadataMap = GetOrCreateMetadataMap(target, targetKey, false); + var keys = []; + if (metadataMap) { + metadataMap.forEach(function (_, key) { return keys.push(key); }); + } + return keys; + } + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-ecmascript-language-types-undefined-type + function IsUndefined(x) { + return x === undefined; + } + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isarray + function IsArray(x) { + return Array.isArray(x); + } + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object-type + function IsObject(x) { + return typeof x === "object" ? x !== null : typeof x === "function"; + } + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isconstructor + function IsConstructor(x) { + return typeof x === "function"; + } + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-ecmascript-language-types-symbol-type + function IsSymbol(x) { + return typeof x === "symbol"; + } + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-topropertykey + function ToPropertyKey(value) { + if (IsSymbol(value)) { + return value; + } + return String(value); + } + function GetPrototypeOf(O) { + var proto = Object.getPrototypeOf(O); + if (typeof O !== "function" || O === functionPrototype) { + return proto; + } + // TypeScript doesn't set __proto__ in ES5, as it's non-standard. + // Try to determine the superclass constructor. Compatible implementations + // must either set __proto__ on a subclass constructor to the superclass constructor, + // or ensure each class has a valid `constructor` property on its prototype that + // points back to the constructor. + // If this is not the same as Function.[[Prototype]], then this is definately inherited. + // This is the case when in ES6 or when using __proto__ in a compatible browser. + if (proto !== functionPrototype) { + return proto; + } + // If the super prototype is Object.prototype, null, or undefined, then we cannot determine the heritage. + var prototype = O.prototype; + var prototypeProto = Object.getPrototypeOf(prototype); + if (prototypeProto == null || prototypeProto === Object.prototype) { + return proto; + } + // if the constructor was not a function, then we cannot determine the heritage. + var constructor = prototypeProto.constructor; + if (typeof constructor !== "function") { + return proto; + } + // if we have some kind of self-reference, then we cannot determine the heritage. + if (constructor === O) { + return proto; + } + // we have a pretty good guess at the heritage. + return constructor; + } + // naive Map shim + function CreateMapPolyfill() { + var cacheSentinel = {}; + function Map() { + this._keys = []; + this._values = []; + this._cache = cacheSentinel; + } + Map.prototype = { + get size() { + return this._keys.length; + }, + has: function (key) { + if (key === this._cache) { + return true; + } + if (this._find(key) >= 0) { + this._cache = key; + return true; + } + return false; + }, + get: function (key) { + var index = this._find(key); + if (index >= 0) { + this._cache = key; + return this._values[index]; + } + return undefined; + }, + set: function (key, value) { + this.delete(key); + this._keys.push(key); + this._values.push(value); + this._cache = key; + return this; + }, + delete: function (key) { + var index = this._find(key); + if (index >= 0) { + this._keys.splice(index, 1); + this._values.splice(index, 1); + this._cache = cacheSentinel; + return true; + } + return false; + }, + clear: function () { + this._keys.length = 0; + this._values.length = 0; + this._cache = cacheSentinel; + }, + forEach: function (callback, thisArg) { + var size = this.size; + for (var i = 0; i < size; ++i) { + var key = this._keys[i]; + var value = this._values[i]; + this._cache = key; + callback.call(this, value, key, this); + } + }, + _find: function (key) { + var keys = this._keys; + var size = keys.length; + for (var i = 0; i < size; ++i) { + if (keys[i] === key) { + return i; + } + } + return -1; + } + }; + return Map; + } + // naive Set shim + function CreateSetPolyfill() { + var cacheSentinel = {}; + function Set() { + this._map = new _Map(); + } + Set.prototype = { + get size() { + return this._map.length; + }, + has: function (value) { + return this._map.has(value); + }, + add: function (value) { + this._map.set(value, value); + return this; + }, + delete: function (value) { + return this._map.delete(value); + }, + clear: function () { + this._map.clear(); + }, + forEach: function (callback, thisArg) { + this._map.forEach(callback, thisArg); + } + }; + return Set; + } + // naive WeakMap shim + function CreateWeakMapPolyfill() { + var UUID_SIZE = 16; + var isNode = typeof global !== "undefined" && Object.prototype.toString.call(global.process) === '[object process]'; + var nodeCrypto = isNode && require("crypto"); + var hasOwn = Object.prototype.hasOwnProperty; + var keys = {}; + var rootKey = CreateUniqueKey(); + function WeakMap() { + this._key = CreateUniqueKey(); + } + WeakMap.prototype = { + has: function (target) { + var table = GetOrCreateWeakMapTable(target, false); + if (table) { + return this._key in table; + } + return false; + }, + get: function (target) { + var table = GetOrCreateWeakMapTable(target, false); + if (table) { + return table[this._key]; + } + return undefined; + }, + set: function (target, value) { + var table = GetOrCreateWeakMapTable(target, true); + table[this._key] = value; + return this; + }, + delete: function (target) { + var table = GetOrCreateWeakMapTable(target, false); + if (table && this._key in table) { + return delete table[this._key]; + } + return false; + }, + clear: function () { + // NOTE: not a real clear, just makes the previous data unreachable + this._key = CreateUniqueKey(); + } + }; + function FillRandomBytes(buffer, size) { + for (var i = 0; i < size; ++i) { + buffer[i] = Math.random() * 255 | 0; + } + } + function GenRandomBytes(size) { + if (nodeCrypto) { + var data = nodeCrypto.randomBytes(size); + return data; + } + else if (typeof Uint8Array === "function") { + var data = new Uint8Array(size); + if (typeof crypto !== "undefined") { + crypto.getRandomValues(data); + } + else if (typeof msCrypto !== "undefined") { + msCrypto.getRandomValues(data); + } + else { + FillRandomBytes(data, size); + } + return data; + } + else { + var data = new Array(size); + FillRandomBytes(data, size); + return data; + } + } + function CreateUUID() { + var data = GenRandomBytes(UUID_SIZE); + // mark as random - RFC 4122 § 4.4 + data[6] = data[6] & 0x4f | 0x40; + data[8] = data[8] & 0xbf | 0x80; + var result = ""; + for (var offset = 0; offset < UUID_SIZE; ++offset) { + var byte = data[offset]; + if (offset === 4 || offset === 6 || offset === 8) { + result += "-"; + } + if (byte < 16) { + result += "0"; + } + result += byte.toString(16).toLowerCase(); + } + return result; + } + function CreateUniqueKey() { + var key; + do { + key = "@@WeakMap@@" + CreateUUID(); + } while (hasOwn.call(keys, key)); + keys[key] = true; + return key; + } + function GetOrCreateWeakMapTable(target, create) { + if (!hasOwn.call(target, rootKey)) { + if (!create) { + return undefined; + } + Object.defineProperty(target, rootKey, { value: Object.create(null) }); + } + return target[rootKey]; + } + return WeakMap; + } + // hook global Reflect + (function (__global) { + if (typeof __global.Reflect !== "undefined") { + if (__global.Reflect !== Reflect) { + for (var p in Reflect) { + __global.Reflect[p] = Reflect[p]; + } + } + } + else { + __global.Reflect = Reflect; + } + })(typeof window !== "undefined" ? window : + typeof WorkerGlobalScope !== "undefined" ? self : + typeof global !== "undefined" ? global : + Function("return this;")()); +})(Reflect || (Reflect = {})); +//# sourceMappingURLDisabled=Reflect.js.map \ No newline at end of file diff --git a/testapp/ng2/lib/angular2.0.0-beta.0/bundles/angular2.dev.js b/testapp/ng2/lib/angular2.0.0-beta.0/bundles/angular2.dev.js new file mode 100644 index 000000000..9f9bde89b --- /dev/null +++ b/testapp/ng2/lib/angular2.0.0-beta.0/bundles/angular2.dev.js @@ -0,0 +1,25074 @@ +"format register"; +System.register("angular2/src/facade/lang", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var globalScope; + if (typeof window === 'undefined') { + if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) { + globalScope = self; + } else { + globalScope = global; + } + } else { + globalScope = window; + } + ; + exports.IS_DART = false; + var _global = globalScope; + exports.global = _global; + exports.Type = Function; + function getTypeNameForDebugging(type) { + return type['name']; + } + exports.getTypeNameForDebugging = getTypeNameForDebugging; + exports.Math = _global.Math; + exports.Date = _global.Date; + var _devMode = true; + var _modeLocked = false; + function lockMode() { + _modeLocked = true; + } + exports.lockMode = lockMode; + function enableProdMode() { + if (_modeLocked) { + throw 'Cannot enable prod mode after platform setup.'; + } + _devMode = false; + } + exports.enableProdMode = enableProdMode; + function assertionsEnabled() { + return _devMode; + } + exports.assertionsEnabled = assertionsEnabled; + _global.assert = function assert(condition) {}; + function CONST_EXPR(expr) { + return expr; + } + exports.CONST_EXPR = CONST_EXPR; + function CONST() { + return function(target) { + return target; + }; + } + exports.CONST = CONST; + function isPresent(obj) { + return obj !== undefined && obj !== null; + } + exports.isPresent = isPresent; + function isBlank(obj) { + return obj === undefined || obj === null; + } + exports.isBlank = isBlank; + function isString(obj) { + return typeof obj === "string"; + } + exports.isString = isString; + function isFunction(obj) { + return typeof obj === "function"; + } + exports.isFunction = isFunction; + function isType(obj) { + return isFunction(obj); + } + exports.isType = isType; + function isStringMap(obj) { + return typeof obj === 'object' && obj !== null; + } + exports.isStringMap = isStringMap; + function isPromise(obj) { + return obj instanceof _global.Promise; + } + exports.isPromise = isPromise; + function isArray(obj) { + return Array.isArray(obj); + } + exports.isArray = isArray; + function isNumber(obj) { + return typeof obj === 'number'; + } + exports.isNumber = isNumber; + function isDate(obj) { + return obj instanceof exports.Date && !isNaN(obj.valueOf()); + } + exports.isDate = isDate; + function noop() {} + exports.noop = noop; + function stringify(token) { + if (typeof token === 'string') { + return token; + } + if (token === undefined || token === null) { + return '' + token; + } + if (token.name) { + return token.name; + } + var res = token.toString(); + var newLineIndex = res.indexOf("\n"); + return (newLineIndex === -1) ? res : res.substring(0, newLineIndex); + } + exports.stringify = stringify; + function serializeEnum(val) { + return val; + } + exports.serializeEnum = serializeEnum; + function deserializeEnum(val, values) { + return val; + } + exports.deserializeEnum = deserializeEnum; + var StringWrapper = (function() { + function StringWrapper() {} + StringWrapper.fromCharCode = function(code) { + return String.fromCharCode(code); + }; + StringWrapper.charCodeAt = function(s, index) { + return s.charCodeAt(index); + }; + StringWrapper.split = function(s, regExp) { + return s.split(regExp); + }; + StringWrapper.equals = function(s, s2) { + return s === s2; + }; + StringWrapper.stripLeft = function(s, charVal) { + if (s && s.length) { + var pos = 0; + for (var i = 0; i < s.length; i++) { + if (s[i] != charVal) + break; + pos++; + } + s = s.substring(pos); + } + return s; + }; + StringWrapper.stripRight = function(s, charVal) { + if (s && s.length) { + var pos = s.length; + for (var i = s.length - 1; i >= 0; i--) { + if (s[i] != charVal) + break; + pos--; + } + s = s.substring(0, pos); + } + return s; + }; + StringWrapper.replace = function(s, from, replace) { + return s.replace(from, replace); + }; + StringWrapper.replaceAll = function(s, from, replace) { + return s.replace(from, replace); + }; + StringWrapper.slice = function(s, from, to) { + if (from === void 0) { + from = 0; + } + if (to === void 0) { + to = null; + } + return s.slice(from, to === null ? undefined : to); + }; + StringWrapper.replaceAllMapped = function(s, from, cb) { + return s.replace(from, function() { + var matches = []; + for (var _i = 0; _i < arguments.length; _i++) { + matches[_i - 0] = arguments[_i]; + } + matches.splice(-2, 2); + return cb(matches); + }); + }; + StringWrapper.contains = function(s, substr) { + return s.indexOf(substr) != -1; + }; + StringWrapper.compare = function(a, b) { + if (a < b) { + return -1; + } else if (a > b) { + return 1; + } else { + return 0; + } + }; + return StringWrapper; + })(); + exports.StringWrapper = StringWrapper; + var StringJoiner = (function() { + function StringJoiner(parts) { + if (parts === void 0) { + parts = []; + } + this.parts = parts; + } + StringJoiner.prototype.add = function(part) { + this.parts.push(part); + }; + StringJoiner.prototype.toString = function() { + return this.parts.join(""); + }; + return StringJoiner; + })(); + exports.StringJoiner = StringJoiner; + var NumberParseError = (function(_super) { + __extends(NumberParseError, _super); + function NumberParseError(message) { + _super.call(this); + this.message = message; + } + NumberParseError.prototype.toString = function() { + return this.message; + }; + return NumberParseError; + })(Error); + exports.NumberParseError = NumberParseError; + var NumberWrapper = (function() { + function NumberWrapper() {} + NumberWrapper.toFixed = function(n, fractionDigits) { + return n.toFixed(fractionDigits); + }; + NumberWrapper.equal = function(a, b) { + return a === b; + }; + NumberWrapper.parseIntAutoRadix = function(text) { + var result = parseInt(text); + if (isNaN(result)) { + throw new NumberParseError("Invalid integer literal when parsing " + text); + } + return result; + }; + NumberWrapper.parseInt = function(text, radix) { + if (radix == 10) { + if (/^(\-|\+)?[0-9]+$/.test(text)) { + return parseInt(text, radix); + } + } else if (radix == 16) { + if (/^(\-|\+)?[0-9ABCDEFabcdef]+$/.test(text)) { + return parseInt(text, radix); + } + } else { + var result = parseInt(text, radix); + if (!isNaN(result)) { + return result; + } + } + throw new NumberParseError("Invalid integer literal when parsing " + text + " in base " + radix); + }; + NumberWrapper.parseFloat = function(text) { + return parseFloat(text); + }; + Object.defineProperty(NumberWrapper, "NaN", { + get: function() { + return NaN; + }, + enumerable: true, + configurable: true + }); + NumberWrapper.isNaN = function(value) { + return isNaN(value); + }; + NumberWrapper.isInteger = function(value) { + return Number.isInteger(value); + }; + return NumberWrapper; + })(); + exports.NumberWrapper = NumberWrapper; + exports.RegExp = _global.RegExp; + var RegExpWrapper = (function() { + function RegExpWrapper() {} + RegExpWrapper.create = function(regExpStr, flags) { + if (flags === void 0) { + flags = ''; + } + flags = flags.replace(/g/g, ''); + return new _global.RegExp(regExpStr, flags + 'g'); + }; + RegExpWrapper.firstMatch = function(regExp, input) { + regExp.lastIndex = 0; + return regExp.exec(input); + }; + RegExpWrapper.test = function(regExp, input) { + regExp.lastIndex = 0; + return regExp.test(input); + }; + RegExpWrapper.matcher = function(regExp, input) { + regExp.lastIndex = 0; + return { + re: regExp, + input: input + }; + }; + return RegExpWrapper; + })(); + exports.RegExpWrapper = RegExpWrapper; + var RegExpMatcherWrapper = (function() { + function RegExpMatcherWrapper() {} + RegExpMatcherWrapper.next = function(matcher) { + return matcher.re.exec(matcher.input); + }; + return RegExpMatcherWrapper; + })(); + exports.RegExpMatcherWrapper = RegExpMatcherWrapper; + var FunctionWrapper = (function() { + function FunctionWrapper() {} + FunctionWrapper.apply = function(fn, posArgs) { + return fn.apply(null, posArgs); + }; + return FunctionWrapper; + })(); + exports.FunctionWrapper = FunctionWrapper; + function looseIdentical(a, b) { + return a === b || typeof a === "number" && typeof b === "number" && isNaN(a) && isNaN(b); + } + exports.looseIdentical = looseIdentical; + function getMapKey(value) { + return value; + } + exports.getMapKey = getMapKey; + function normalizeBlank(obj) { + return isBlank(obj) ? null : obj; + } + exports.normalizeBlank = normalizeBlank; + function normalizeBool(obj) { + return isBlank(obj) ? false : obj; + } + exports.normalizeBool = normalizeBool; + function isJsObject(o) { + return o !== null && (typeof o === "function" || typeof o === "object"); + } + exports.isJsObject = isJsObject; + function print(obj) { + console.log(obj); + } + exports.print = print; + var Json = (function() { + function Json() {} + Json.parse = function(s) { + return _global.JSON.parse(s); + }; + Json.stringify = function(data) { + return _global.JSON.stringify(data, null, 2); + }; + return Json; + })(); + exports.Json = Json; + var DateWrapper = (function() { + function DateWrapper() {} + DateWrapper.create = function(year, month, day, hour, minutes, seconds, milliseconds) { + if (month === void 0) { + month = 1; + } + if (day === void 0) { + day = 1; + } + if (hour === void 0) { + hour = 0; + } + if (minutes === void 0) { + minutes = 0; + } + if (seconds === void 0) { + seconds = 0; + } + if (milliseconds === void 0) { + milliseconds = 0; + } + return new exports.Date(year, month - 1, day, hour, minutes, seconds, milliseconds); + }; + DateWrapper.fromISOString = function(str) { + return new exports.Date(str); + }; + DateWrapper.fromMillis = function(ms) { + return new exports.Date(ms); + }; + DateWrapper.toMillis = function(date) { + return date.getTime(); + }; + DateWrapper.now = function() { + return new exports.Date(); + }; + DateWrapper.toJson = function(date) { + return date.toJSON(); + }; + return DateWrapper; + })(); + exports.DateWrapper = DateWrapper; + function setValueOnPath(global, path, value) { + var parts = path.split('.'); + var obj = global; + while (parts.length > 1) { + var name = parts.shift(); + if (obj.hasOwnProperty(name) && isPresent(obj[name])) { + obj = obj[name]; + } else { + obj = obj[name] = {}; + } + } + if (obj === undefined || obj === null) { + obj = {}; + } + obj[parts.shift()] = value; + } + exports.setValueOnPath = setValueOnPath; + var _symbolIterator = null; + function getSymbolIterator() { + if (isBlank(_symbolIterator)) { + if (isPresent(Symbol) && isPresent(Symbol.iterator)) { + _symbolIterator = Symbol.iterator; + } else { + var keys = Object.getOwnPropertyNames(Map.prototype); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (key !== 'entries' && key !== 'size' && Map.prototype[key] === Map.prototype['entries']) { + _symbolIterator = key; + } + } + } + } + return _symbolIterator; + } + exports.getSymbolIterator = getSymbolIterator; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/di/metadata", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var InjectMetadata = (function() { + function InjectMetadata(token) { + this.token = token; + } + InjectMetadata.prototype.toString = function() { + return "@Inject(" + lang_1.stringify(this.token) + ")"; + }; + InjectMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object])], InjectMetadata); + return InjectMetadata; + })(); + exports.InjectMetadata = InjectMetadata; + var OptionalMetadata = (function() { + function OptionalMetadata() {} + OptionalMetadata.prototype.toString = function() { + return "@Optional()"; + }; + OptionalMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [])], OptionalMetadata); + return OptionalMetadata; + })(); + exports.OptionalMetadata = OptionalMetadata; + var DependencyMetadata = (function() { + function DependencyMetadata() {} + Object.defineProperty(DependencyMetadata.prototype, "token", { + get: function() { + return null; + }, + enumerable: true, + configurable: true + }); + DependencyMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [])], DependencyMetadata); + return DependencyMetadata; + })(); + exports.DependencyMetadata = DependencyMetadata; + var InjectableMetadata = (function() { + function InjectableMetadata() {} + InjectableMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [])], InjectableMetadata); + return InjectableMetadata; + })(); + exports.InjectableMetadata = InjectableMetadata; + var SelfMetadata = (function() { + function SelfMetadata() {} + SelfMetadata.prototype.toString = function() { + return "@Self()"; + }; + SelfMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [])], SelfMetadata); + return SelfMetadata; + })(); + exports.SelfMetadata = SelfMetadata; + var SkipSelfMetadata = (function() { + function SkipSelfMetadata() {} + SkipSelfMetadata.prototype.toString = function() { + return "@SkipSelf()"; + }; + SkipSelfMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [])], SkipSelfMetadata); + return SkipSelfMetadata; + })(); + exports.SkipSelfMetadata = SkipSelfMetadata; + var HostMetadata = (function() { + function HostMetadata() {} + HostMetadata.prototype.toString = function() { + return "@Host()"; + }; + HostMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [])], HostMetadata); + return HostMetadata; + })(); + exports.HostMetadata = HostMetadata; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/util/decorators", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + function extractAnnotation(annotation) { + if (lang_1.isFunction(annotation) && annotation.hasOwnProperty('annotation')) { + annotation = annotation.annotation; + } + return annotation; + } + function applyParams(fnOrArray, key) { + if (fnOrArray === Object || fnOrArray === String || fnOrArray === Function || fnOrArray === Number || fnOrArray === Array) { + throw new Error("Can not use native " + lang_1.stringify(fnOrArray) + " as constructor"); + } + if (lang_1.isFunction(fnOrArray)) { + return fnOrArray; + } else if (fnOrArray instanceof Array) { + var annotations = fnOrArray; + var fn = fnOrArray[fnOrArray.length - 1]; + if (!lang_1.isFunction(fn)) { + throw new Error("Last position of Class method array must be Function in key " + key + " was '" + lang_1.stringify(fn) + "'"); + } + var annoLength = annotations.length - 1; + if (annoLength != fn.length) { + throw new Error("Number of annotations (" + annoLength + ") does not match number of arguments (" + fn.length + ") in the function: " + lang_1.stringify(fn)); + } + var paramsAnnotations = []; + for (var i = 0, + ii = annotations.length - 1; i < ii; i++) { + var paramAnnotations = []; + paramsAnnotations.push(paramAnnotations); + var annotation = annotations[i]; + if (annotation instanceof Array) { + for (var j = 0; j < annotation.length; j++) { + paramAnnotations.push(extractAnnotation(annotation[j])); + } + } else if (lang_1.isFunction(annotation)) { + paramAnnotations.push(extractAnnotation(annotation)); + } else { + paramAnnotations.push(annotation); + } + } + Reflect.defineMetadata('parameters', paramsAnnotations, fn); + return fn; + } else { + throw new Error("Only Function or Array is supported in Class definition for key '" + key + "' is '" + lang_1.stringify(fnOrArray) + "'"); + } + } + function Class(clsDef) { + var constructor = applyParams(clsDef.hasOwnProperty('constructor') ? clsDef.constructor : undefined, 'constructor'); + var proto = constructor.prototype; + if (clsDef.hasOwnProperty('extends')) { + if (lang_1.isFunction(clsDef.extends)) { + constructor.prototype = proto = Object.create(clsDef.extends.prototype); + } else { + throw new Error("Class definition 'extends' property must be a constructor function was: " + lang_1.stringify(clsDef.extends)); + } + } + for (var key in clsDef) { + if (key != 'extends' && key != 'prototype' && clsDef.hasOwnProperty(key)) { + proto[key] = applyParams(clsDef[key], key); + } + } + if (this && this.annotations instanceof Array) { + Reflect.defineMetadata('annotations', this.annotations, constructor); + } + return constructor; + } + exports.Class = Class; + var Reflect = lang_1.global.Reflect; + if (!(Reflect && Reflect.getMetadata)) { + throw 'reflect-metadata shim is required when using class decorators'; + } + function makeDecorator(annotationCls, chainFn) { + if (chainFn === void 0) { + chainFn = null; + } + function DecoratorFactory(objOrType) { + var annotationInstance = new annotationCls(objOrType); + if (this instanceof annotationCls) { + return annotationInstance; + } else { + var chainAnnotation = lang_1.isFunction(this) && this.annotations instanceof Array ? this.annotations : []; + chainAnnotation.push(annotationInstance); + var TypeDecorator = function TypeDecorator(cls) { + var annotations = Reflect.getOwnMetadata('annotations', cls); + annotations = annotations || []; + annotations.push(annotationInstance); + Reflect.defineMetadata('annotations', annotations, cls); + return cls; + }; + TypeDecorator.annotations = chainAnnotation; + TypeDecorator.Class = Class; + if (chainFn) + chainFn(TypeDecorator); + return TypeDecorator; + } + } + DecoratorFactory.prototype = Object.create(annotationCls.prototype); + return DecoratorFactory; + } + exports.makeDecorator = makeDecorator; + function makeParamDecorator(annotationCls) { + function ParamDecoratorFactory() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + var annotationInstance = Object.create(annotationCls.prototype); + annotationCls.apply(annotationInstance, args); + if (this instanceof annotationCls) { + return annotationInstance; + } else { + ParamDecorator.annotation = annotationInstance; + return ParamDecorator; + } + function ParamDecorator(cls, unusedKey, index) { + var parameters = Reflect.getMetadata('parameters', cls); + parameters = parameters || []; + while (parameters.length <= index) { + parameters.push(null); + } + parameters[index] = parameters[index] || []; + var annotationsForParam = parameters[index]; + annotationsForParam.push(annotationInstance); + Reflect.defineMetadata('parameters', parameters, cls); + return cls; + } + } + ParamDecoratorFactory.prototype = Object.create(annotationCls.prototype); + return ParamDecoratorFactory; + } + exports.makeParamDecorator = makeParamDecorator; + function makePropDecorator(decoratorCls) { + function PropDecoratorFactory() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + var decoratorInstance = Object.create(decoratorCls.prototype); + decoratorCls.apply(decoratorInstance, args); + if (this instanceof decoratorCls) { + return decoratorInstance; + } else { + return function PropDecorator(target, name) { + var meta = Reflect.getOwnMetadata('propMetadata', target.constructor); + meta = meta || {}; + meta[name] = meta[name] || []; + meta[name].unshift(decoratorInstance); + Reflect.defineMetadata('propMetadata', meta, target.constructor); + }; + } + } + PropDecoratorFactory.prototype = Object.create(decoratorCls.prototype); + return PropDecoratorFactory; + } + exports.makePropDecorator = makePropDecorator; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/di/forward_ref", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + function forwardRef(forwardRefFn) { + forwardRefFn.__forward_ref__ = forwardRef; + forwardRefFn.toString = function() { + return lang_1.stringify(this()); + }; + return forwardRefFn; + } + exports.forwardRef = forwardRef; + function resolveForwardRef(type) { + if (lang_1.isFunction(type) && type.hasOwnProperty('__forward_ref__') && type.__forward_ref__ === forwardRef) { + return type(); + } else { + return type; + } + } + exports.resolveForwardRef = resolveForwardRef; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/facade/collection", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + exports.Map = lang_1.global.Map; + exports.Set = lang_1.global.Set; + var createMapFromPairs = (function() { + try { + if (new exports.Map([[1, 2]]).size === 1) { + return function createMapFromPairs(pairs) { + return new exports.Map(pairs); + }; + } + } catch (e) {} + return function createMapAndPopulateFromPairs(pairs) { + var map = new exports.Map(); + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i]; + map.set(pair[0], pair[1]); + } + return map; + }; + })(); + var createMapFromMap = (function() { + try { + if (new exports.Map(new exports.Map())) { + return function createMapFromMap(m) { + return new exports.Map(m); + }; + } + } catch (e) {} + return function createMapAndPopulateFromMap(m) { + var map = new exports.Map(); + m.forEach(function(v, k) { + map.set(k, v); + }); + return map; + }; + })(); + var _clearValues = (function() { + if ((new exports.Map()).keys().next) { + return function _clearValues(m) { + var keyIterator = m.keys(); + var k; + while (!((k = keyIterator.next()).done)) { + m.set(k.value, null); + } + }; + } else { + return function _clearValuesWithForeEach(m) { + m.forEach(function(v, k) { + m.set(k, null); + }); + }; + } + })(); + var _arrayFromMap = (function() { + try { + if ((new exports.Map()).values().next) { + return function createArrayFromMap(m, getValues) { + return getValues ? Array.from(m.values()) : Array.from(m.keys()); + }; + } + } catch (e) {} + return function createArrayFromMapWithForeach(m, getValues) { + var res = ListWrapper.createFixedSize(m.size), + i = 0; + m.forEach(function(v, k) { + res[i] = getValues ? v : k; + i++; + }); + return res; + }; + })(); + var MapWrapper = (function() { + function MapWrapper() {} + MapWrapper.clone = function(m) { + return createMapFromMap(m); + }; + MapWrapper.createFromStringMap = function(stringMap) { + var result = new exports.Map(); + for (var prop in stringMap) { + result.set(prop, stringMap[prop]); + } + return result; + }; + MapWrapper.toStringMap = function(m) { + var r = {}; + m.forEach(function(v, k) { + return r[k] = v; + }); + return r; + }; + MapWrapper.createFromPairs = function(pairs) { + return createMapFromPairs(pairs); + }; + MapWrapper.clearValues = function(m) { + _clearValues(m); + }; + MapWrapper.iterable = function(m) { + return m; + }; + MapWrapper.keys = function(m) { + return _arrayFromMap(m, false); + }; + MapWrapper.values = function(m) { + return _arrayFromMap(m, true); + }; + return MapWrapper; + })(); + exports.MapWrapper = MapWrapper; + var StringMapWrapper = (function() { + function StringMapWrapper() {} + StringMapWrapper.create = function() { + return {}; + }; + StringMapWrapper.contains = function(map, key) { + return map.hasOwnProperty(key); + }; + StringMapWrapper.get = function(map, key) { + return map.hasOwnProperty(key) ? map[key] : undefined; + }; + StringMapWrapper.set = function(map, key, value) { + map[key] = value; + }; + StringMapWrapper.keys = function(map) { + return Object.keys(map); + }; + StringMapWrapper.isEmpty = function(map) { + for (var prop in map) { + return false; + } + return true; + }; + StringMapWrapper.delete = function(map, key) { + delete map[key]; + }; + StringMapWrapper.forEach = function(map, callback) { + for (var prop in map) { + if (map.hasOwnProperty(prop)) { + callback(map[prop], prop); + } + } + }; + StringMapWrapper.merge = function(m1, m2) { + var m = {}; + for (var attr in m1) { + if (m1.hasOwnProperty(attr)) { + m[attr] = m1[attr]; + } + } + for (var attr in m2) { + if (m2.hasOwnProperty(attr)) { + m[attr] = m2[attr]; + } + } + return m; + }; + StringMapWrapper.equals = function(m1, m2) { + var k1 = Object.keys(m1); + var k2 = Object.keys(m2); + if (k1.length != k2.length) { + return false; + } + var key; + for (var i = 0; i < k1.length; i++) { + key = k1[i]; + if (m1[key] !== m2[key]) { + return false; + } + } + return true; + }; + return StringMapWrapper; + })(); + exports.StringMapWrapper = StringMapWrapper; + var ListWrapper = (function() { + function ListWrapper() {} + ListWrapper.createFixedSize = function(size) { + return new Array(size); + }; + ListWrapper.createGrowableSize = function(size) { + return new Array(size); + }; + ListWrapper.clone = function(array) { + return array.slice(0); + }; + ListWrapper.forEachWithIndex = function(array, fn) { + for (var i = 0; i < array.length; i++) { + fn(array[i], i); + } + }; + ListWrapper.first = function(array) { + if (!array) + return null; + return array[0]; + }; + ListWrapper.last = function(array) { + if (!array || array.length == 0) + return null; + return array[array.length - 1]; + }; + ListWrapper.indexOf = function(array, value, startIndex) { + if (startIndex === void 0) { + startIndex = 0; + } + return array.indexOf(value, startIndex); + }; + ListWrapper.contains = function(list, el) { + return list.indexOf(el) !== -1; + }; + ListWrapper.reversed = function(array) { + var a = ListWrapper.clone(array); + return a.reverse(); + }; + ListWrapper.concat = function(a, b) { + return a.concat(b); + }; + ListWrapper.insert = function(list, index, value) { + list.splice(index, 0, value); + }; + ListWrapper.removeAt = function(list, index) { + var res = list[index]; + list.splice(index, 1); + return res; + }; + ListWrapper.removeAll = function(list, items) { + for (var i = 0; i < items.length; ++i) { + var index = list.indexOf(items[i]); + list.splice(index, 1); + } + }; + ListWrapper.remove = function(list, el) { + var index = list.indexOf(el); + if (index > -1) { + list.splice(index, 1); + return true; + } + return false; + }; + ListWrapper.clear = function(list) { + list.length = 0; + }; + ListWrapper.isEmpty = function(list) { + return list.length == 0; + }; + ListWrapper.fill = function(list, value, start, end) { + if (start === void 0) { + start = 0; + } + if (end === void 0) { + end = null; + } + list.fill(value, start, end === null ? list.length : end); + }; + ListWrapper.equals = function(a, b) { + if (a.length != b.length) + return false; + for (var i = 0; i < a.length; ++i) { + if (a[i] !== b[i]) + return false; + } + return true; + }; + ListWrapper.slice = function(l, from, to) { + if (from === void 0) { + from = 0; + } + if (to === void 0) { + to = null; + } + return l.slice(from, to === null ? undefined : to); + }; + ListWrapper.splice = function(l, from, length) { + return l.splice(from, length); + }; + ListWrapper.sort = function(l, compareFn) { + if (lang_1.isPresent(compareFn)) { + l.sort(compareFn); + } else { + l.sort(); + } + }; + ListWrapper.toString = function(l) { + return l.toString(); + }; + ListWrapper.toJSON = function(l) { + return JSON.stringify(l); + }; + ListWrapper.maximum = function(list, predicate) { + if (list.length == 0) { + return null; + } + var solution = null; + var maxValue = -Infinity; + for (var index = 0; index < list.length; index++) { + var candidate = list[index]; + if (lang_1.isBlank(candidate)) { + continue; + } + var candidateValue = predicate(candidate); + if (candidateValue > maxValue) { + solution = candidate; + maxValue = candidateValue; + } + } + return solution; + }; + return ListWrapper; + })(); + exports.ListWrapper = ListWrapper; + function isListLikeIterable(obj) { + if (!lang_1.isJsObject(obj)) + return false; + return lang_1.isArray(obj) || (!(obj instanceof exports.Map) && lang_1.getSymbolIterator() in obj); + } + exports.isListLikeIterable = isListLikeIterable; + function iterateListLike(obj, fn) { + if (lang_1.isArray(obj)) { + for (var i = 0; i < obj.length; i++) { + fn(obj[i]); + } + } else { + var iterator = obj[lang_1.getSymbolIterator()](); + var item; + while (!((item = iterator.next()).done)) { + fn(item.value); + } + } + } + exports.iterateListLike = iterateListLike; + var createSetFromList = (function() { + var test = new exports.Set([1, 2, 3]); + if (test.size === 3) { + return function createSetFromList(lst) { + return new exports.Set(lst); + }; + } else { + return function createSetAndPopulateFromList(lst) { + var res = new exports.Set(lst); + if (res.size !== lst.length) { + for (var i = 0; i < lst.length; i++) { + res.add(lst[i]); + } + } + return res; + }; + } + })(); + var SetWrapper = (function() { + function SetWrapper() {} + SetWrapper.createFromList = function(lst) { + return createSetFromList(lst); + }; + SetWrapper.has = function(s, key) { + return s.has(key); + }; + SetWrapper.delete = function(m, k) { + m.delete(k); + }; + return SetWrapper; + })(); + exports.SetWrapper = SetWrapper; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/facade/exception_handler", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var _ArrayLogger = (function() { + function _ArrayLogger() { + this.res = []; + } + _ArrayLogger.prototype.log = function(s) { + this.res.push(s); + }; + _ArrayLogger.prototype.logError = function(s) { + this.res.push(s); + }; + _ArrayLogger.prototype.logGroup = function(s) { + this.res.push(s); + }; + _ArrayLogger.prototype.logGroupEnd = function() {}; + ; + return _ArrayLogger; + })(); + var ExceptionHandler = (function() { + function ExceptionHandler(_logger, _rethrowException) { + if (_rethrowException === void 0) { + _rethrowException = true; + } + this._logger = _logger; + this._rethrowException = _rethrowException; + } + ExceptionHandler.exceptionToString = function(exception, stackTrace, reason) { + if (stackTrace === void 0) { + stackTrace = null; + } + if (reason === void 0) { + reason = null; + } + var l = new _ArrayLogger(); + var e = new ExceptionHandler(l, false); + e.call(exception, stackTrace, reason); + return l.res.join("\n"); + }; + ExceptionHandler.prototype.call = function(exception, stackTrace, reason) { + if (stackTrace === void 0) { + stackTrace = null; + } + if (reason === void 0) { + reason = null; + } + var originalException = this._findOriginalException(exception); + var originalStack = this._findOriginalStack(exception); + var context = this._findContext(exception); + this._logger.logGroup("EXCEPTION: " + this._extractMessage(exception)); + if (lang_1.isPresent(stackTrace) && lang_1.isBlank(originalStack)) { + this._logger.logError("STACKTRACE:"); + this._logger.logError(this._longStackTrace(stackTrace)); + } + if (lang_1.isPresent(reason)) { + this._logger.logError("REASON: " + reason); + } + if (lang_1.isPresent(originalException)) { + this._logger.logError("ORIGINAL EXCEPTION: " + this._extractMessage(originalException)); + } + if (lang_1.isPresent(originalStack)) { + this._logger.logError("ORIGINAL STACKTRACE:"); + this._logger.logError(this._longStackTrace(originalStack)); + } + if (lang_1.isPresent(context)) { + this._logger.logError("ERROR CONTEXT:"); + this._logger.logError(context); + } + this._logger.logGroupEnd(); + if (this._rethrowException) + throw exception; + }; + ExceptionHandler.prototype._extractMessage = function(exception) { + return exception instanceof exceptions_1.WrappedException ? exception.wrapperMessage : exception.toString(); + }; + ExceptionHandler.prototype._longStackTrace = function(stackTrace) { + return collection_1.isListLikeIterable(stackTrace) ? stackTrace.join("\n\n-----async gap-----\n") : stackTrace.toString(); + }; + ExceptionHandler.prototype._findContext = function(exception) { + try { + if (!(exception instanceof exceptions_1.WrappedException)) + return null; + return lang_1.isPresent(exception.context) ? exception.context : this._findContext(exception.originalException); + } catch (e) { + return null; + } + }; + ExceptionHandler.prototype._findOriginalException = function(exception) { + if (!(exception instanceof exceptions_1.WrappedException)) + return null; + var e = exception.originalException; + while (e instanceof exceptions_1.WrappedException && lang_1.isPresent(e.originalException)) { + e = e.originalException; + } + return e; + }; + ExceptionHandler.prototype._findOriginalStack = function(exception) { + if (!(exception instanceof exceptions_1.WrappedException)) + return null; + var e = exception; + var stack = exception.originalStack; + while (e instanceof exceptions_1.WrappedException && lang_1.isPresent(e.originalException)) { + e = e.originalException; + if (e instanceof exceptions_1.WrappedException && lang_1.isPresent(e.originalException)) { + stack = e.originalStack; + } + } + return stack; + }; + return ExceptionHandler; + })(); + exports.ExceptionHandler = ExceptionHandler; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/reflection/reflector", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var ReflectionInfo = (function() { + function ReflectionInfo(annotations, parameters, factory, interfaces, propMetadata) { + this.annotations = annotations; + this.parameters = parameters; + this.factory = factory; + this.interfaces = interfaces; + this.propMetadata = propMetadata; + } + return ReflectionInfo; + })(); + exports.ReflectionInfo = ReflectionInfo; + var Reflector = (function() { + function Reflector(reflectionCapabilities) { + this._injectableInfo = new collection_1.Map(); + this._getters = new collection_1.Map(); + this._setters = new collection_1.Map(); + this._methods = new collection_1.Map(); + this._usedKeys = null; + this.reflectionCapabilities = reflectionCapabilities; + } + Reflector.prototype.isReflectionEnabled = function() { + return this.reflectionCapabilities.isReflectionEnabled(); + }; + Reflector.prototype.trackUsage = function() { + this._usedKeys = new collection_1.Set(); + }; + Reflector.prototype.listUnusedKeys = function() { + var _this = this; + if (this._usedKeys == null) { + throw new exceptions_1.BaseException('Usage tracking is disabled'); + } + var allTypes = collection_1.MapWrapper.keys(this._injectableInfo); + return allTypes.filter(function(key) { + return !collection_1.SetWrapper.has(_this._usedKeys, key); + }); + }; + Reflector.prototype.registerFunction = function(func, funcInfo) { + this._injectableInfo.set(func, funcInfo); + }; + Reflector.prototype.registerType = function(type, typeInfo) { + this._injectableInfo.set(type, typeInfo); + }; + Reflector.prototype.registerGetters = function(getters) { + _mergeMaps(this._getters, getters); + }; + Reflector.prototype.registerSetters = function(setters) { + _mergeMaps(this._setters, setters); + }; + Reflector.prototype.registerMethods = function(methods) { + _mergeMaps(this._methods, methods); + }; + Reflector.prototype.factory = function(type) { + if (this._containsReflectionInfo(type)) { + var res = this._getReflectionInfo(type).factory; + return lang_1.isPresent(res) ? res : null; + } else { + return this.reflectionCapabilities.factory(type); + } + }; + Reflector.prototype.parameters = function(typeOrFunc) { + if (this._injectableInfo.has(typeOrFunc)) { + var res = this._getReflectionInfo(typeOrFunc).parameters; + return lang_1.isPresent(res) ? res : []; + } else { + return this.reflectionCapabilities.parameters(typeOrFunc); + } + }; + Reflector.prototype.annotations = function(typeOrFunc) { + if (this._injectableInfo.has(typeOrFunc)) { + var res = this._getReflectionInfo(typeOrFunc).annotations; + return lang_1.isPresent(res) ? res : []; + } else { + return this.reflectionCapabilities.annotations(typeOrFunc); + } + }; + Reflector.prototype.propMetadata = function(typeOrFunc) { + if (this._injectableInfo.has(typeOrFunc)) { + var res = this._getReflectionInfo(typeOrFunc).propMetadata; + return lang_1.isPresent(res) ? res : {}; + } else { + return this.reflectionCapabilities.propMetadata(typeOrFunc); + } + }; + Reflector.prototype.interfaces = function(type) { + if (this._injectableInfo.has(type)) { + var res = this._getReflectionInfo(type).interfaces; + return lang_1.isPresent(res) ? res : []; + } else { + return this.reflectionCapabilities.interfaces(type); + } + }; + Reflector.prototype.getter = function(name) { + if (this._getters.has(name)) { + return this._getters.get(name); + } else { + return this.reflectionCapabilities.getter(name); + } + }; + Reflector.prototype.setter = function(name) { + if (this._setters.has(name)) { + return this._setters.get(name); + } else { + return this.reflectionCapabilities.setter(name); + } + }; + Reflector.prototype.method = function(name) { + if (this._methods.has(name)) { + return this._methods.get(name); + } else { + return this.reflectionCapabilities.method(name); + } + }; + Reflector.prototype._getReflectionInfo = function(typeOrFunc) { + if (lang_1.isPresent(this._usedKeys)) { + this._usedKeys.add(typeOrFunc); + } + return this._injectableInfo.get(typeOrFunc); + }; + Reflector.prototype._containsReflectionInfo = function(typeOrFunc) { + return this._injectableInfo.has(typeOrFunc); + }; + Reflector.prototype.importUri = function(type) { + return this.reflectionCapabilities.importUri(type); + }; + return Reflector; + })(); + exports.Reflector = Reflector; + function _mergeMaps(target, config) { + collection_1.StringMapWrapper.forEach(config, function(v, k) { + return target.set(k, v); + }); + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/reflection/reflection_capabilities", ["angular2/src/facade/lang", "angular2/src/facade/exceptions"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var ReflectionCapabilities = (function() { + function ReflectionCapabilities(reflect) { + this._reflect = lang_1.isPresent(reflect) ? reflect : lang_1.global.Reflect; + } + ReflectionCapabilities.prototype.isReflectionEnabled = function() { + return true; + }; + ReflectionCapabilities.prototype.factory = function(t) { + switch (t.length) { + case 0: + return function() { + return new t(); + }; + case 1: + return function(a1) { + return new t(a1); + }; + case 2: + return function(a1, a2) { + return new t(a1, a2); + }; + case 3: + return function(a1, a2, a3) { + return new t(a1, a2, a3); + }; + case 4: + return function(a1, a2, a3, a4) { + return new t(a1, a2, a3, a4); + }; + case 5: + return function(a1, a2, a3, a4, a5) { + return new t(a1, a2, a3, a4, a5); + }; + case 6: + return function(a1, a2, a3, a4, a5, a6) { + return new t(a1, a2, a3, a4, a5, a6); + }; + case 7: + return function(a1, a2, a3, a4, a5, a6, a7) { + return new t(a1, a2, a3, a4, a5, a6, a7); + }; + case 8: + return function(a1, a2, a3, a4, a5, a6, a7, a8) { + return new t(a1, a2, a3, a4, a5, a6, a7, a8); + }; + case 9: + return function(a1, a2, a3, a4, a5, a6, a7, a8, a9) { + return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9); + }; + case 10: + return function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { + return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); + }; + case 11: + return function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) { + return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11); + }; + case 12: + return function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) { + return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12); + }; + case 13: + return function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13) { + return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13); + }; + case 14: + return function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) { + return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); + }; + case 15: + return function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) { + return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15); + }; + case 16: + return function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16) { + return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16); + }; + case 17: + return function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17) { + return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17); + }; + case 18: + return function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18) { + return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18); + }; + case 19: + return function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19) { + return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19); + }; + case 20: + return function(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) { + return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + }; + } + ; + throw new Error("Cannot create a factory for '" + lang_1.stringify(t) + "' because its constructor has more than 20 arguments"); + }; + ReflectionCapabilities.prototype._zipTypesAndAnnotaions = function(paramTypes, paramAnnotations) { + var result; + if (typeof paramTypes === 'undefined') { + result = new Array(paramAnnotations.length); + } else { + result = new Array(paramTypes.length); + } + for (var i = 0; i < result.length; i++) { + if (typeof paramTypes === 'undefined') { + result[i] = []; + } else if (paramTypes[i] != Object) { + result[i] = [paramTypes[i]]; + } else { + result[i] = []; + } + if (lang_1.isPresent(paramAnnotations) && lang_1.isPresent(paramAnnotations[i])) { + result[i] = result[i].concat(paramAnnotations[i]); + } + } + return result; + }; + ReflectionCapabilities.prototype.parameters = function(typeOrFunc) { + if (lang_1.isPresent(typeOrFunc.parameters)) { + return typeOrFunc.parameters; + } + if (lang_1.isPresent(this._reflect) && lang_1.isPresent(this._reflect.getMetadata)) { + var paramAnnotations = this._reflect.getMetadata('parameters', typeOrFunc); + var paramTypes = this._reflect.getMetadata('design:paramtypes', typeOrFunc); + if (lang_1.isPresent(paramTypes) || lang_1.isPresent(paramAnnotations)) { + return this._zipTypesAndAnnotaions(paramTypes, paramAnnotations); + } + } + var parameters = new Array(typeOrFunc.length); + parameters.fill(undefined); + return parameters; + }; + ReflectionCapabilities.prototype.annotations = function(typeOrFunc) { + if (lang_1.isPresent(typeOrFunc.annotations)) { + var annotations = typeOrFunc.annotations; + if (lang_1.isFunction(annotations) && annotations.annotations) { + annotations = annotations.annotations; + } + return annotations; + } + if (lang_1.isPresent(this._reflect) && lang_1.isPresent(this._reflect.getMetadata)) { + var annotations = this._reflect.getMetadata('annotations', typeOrFunc); + if (lang_1.isPresent(annotations)) + return annotations; + } + return []; + }; + ReflectionCapabilities.prototype.propMetadata = function(typeOrFunc) { + if (lang_1.isPresent(typeOrFunc.propMetadata)) { + var propMetadata = typeOrFunc.propMetadata; + if (lang_1.isFunction(propMetadata) && propMetadata.propMetadata) { + propMetadata = propMetadata.propMetadata; + } + return propMetadata; + } + if (lang_1.isPresent(this._reflect) && lang_1.isPresent(this._reflect.getMetadata)) { + var propMetadata = this._reflect.getMetadata('propMetadata', typeOrFunc); + if (lang_1.isPresent(propMetadata)) + return propMetadata; + } + return {}; + }; + ReflectionCapabilities.prototype.interfaces = function(type) { + throw new exceptions_1.BaseException("JavaScript does not support interfaces"); + }; + ReflectionCapabilities.prototype.getter = function(name) { + return new Function('o', 'return o.' + name + ';'); + }; + ReflectionCapabilities.prototype.setter = function(name) { + return new Function('o', 'v', 'return o.' + name + ' = v;'); + }; + ReflectionCapabilities.prototype.method = function(name) { + var functionBody = "if (!o." + name + ") throw new Error('\"" + name + "\" is undefined');\n return o." + name + ".apply(o, args);"; + return new Function('o', 'args', functionBody); + }; + ReflectionCapabilities.prototype.importUri = function(type) { + return './'; + }; + return ReflectionCapabilities; + })(); + exports.ReflectionCapabilities = ReflectionCapabilities; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/di/type_literal", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var TypeLiteral = (function() { + function TypeLiteral() {} + Object.defineProperty(TypeLiteral.prototype, "type", { + get: function() { + throw new Error("Type literals are only supported in Dart"); + }, + enumerable: true, + configurable: true + }); + return TypeLiteral; + })(); + exports.TypeLiteral = TypeLiteral; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/di/exceptions", ["angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/facade/exceptions"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + function findFirstClosedCycle(keys) { + var res = []; + for (var i = 0; i < keys.length; ++i) { + if (collection_1.ListWrapper.contains(res, keys[i])) { + res.push(keys[i]); + return res; + } else { + res.push(keys[i]); + } + } + return res; + } + function constructResolvingPath(keys) { + if (keys.length > 1) { + var reversed = findFirstClosedCycle(collection_1.ListWrapper.reversed(keys)); + var tokenStrs = reversed.map(function(k) { + return lang_1.stringify(k.token); + }); + return " (" + tokenStrs.join(' -> ') + ")"; + } else { + return ""; + } + } + var AbstractProviderError = (function(_super) { + __extends(AbstractProviderError, _super); + function AbstractProviderError(injector, key, constructResolvingMessage) { + _super.call(this, "DI Exception"); + this.keys = [key]; + this.injectors = [injector]; + this.constructResolvingMessage = constructResolvingMessage; + this.message = this.constructResolvingMessage(this.keys); + } + AbstractProviderError.prototype.addKey = function(injector, key) { + this.injectors.push(injector); + this.keys.push(key); + this.message = this.constructResolvingMessage(this.keys); + }; + Object.defineProperty(AbstractProviderError.prototype, "context", { + get: function() { + return this.injectors[this.injectors.length - 1].debugContext(); + }, + enumerable: true, + configurable: true + }); + return AbstractProviderError; + })(exceptions_1.BaseException); + exports.AbstractProviderError = AbstractProviderError; + var NoProviderError = (function(_super) { + __extends(NoProviderError, _super); + function NoProviderError(injector, key) { + _super.call(this, injector, key, function(keys) { + var first = lang_1.stringify(collection_1.ListWrapper.first(keys).token); + return "No provider for " + first + "!" + constructResolvingPath(keys); + }); + } + return NoProviderError; + })(AbstractProviderError); + exports.NoProviderError = NoProviderError; + var CyclicDependencyError = (function(_super) { + __extends(CyclicDependencyError, _super); + function CyclicDependencyError(injector, key) { + _super.call(this, injector, key, function(keys) { + return "Cannot instantiate cyclic dependency!" + constructResolvingPath(keys); + }); + } + return CyclicDependencyError; + })(AbstractProviderError); + exports.CyclicDependencyError = CyclicDependencyError; + var InstantiationError = (function(_super) { + __extends(InstantiationError, _super); + function InstantiationError(injector, originalException, originalStack, key) { + _super.call(this, "DI Exception", originalException, originalStack, null); + this.keys = [key]; + this.injectors = [injector]; + } + InstantiationError.prototype.addKey = function(injector, key) { + this.injectors.push(injector); + this.keys.push(key); + }; + Object.defineProperty(InstantiationError.prototype, "wrapperMessage", { + get: function() { + var first = lang_1.stringify(collection_1.ListWrapper.first(this.keys).token); + return "Error during instantiation of " + first + "!" + constructResolvingPath(this.keys) + "."; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(InstantiationError.prototype, "causeKey", { + get: function() { + return this.keys[0]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(InstantiationError.prototype, "context", { + get: function() { + return this.injectors[this.injectors.length - 1].debugContext(); + }, + enumerable: true, + configurable: true + }); + return InstantiationError; + })(exceptions_1.WrappedException); + exports.InstantiationError = InstantiationError; + var InvalidProviderError = (function(_super) { + __extends(InvalidProviderError, _super); + function InvalidProviderError(provider) { + _super.call(this, "Invalid provider - only instances of Provider and Type are allowed, got: " + provider.toString()); + } + return InvalidProviderError; + })(exceptions_1.BaseException); + exports.InvalidProviderError = InvalidProviderError; + var NoAnnotationError = (function(_super) { + __extends(NoAnnotationError, _super); + function NoAnnotationError(typeOrFunc, params) { + _super.call(this, NoAnnotationError._genMessage(typeOrFunc, params)); + } + NoAnnotationError._genMessage = function(typeOrFunc, params) { + var signature = []; + for (var i = 0, + ii = params.length; i < ii; i++) { + var parameter = params[i]; + if (lang_1.isBlank(parameter) || parameter.length == 0) { + signature.push('?'); + } else { + signature.push(parameter.map(lang_1.stringify).join(' ')); + } + } + return "Cannot resolve all parameters for " + lang_1.stringify(typeOrFunc) + "(" + signature.join(', ') + "). " + 'Make sure they all have valid type or annotations.'; + }; + return NoAnnotationError; + })(exceptions_1.BaseException); + exports.NoAnnotationError = NoAnnotationError; + var OutOfBoundsError = (function(_super) { + __extends(OutOfBoundsError, _super); + function OutOfBoundsError(index) { + _super.call(this, "Index " + index + " is out-of-bounds."); + } + return OutOfBoundsError; + })(exceptions_1.BaseException); + exports.OutOfBoundsError = OutOfBoundsError; + var MixingMultiProvidersWithRegularProvidersError = (function(_super) { + __extends(MixingMultiProvidersWithRegularProvidersError, _super); + function MixingMultiProvidersWithRegularProvidersError(provider1, provider2) { + _super.call(this, "Cannot mix multi providers and regular providers, got: " + provider1.toString() + " " + provider2.toString()); + } + return MixingMultiProvidersWithRegularProvidersError; + })(exceptions_1.BaseException); + exports.MixingMultiProvidersWithRegularProvidersError = MixingMultiProvidersWithRegularProvidersError; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/di/opaque_token", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var OpaqueToken = (function() { + function OpaqueToken(_desc) { + this._desc = _desc; + } + OpaqueToken.prototype.toString = function() { + return "Token " + this._desc; + }; + OpaqueToken = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [String])], OpaqueToken); + return OpaqueToken; + })(); + exports.OpaqueToken = OpaqueToken; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/animate/css_animation_options", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var CssAnimationOptions = (function() { + function CssAnimationOptions() { + this.classesToAdd = []; + this.classesToRemove = []; + this.animationClasses = []; + } + return CssAnimationOptions; + })(); + exports.CssAnimationOptions = CssAnimationOptions; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/facade/math", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + exports.Math = lang_1.global.Math; + exports.NaN = typeof exports.NaN; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/dom/util", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var CAMEL_CASE_REGEXP = /([A-Z])/g; + var DASH_CASE_REGEXP = /-([a-z])/g; + function camelCaseToDashCase(input) { + return lang_1.StringWrapper.replaceAllMapped(input, CAMEL_CASE_REGEXP, function(m) { + return '-' + m[1].toLowerCase(); + }); + } + exports.camelCaseToDashCase = camelCaseToDashCase; + function dashCaseToCamelCase(input) { + return lang_1.StringWrapper.replaceAllMapped(input, DASH_CASE_REGEXP, function(m) { + return m[1].toUpperCase(); + }); + } + exports.dashCaseToCamelCase = dashCaseToCamelCase; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/animate/browser_details", ["angular2/src/core/di", "angular2/src/facade/math", "angular2/src/platform/dom/dom_adapter"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var di_1 = require("angular2/src/core/di"); + var math_1 = require("angular2/src/facade/math"); + var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); + var BrowserDetails = (function() { + function BrowserDetails() { + this.elapsedTimeIncludesDelay = false; + this.doesElapsedTimeIncludesDelay(); + } + BrowserDetails.prototype.doesElapsedTimeIncludesDelay = function() { + var _this = this; + var div = dom_adapter_1.DOM.createElement('div'); + dom_adapter_1.DOM.setAttribute(div, 'style', "position: absolute; top: -9999px; left: -9999px; width: 1px;\n height: 1px; transition: all 1ms linear 1ms;"); + this.raf(function(timestamp) { + dom_adapter_1.DOM.on(div, 'transitionend', function(event) { + var elapsed = math_1.Math.round(event.elapsedTime * 1000); + _this.elapsedTimeIncludesDelay = elapsed == 2; + dom_adapter_1.DOM.remove(div); + }); + dom_adapter_1.DOM.setStyle(div, 'width', '2px'); + }, 2); + }; + BrowserDetails.prototype.raf = function(callback, frames) { + if (frames === void 0) { + frames = 1; + } + var queue = new RafQueue(callback, frames); + return function() { + return queue.cancel(); + }; + }; + BrowserDetails = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], BrowserDetails); + return BrowserDetails; + })(); + exports.BrowserDetails = BrowserDetails; + var RafQueue = (function() { + function RafQueue(callback, frames) { + this.callback = callback; + this.frames = frames; + this._raf(); + } + RafQueue.prototype._raf = function() { + var _this = this; + this.currentFrameId = dom_adapter_1.DOM.requestAnimationFrame(function(timestamp) { + return _this._nextFrame(timestamp); + }); + }; + RafQueue.prototype._nextFrame = function(timestamp) { + this.frames--; + if (this.frames > 0) { + this._raf(); + } else { + this.callback(timestamp); + } + }; + RafQueue.prototype.cancel = function() { + dom_adapter_1.DOM.cancelAnimationFrame(this.currentFrameId); + this.currentFrameId = null; + }; + return RafQueue; + })(); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/dom/dom_tokens", ["angular2/src/core/di", "angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var di_1 = require("angular2/src/core/di"); + var lang_1 = require("angular2/src/facade/lang"); + exports.DOCUMENT = lang_1.CONST_EXPR(new di_1.OpaqueToken('DocumentToken')); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/profile/wtf_impl", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var trace; + var events; + function detectWTF() { + var wtf = lang_1.global['wtf']; + if (wtf) { + trace = wtf['trace']; + if (trace) { + events = trace['events']; + return true; + } + } + return false; + } + exports.detectWTF = detectWTF; + function createScope(signature, flags) { + if (flags === void 0) { + flags = null; + } + return events.createScope(signature, flags); + } + exports.createScope = createScope; + function leave(scope, returnValue) { + trace.leaveScope(scope, returnValue); + return returnValue; + } + exports.leave = leave; + function startTimeRange(rangeType, action) { + return trace.beginTimeRange(rangeType, action); + } + exports.startTimeRange = startTimeRange; + function endTimeRange(range) { + trace.endTimeRange(range); + } + exports.endTimeRange = endTimeRange; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/metadata/di", ["angular2/src/facade/lang", "angular2/src/core/di", "angular2/src/core/di/metadata"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var di_1 = require("angular2/src/core/di"); + var metadata_1 = require("angular2/src/core/di/metadata"); + var AttributeMetadata = (function(_super) { + __extends(AttributeMetadata, _super); + function AttributeMetadata(attributeName) { + _super.call(this); + this.attributeName = attributeName; + } + Object.defineProperty(AttributeMetadata.prototype, "token", { + get: function() { + return this; + }, + enumerable: true, + configurable: true + }); + AttributeMetadata.prototype.toString = function() { + return "@Attribute(" + lang_1.stringify(this.attributeName) + ")"; + }; + AttributeMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [String])], AttributeMetadata); + return AttributeMetadata; + })(metadata_1.DependencyMetadata); + exports.AttributeMetadata = AttributeMetadata; + var QueryMetadata = (function(_super) { + __extends(QueryMetadata, _super); + function QueryMetadata(_selector, _a) { + var _b = _a === void 0 ? {} : _a, + _c = _b.descendants, + descendants = _c === void 0 ? false : _c, + _d = _b.first, + first = _d === void 0 ? false : _d; + _super.call(this); + this._selector = _selector; + this.descendants = descendants; + this.first = first; + } + Object.defineProperty(QueryMetadata.prototype, "isViewQuery", { + get: function() { + return false; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(QueryMetadata.prototype, "selector", { + get: function() { + return di_1.resolveForwardRef(this._selector); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(QueryMetadata.prototype, "isVarBindingQuery", { + get: function() { + return lang_1.isString(this.selector); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(QueryMetadata.prototype, "varBindings", { + get: function() { + return this.selector.split(','); + }, + enumerable: true, + configurable: true + }); + QueryMetadata.prototype.toString = function() { + return "@Query(" + lang_1.stringify(this.selector) + ")"; + }; + QueryMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object, Object])], QueryMetadata); + return QueryMetadata; + })(metadata_1.DependencyMetadata); + exports.QueryMetadata = QueryMetadata; + var ContentChildrenMetadata = (function(_super) { + __extends(ContentChildrenMetadata, _super); + function ContentChildrenMetadata(_selector, _a) { + var _b = (_a === void 0 ? {} : _a).descendants, + descendants = _b === void 0 ? false : _b; + _super.call(this, _selector, {descendants: descendants}); + } + ContentChildrenMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object, Object])], ContentChildrenMetadata); + return ContentChildrenMetadata; + })(QueryMetadata); + exports.ContentChildrenMetadata = ContentChildrenMetadata; + var ContentChildMetadata = (function(_super) { + __extends(ContentChildMetadata, _super); + function ContentChildMetadata(_selector) { + _super.call(this, _selector, { + descendants: true, + first: true + }); + } + ContentChildMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object])], ContentChildMetadata); + return ContentChildMetadata; + })(QueryMetadata); + exports.ContentChildMetadata = ContentChildMetadata; + var ViewQueryMetadata = (function(_super) { + __extends(ViewQueryMetadata, _super); + function ViewQueryMetadata(_selector, _a) { + var _b = _a === void 0 ? {} : _a, + _c = _b.descendants, + descendants = _c === void 0 ? false : _c, + _d = _b.first, + first = _d === void 0 ? false : _d; + _super.call(this, _selector, { + descendants: descendants, + first: first + }); + } + Object.defineProperty(ViewQueryMetadata.prototype, "isViewQuery", { + get: function() { + return true; + }, + enumerable: true, + configurable: true + }); + ViewQueryMetadata.prototype.toString = function() { + return "@ViewQuery(" + lang_1.stringify(this.selector) + ")"; + }; + ViewQueryMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object, Object])], ViewQueryMetadata); + return ViewQueryMetadata; + })(QueryMetadata); + exports.ViewQueryMetadata = ViewQueryMetadata; + var ViewChildrenMetadata = (function(_super) { + __extends(ViewChildrenMetadata, _super); + function ViewChildrenMetadata(_selector) { + _super.call(this, _selector, {descendants: true}); + } + ViewChildrenMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object])], ViewChildrenMetadata); + return ViewChildrenMetadata; + })(ViewQueryMetadata); + exports.ViewChildrenMetadata = ViewChildrenMetadata; + var ViewChildMetadata = (function(_super) { + __extends(ViewChildMetadata, _super); + function ViewChildMetadata(_selector) { + _super.call(this, _selector, { + descendants: true, + first: true + }); + } + ViewChildMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object])], ViewChildMetadata); + return ViewChildMetadata; + })(ViewQueryMetadata); + exports.ViewChildMetadata = ViewChildMetadata; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/differs/iterable_differs", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/core/di"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var di_1 = require("angular2/src/core/di"); + var IterableDiffers = (function() { + function IterableDiffers(factories) { + this.factories = factories; + } + IterableDiffers.create = function(factories, parent) { + if (lang_1.isPresent(parent)) { + var copied = collection_1.ListWrapper.clone(parent.factories); + factories = factories.concat(copied); + return new IterableDiffers(factories); + } else { + return new IterableDiffers(factories); + } + }; + IterableDiffers.extend = function(factories) { + return new di_1.Provider(IterableDiffers, { + useFactory: function(parent) { + if (lang_1.isBlank(parent)) { + throw new exceptions_1.BaseException('Cannot extend IterableDiffers without a parent injector'); + } + return IterableDiffers.create(factories, parent); + }, + deps: [[IterableDiffers, new di_1.SkipSelfMetadata(), new di_1.OptionalMetadata()]] + }); + }; + IterableDiffers.prototype.find = function(iterable) { + var factory = this.factories.find(function(f) { + return f.supports(iterable); + }); + if (lang_1.isPresent(factory)) { + return factory; + } else { + throw new exceptions_1.BaseException("Cannot find a differ supporting object '" + iterable + "'"); + } + }; + IterableDiffers = __decorate([di_1.Injectable(), lang_1.CONST(), __metadata('design:paramtypes', [Array])], IterableDiffers); + return IterableDiffers; + })(); + exports.IterableDiffers = IterableDiffers; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/differs/default_iterable_differ", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var lang_2 = require("angular2/src/facade/lang"); + var DefaultIterableDifferFactory = (function() { + function DefaultIterableDifferFactory() {} + DefaultIterableDifferFactory.prototype.supports = function(obj) { + return collection_1.isListLikeIterable(obj); + }; + DefaultIterableDifferFactory.prototype.create = function(cdRef) { + return new DefaultIterableDiffer(); + }; + DefaultIterableDifferFactory = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [])], DefaultIterableDifferFactory); + return DefaultIterableDifferFactory; + })(); + exports.DefaultIterableDifferFactory = DefaultIterableDifferFactory; + var DefaultIterableDiffer = (function() { + function DefaultIterableDiffer() { + this._collection = null; + this._length = null; + this._linkedRecords = null; + this._unlinkedRecords = null; + this._previousItHead = null; + this._itHead = null; + this._itTail = null; + this._additionsHead = null; + this._additionsTail = null; + this._movesHead = null; + this._movesTail = null; + this._removalsHead = null; + this._removalsTail = null; + } + Object.defineProperty(DefaultIterableDiffer.prototype, "collection", { + get: function() { + return this._collection; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DefaultIterableDiffer.prototype, "length", { + get: function() { + return this._length; + }, + enumerable: true, + configurable: true + }); + DefaultIterableDiffer.prototype.forEachItem = function(fn) { + var record; + for (record = this._itHead; record !== null; record = record._next) { + fn(record); + } + }; + DefaultIterableDiffer.prototype.forEachPreviousItem = function(fn) { + var record; + for (record = this._previousItHead; record !== null; record = record._nextPrevious) { + fn(record); + } + }; + DefaultIterableDiffer.prototype.forEachAddedItem = function(fn) { + var record; + for (record = this._additionsHead; record !== null; record = record._nextAdded) { + fn(record); + } + }; + DefaultIterableDiffer.prototype.forEachMovedItem = function(fn) { + var record; + for (record = this._movesHead; record !== null; record = record._nextMoved) { + fn(record); + } + }; + DefaultIterableDiffer.prototype.forEachRemovedItem = function(fn) { + var record; + for (record = this._removalsHead; record !== null; record = record._nextRemoved) { + fn(record); + } + }; + DefaultIterableDiffer.prototype.diff = function(collection) { + if (lang_2.isBlank(collection)) + collection = []; + if (!collection_1.isListLikeIterable(collection)) { + throw new exceptions_1.BaseException("Error trying to diff '" + collection + "'"); + } + if (this.check(collection)) { + return this; + } else { + return null; + } + }; + DefaultIterableDiffer.prototype.onDestroy = function() {}; + DefaultIterableDiffer.prototype.check = function(collection) { + var _this = this; + this._reset(); + var record = this._itHead; + var mayBeDirty = false; + var index; + var item; + if (lang_2.isArray(collection)) { + var list = collection; + this._length = collection.length; + for (index = 0; index < this._length; index++) { + item = list[index]; + if (record === null || !lang_2.looseIdentical(record.item, item)) { + record = this._mismatch(record, item, index); + mayBeDirty = true; + } else if (mayBeDirty) { + record = this._verifyReinsertion(record, item, index); + } + record = record._next; + } + } else { + index = 0; + collection_1.iterateListLike(collection, function(item) { + if (record === null || !lang_2.looseIdentical(record.item, item)) { + record = _this._mismatch(record, item, index); + mayBeDirty = true; + } else if (mayBeDirty) { + record = _this._verifyReinsertion(record, item, index); + } + record = record._next; + index++; + }); + this._length = index; + } + this._truncate(record); + this._collection = collection; + return this.isDirty; + }; + Object.defineProperty(DefaultIterableDiffer.prototype, "isDirty", { + get: function() { + return this._additionsHead !== null || this._movesHead !== null || this._removalsHead !== null; + }, + enumerable: true, + configurable: true + }); + DefaultIterableDiffer.prototype._reset = function() { + if (this.isDirty) { + var record; + var nextRecord; + for (record = this._previousItHead = this._itHead; record !== null; record = record._next) { + record._nextPrevious = record._next; + } + for (record = this._additionsHead; record !== null; record = record._nextAdded) { + record.previousIndex = record.currentIndex; + } + this._additionsHead = this._additionsTail = null; + for (record = this._movesHead; record !== null; record = nextRecord) { + record.previousIndex = record.currentIndex; + nextRecord = record._nextMoved; + } + this._movesHead = this._movesTail = null; + this._removalsHead = this._removalsTail = null; + } + }; + DefaultIterableDiffer.prototype._mismatch = function(record, item, index) { + var previousRecord; + if (record === null) { + previousRecord = this._itTail; + } else { + previousRecord = record._prev; + this._remove(record); + } + record = this._linkedRecords === null ? null : this._linkedRecords.get(item, index); + if (record !== null) { + this._moveAfter(record, previousRecord, index); + } else { + record = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(item); + if (record !== null) { + this._reinsertAfter(record, previousRecord, index); + } else { + record = this._addAfter(new CollectionChangeRecord(item), previousRecord, index); + } + } + return record; + }; + DefaultIterableDiffer.prototype._verifyReinsertion = function(record, item, index) { + var reinsertRecord = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(item); + if (reinsertRecord !== null) { + record = this._reinsertAfter(reinsertRecord, record._prev, index); + } else if (record.currentIndex != index) { + record.currentIndex = index; + this._addToMoves(record, index); + } + return record; + }; + DefaultIterableDiffer.prototype._truncate = function(record) { + while (record !== null) { + var nextRecord = record._next; + this._addToRemovals(this._unlink(record)); + record = nextRecord; + } + if (this._unlinkedRecords !== null) { + this._unlinkedRecords.clear(); + } + if (this._additionsTail !== null) { + this._additionsTail._nextAdded = null; + } + if (this._movesTail !== null) { + this._movesTail._nextMoved = null; + } + if (this._itTail !== null) { + this._itTail._next = null; + } + if (this._removalsTail !== null) { + this._removalsTail._nextRemoved = null; + } + }; + DefaultIterableDiffer.prototype._reinsertAfter = function(record, prevRecord, index) { + if (this._unlinkedRecords !== null) { + this._unlinkedRecords.remove(record); + } + var prev = record._prevRemoved; + var next = record._nextRemoved; + if (prev === null) { + this._removalsHead = next; + } else { + prev._nextRemoved = next; + } + if (next === null) { + this._removalsTail = prev; + } else { + next._prevRemoved = prev; + } + this._insertAfter(record, prevRecord, index); + this._addToMoves(record, index); + return record; + }; + DefaultIterableDiffer.prototype._moveAfter = function(record, prevRecord, index) { + this._unlink(record); + this._insertAfter(record, prevRecord, index); + this._addToMoves(record, index); + return record; + }; + DefaultIterableDiffer.prototype._addAfter = function(record, prevRecord, index) { + this._insertAfter(record, prevRecord, index); + if (this._additionsTail === null) { + this._additionsTail = this._additionsHead = record; + } else { + this._additionsTail = this._additionsTail._nextAdded = record; + } + return record; + }; + DefaultIterableDiffer.prototype._insertAfter = function(record, prevRecord, index) { + var next = prevRecord === null ? this._itHead : prevRecord._next; + record._next = next; + record._prev = prevRecord; + if (next === null) { + this._itTail = record; + } else { + next._prev = record; + } + if (prevRecord === null) { + this._itHead = record; + } else { + prevRecord._next = record; + } + if (this._linkedRecords === null) { + this._linkedRecords = new _DuplicateMap(); + } + this._linkedRecords.put(record); + record.currentIndex = index; + return record; + }; + DefaultIterableDiffer.prototype._remove = function(record) { + return this._addToRemovals(this._unlink(record)); + }; + DefaultIterableDiffer.prototype._unlink = function(record) { + if (this._linkedRecords !== null) { + this._linkedRecords.remove(record); + } + var prev = record._prev; + var next = record._next; + if (prev === null) { + this._itHead = next; + } else { + prev._next = next; + } + if (next === null) { + this._itTail = prev; + } else { + next._prev = prev; + } + return record; + }; + DefaultIterableDiffer.prototype._addToMoves = function(record, toIndex) { + if (record.previousIndex === toIndex) { + return record; + } + if (this._movesTail === null) { + this._movesTail = this._movesHead = record; + } else { + this._movesTail = this._movesTail._nextMoved = record; + } + return record; + }; + DefaultIterableDiffer.prototype._addToRemovals = function(record) { + if (this._unlinkedRecords === null) { + this._unlinkedRecords = new _DuplicateMap(); + } + this._unlinkedRecords.put(record); + record.currentIndex = null; + record._nextRemoved = null; + if (this._removalsTail === null) { + this._removalsTail = this._removalsHead = record; + record._prevRemoved = null; + } else { + record._prevRemoved = this._removalsTail; + this._removalsTail = this._removalsTail._nextRemoved = record; + } + return record; + }; + DefaultIterableDiffer.prototype.toString = function() { + var record; + var list = []; + for (record = this._itHead; record !== null; record = record._next) { + list.push(record); + } + var previous = []; + for (record = this._previousItHead; record !== null; record = record._nextPrevious) { + previous.push(record); + } + var additions = []; + for (record = this._additionsHead; record !== null; record = record._nextAdded) { + additions.push(record); + } + var moves = []; + for (record = this._movesHead; record !== null; record = record._nextMoved) { + moves.push(record); + } + var removals = []; + for (record = this._removalsHead; record !== null; record = record._nextRemoved) { + removals.push(record); + } + return "collection: " + list.join(', ') + "\n" + "previous: " + previous.join(', ') + "\n" + "additions: " + additions.join(', ') + "\n" + "moves: " + moves.join(', ') + "\n" + "removals: " + removals.join(', ') + "\n"; + }; + return DefaultIterableDiffer; + })(); + exports.DefaultIterableDiffer = DefaultIterableDiffer; + var CollectionChangeRecord = (function() { + function CollectionChangeRecord(item) { + this.item = item; + this.currentIndex = null; + this.previousIndex = null; + this._nextPrevious = null; + this._prev = null; + this._next = null; + this._prevDup = null; + this._nextDup = null; + this._prevRemoved = null; + this._nextRemoved = null; + this._nextAdded = null; + this._nextMoved = null; + } + CollectionChangeRecord.prototype.toString = function() { + return this.previousIndex === this.currentIndex ? lang_2.stringify(this.item) : lang_2.stringify(this.item) + '[' + lang_2.stringify(this.previousIndex) + '->' + lang_2.stringify(this.currentIndex) + ']'; + }; + return CollectionChangeRecord; + })(); + exports.CollectionChangeRecord = CollectionChangeRecord; + var _DuplicateItemRecordList = (function() { + function _DuplicateItemRecordList() { + this._head = null; + this._tail = null; + } + _DuplicateItemRecordList.prototype.add = function(record) { + if (this._head === null) { + this._head = this._tail = record; + record._nextDup = null; + record._prevDup = null; + } else { + this._tail._nextDup = record; + record._prevDup = this._tail; + record._nextDup = null; + this._tail = record; + } + }; + _DuplicateItemRecordList.prototype.get = function(item, afterIndex) { + var record; + for (record = this._head; record !== null; record = record._nextDup) { + if ((afterIndex === null || afterIndex < record.currentIndex) && lang_2.looseIdentical(record.item, item)) { + return record; + } + } + return null; + }; + _DuplicateItemRecordList.prototype.remove = function(record) { + var prev = record._prevDup; + var next = record._nextDup; + if (prev === null) { + this._head = next; + } else { + prev._nextDup = next; + } + if (next === null) { + this._tail = prev; + } else { + next._prevDup = prev; + } + return this._head === null; + }; + return _DuplicateItemRecordList; + })(); + var _DuplicateMap = (function() { + function _DuplicateMap() { + this.map = new Map(); + } + _DuplicateMap.prototype.put = function(record) { + var key = lang_2.getMapKey(record.item); + var duplicates = this.map.get(key); + if (!lang_2.isPresent(duplicates)) { + duplicates = new _DuplicateItemRecordList(); + this.map.set(key, duplicates); + } + duplicates.add(record); + }; + _DuplicateMap.prototype.get = function(value, afterIndex) { + if (afterIndex === void 0) { + afterIndex = null; + } + var key = lang_2.getMapKey(value); + var recordList = this.map.get(key); + return lang_2.isBlank(recordList) ? null : recordList.get(value, afterIndex); + }; + _DuplicateMap.prototype.remove = function(record) { + var key = lang_2.getMapKey(record.item); + var recordList = this.map.get(key); + if (recordList.remove(record)) { + this.map.delete(key); + } + return record; + }; + Object.defineProperty(_DuplicateMap.prototype, "isEmpty", { + get: function() { + return this.map.size === 0; + }, + enumerable: true, + configurable: true + }); + _DuplicateMap.prototype.clear = function() { + this.map.clear(); + }; + _DuplicateMap.prototype.toString = function() { + return '_DuplicateMap(' + lang_2.stringify(this.map) + ')'; + }; + return _DuplicateMap; + })(); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/differs/keyvalue_differs", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/core/di"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var di_1 = require("angular2/src/core/di"); + var KeyValueDiffers = (function() { + function KeyValueDiffers(factories) { + this.factories = factories; + } + KeyValueDiffers.create = function(factories, parent) { + if (lang_1.isPresent(parent)) { + var copied = collection_1.ListWrapper.clone(parent.factories); + factories = factories.concat(copied); + return new KeyValueDiffers(factories); + } else { + return new KeyValueDiffers(factories); + } + }; + KeyValueDiffers.extend = function(factories) { + return new di_1.Provider(KeyValueDiffers, { + useFactory: function(parent) { + if (lang_1.isBlank(parent)) { + throw new exceptions_1.BaseException('Cannot extend KeyValueDiffers without a parent injector'); + } + return KeyValueDiffers.create(factories, parent); + }, + deps: [[KeyValueDiffers, new di_1.SkipSelfMetadata(), new di_1.OptionalMetadata()]] + }); + }; + KeyValueDiffers.prototype.find = function(kv) { + var factory = this.factories.find(function(f) { + return f.supports(kv); + }); + if (lang_1.isPresent(factory)) { + return factory; + } else { + throw new exceptions_1.BaseException("Cannot find a differ supporting object '" + kv + "'"); + } + }; + KeyValueDiffers = __decorate([di_1.Injectable(), lang_1.CONST(), __metadata('design:paramtypes', [Array])], KeyValueDiffers); + return KeyValueDiffers; + })(); + exports.KeyValueDiffers = KeyValueDiffers; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/differs/default_keyvalue_differ", ["angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/facade/exceptions"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var DefaultKeyValueDifferFactory = (function() { + function DefaultKeyValueDifferFactory() {} + DefaultKeyValueDifferFactory.prototype.supports = function(obj) { + return obj instanceof Map || lang_1.isJsObject(obj); + }; + DefaultKeyValueDifferFactory.prototype.create = function(cdRef) { + return new DefaultKeyValueDiffer(); + }; + DefaultKeyValueDifferFactory = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [])], DefaultKeyValueDifferFactory); + return DefaultKeyValueDifferFactory; + })(); + exports.DefaultKeyValueDifferFactory = DefaultKeyValueDifferFactory; + var DefaultKeyValueDiffer = (function() { + function DefaultKeyValueDiffer() { + this._records = new Map(); + this._mapHead = null; + this._previousMapHead = null; + this._changesHead = null; + this._changesTail = null; + this._additionsHead = null; + this._additionsTail = null; + this._removalsHead = null; + this._removalsTail = null; + } + Object.defineProperty(DefaultKeyValueDiffer.prototype, "isDirty", { + get: function() { + return this._additionsHead !== null || this._changesHead !== null || this._removalsHead !== null; + }, + enumerable: true, + configurable: true + }); + DefaultKeyValueDiffer.prototype.forEachItem = function(fn) { + var record; + for (record = this._mapHead; record !== null; record = record._next) { + fn(record); + } + }; + DefaultKeyValueDiffer.prototype.forEachPreviousItem = function(fn) { + var record; + for (record = this._previousMapHead; record !== null; record = record._nextPrevious) { + fn(record); + } + }; + DefaultKeyValueDiffer.prototype.forEachChangedItem = function(fn) { + var record; + for (record = this._changesHead; record !== null; record = record._nextChanged) { + fn(record); + } + }; + DefaultKeyValueDiffer.prototype.forEachAddedItem = function(fn) { + var record; + for (record = this._additionsHead; record !== null; record = record._nextAdded) { + fn(record); + } + }; + DefaultKeyValueDiffer.prototype.forEachRemovedItem = function(fn) { + var record; + for (record = this._removalsHead; record !== null; record = record._nextRemoved) { + fn(record); + } + }; + DefaultKeyValueDiffer.prototype.diff = function(map) { + if (lang_1.isBlank(map)) + map = collection_1.MapWrapper.createFromPairs([]); + if (!(map instanceof Map || lang_1.isJsObject(map))) { + throw new exceptions_1.BaseException("Error trying to diff '" + map + "'"); + } + if (this.check(map)) { + return this; + } else { + return null; + } + }; + DefaultKeyValueDiffer.prototype.onDestroy = function() {}; + DefaultKeyValueDiffer.prototype.check = function(map) { + var _this = this; + this._reset(); + var records = this._records; + var oldSeqRecord = this._mapHead; + var lastOldSeqRecord = null; + var lastNewSeqRecord = null; + var seqChanged = false; + this._forEach(map, function(value, key) { + var newSeqRecord; + if (oldSeqRecord !== null && key === oldSeqRecord.key) { + newSeqRecord = oldSeqRecord; + if (!lang_1.looseIdentical(value, oldSeqRecord.currentValue)) { + oldSeqRecord.previousValue = oldSeqRecord.currentValue; + oldSeqRecord.currentValue = value; + _this._addToChanges(oldSeqRecord); + } + } else { + seqChanged = true; + if (oldSeqRecord !== null) { + oldSeqRecord._next = null; + _this._removeFromSeq(lastOldSeqRecord, oldSeqRecord); + _this._addToRemovals(oldSeqRecord); + } + if (records.has(key)) { + newSeqRecord = records.get(key); + } else { + newSeqRecord = new KVChangeRecord(key); + records.set(key, newSeqRecord); + newSeqRecord.currentValue = value; + _this._addToAdditions(newSeqRecord); + } + } + if (seqChanged) { + if (_this._isInRemovals(newSeqRecord)) { + _this._removeFromRemovals(newSeqRecord); + } + if (lastNewSeqRecord == null) { + _this._mapHead = newSeqRecord; + } else { + lastNewSeqRecord._next = newSeqRecord; + } + } + lastOldSeqRecord = oldSeqRecord; + lastNewSeqRecord = newSeqRecord; + oldSeqRecord = oldSeqRecord === null ? null : oldSeqRecord._next; + }); + this._truncate(lastOldSeqRecord, oldSeqRecord); + return this.isDirty; + }; + DefaultKeyValueDiffer.prototype._reset = function() { + if (this.isDirty) { + var record; + for (record = this._previousMapHead = this._mapHead; record !== null; record = record._next) { + record._nextPrevious = record._next; + } + for (record = this._changesHead; record !== null; record = record._nextChanged) { + record.previousValue = record.currentValue; + } + for (record = this._additionsHead; record != null; record = record._nextAdded) { + record.previousValue = record.currentValue; + } + this._changesHead = this._changesTail = null; + this._additionsHead = this._additionsTail = null; + this._removalsHead = this._removalsTail = null; + } + }; + DefaultKeyValueDiffer.prototype._truncate = function(lastRecord, record) { + while (record !== null) { + if (lastRecord === null) { + this._mapHead = null; + } else { + lastRecord._next = null; + } + var nextRecord = record._next; + this._addToRemovals(record); + lastRecord = record; + record = nextRecord; + } + for (var rec = this._removalsHead; rec !== null; rec = rec._nextRemoved) { + rec.previousValue = rec.currentValue; + rec.currentValue = null; + this._records.delete(rec.key); + } + }; + DefaultKeyValueDiffer.prototype._isInRemovals = function(record) { + return record === this._removalsHead || record._nextRemoved !== null || record._prevRemoved !== null; + }; + DefaultKeyValueDiffer.prototype._addToRemovals = function(record) { + if (this._removalsHead === null) { + this._removalsHead = this._removalsTail = record; + } else { + this._removalsTail._nextRemoved = record; + record._prevRemoved = this._removalsTail; + this._removalsTail = record; + } + }; + DefaultKeyValueDiffer.prototype._removeFromSeq = function(prev, record) { + var next = record._next; + if (prev === null) { + this._mapHead = next; + } else { + prev._next = next; + } + }; + DefaultKeyValueDiffer.prototype._removeFromRemovals = function(record) { + var prev = record._prevRemoved; + var next = record._nextRemoved; + if (prev === null) { + this._removalsHead = next; + } else { + prev._nextRemoved = next; + } + if (next === null) { + this._removalsTail = prev; + } else { + next._prevRemoved = prev; + } + record._prevRemoved = record._nextRemoved = null; + }; + DefaultKeyValueDiffer.prototype._addToAdditions = function(record) { + if (this._additionsHead === null) { + this._additionsHead = this._additionsTail = record; + } else { + this._additionsTail._nextAdded = record; + this._additionsTail = record; + } + }; + DefaultKeyValueDiffer.prototype._addToChanges = function(record) { + if (this._changesHead === null) { + this._changesHead = this._changesTail = record; + } else { + this._changesTail._nextChanged = record; + this._changesTail = record; + } + }; + DefaultKeyValueDiffer.prototype.toString = function() { + var items = []; + var previous = []; + var changes = []; + var additions = []; + var removals = []; + var record; + for (record = this._mapHead; record !== null; record = record._next) { + items.push(lang_1.stringify(record)); + } + for (record = this._previousMapHead; record !== null; record = record._nextPrevious) { + previous.push(lang_1.stringify(record)); + } + for (record = this._changesHead; record !== null; record = record._nextChanged) { + changes.push(lang_1.stringify(record)); + } + for (record = this._additionsHead; record !== null; record = record._nextAdded) { + additions.push(lang_1.stringify(record)); + } + for (record = this._removalsHead; record !== null; record = record._nextRemoved) { + removals.push(lang_1.stringify(record)); + } + return "map: " + items.join(', ') + "\n" + "previous: " + previous.join(', ') + "\n" + "additions: " + additions.join(', ') + "\n" + "changes: " + changes.join(', ') + "\n" + "removals: " + removals.join(', ') + "\n"; + }; + DefaultKeyValueDiffer.prototype._forEach = function(obj, fn) { + if (obj instanceof Map) { + obj.forEach(fn); + } else { + collection_1.StringMapWrapper.forEach(obj, fn); + } + }; + return DefaultKeyValueDiffer; + })(); + exports.DefaultKeyValueDiffer = DefaultKeyValueDiffer; + var KVChangeRecord = (function() { + function KVChangeRecord(key) { + this.key = key; + this.previousValue = null; + this.currentValue = null; + this._nextPrevious = null; + this._next = null; + this._nextAdded = null; + this._nextRemoved = null; + this._prevRemoved = null; + this._nextChanged = null; + } + KVChangeRecord.prototype.toString = function() { + return lang_1.looseIdentical(this.previousValue, this.currentValue) ? lang_1.stringify(this.key) : (lang_1.stringify(this.key) + '[' + lang_1.stringify(this.previousValue) + '->' + lang_1.stringify(this.currentValue) + ']'); + }; + return KVChangeRecord; + })(); + exports.KVChangeRecord = KVChangeRecord; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/parser/ast", ["angular2/src/facade/collection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var collection_1 = require("angular2/src/facade/collection"); + var AST = (function() { + function AST() {} + AST.prototype.visit = function(visitor) { + return null; + }; + AST.prototype.toString = function() { + return "AST"; + }; + return AST; + })(); + exports.AST = AST; + var Quote = (function(_super) { + __extends(Quote, _super); + function Quote(prefix, uninterpretedExpression, location) { + _super.call(this); + this.prefix = prefix; + this.uninterpretedExpression = uninterpretedExpression; + this.location = location; + } + Quote.prototype.visit = function(visitor) { + return visitor.visitQuote(this); + }; + Quote.prototype.toString = function() { + return "Quote"; + }; + return Quote; + })(AST); + exports.Quote = Quote; + var EmptyExpr = (function(_super) { + __extends(EmptyExpr, _super); + function EmptyExpr() { + _super.apply(this, arguments); + } + EmptyExpr.prototype.visit = function(visitor) {}; + return EmptyExpr; + })(AST); + exports.EmptyExpr = EmptyExpr; + var ImplicitReceiver = (function(_super) { + __extends(ImplicitReceiver, _super); + function ImplicitReceiver() { + _super.apply(this, arguments); + } + ImplicitReceiver.prototype.visit = function(visitor) { + return visitor.visitImplicitReceiver(this); + }; + return ImplicitReceiver; + })(AST); + exports.ImplicitReceiver = ImplicitReceiver; + var Chain = (function(_super) { + __extends(Chain, _super); + function Chain(expressions) { + _super.call(this); + this.expressions = expressions; + } + Chain.prototype.visit = function(visitor) { + return visitor.visitChain(this); + }; + return Chain; + })(AST); + exports.Chain = Chain; + var Conditional = (function(_super) { + __extends(Conditional, _super); + function Conditional(condition, trueExp, falseExp) { + _super.call(this); + this.condition = condition; + this.trueExp = trueExp; + this.falseExp = falseExp; + } + Conditional.prototype.visit = function(visitor) { + return visitor.visitConditional(this); + }; + return Conditional; + })(AST); + exports.Conditional = Conditional; + var PropertyRead = (function(_super) { + __extends(PropertyRead, _super); + function PropertyRead(receiver, name, getter) { + _super.call(this); + this.receiver = receiver; + this.name = name; + this.getter = getter; + } + PropertyRead.prototype.visit = function(visitor) { + return visitor.visitPropertyRead(this); + }; + return PropertyRead; + })(AST); + exports.PropertyRead = PropertyRead; + var PropertyWrite = (function(_super) { + __extends(PropertyWrite, _super); + function PropertyWrite(receiver, name, setter, value) { + _super.call(this); + this.receiver = receiver; + this.name = name; + this.setter = setter; + this.value = value; + } + PropertyWrite.prototype.visit = function(visitor) { + return visitor.visitPropertyWrite(this); + }; + return PropertyWrite; + })(AST); + exports.PropertyWrite = PropertyWrite; + var SafePropertyRead = (function(_super) { + __extends(SafePropertyRead, _super); + function SafePropertyRead(receiver, name, getter) { + _super.call(this); + this.receiver = receiver; + this.name = name; + this.getter = getter; + } + SafePropertyRead.prototype.visit = function(visitor) { + return visitor.visitSafePropertyRead(this); + }; + return SafePropertyRead; + })(AST); + exports.SafePropertyRead = SafePropertyRead; + var KeyedRead = (function(_super) { + __extends(KeyedRead, _super); + function KeyedRead(obj, key) { + _super.call(this); + this.obj = obj; + this.key = key; + } + KeyedRead.prototype.visit = function(visitor) { + return visitor.visitKeyedRead(this); + }; + return KeyedRead; + })(AST); + exports.KeyedRead = KeyedRead; + var KeyedWrite = (function(_super) { + __extends(KeyedWrite, _super); + function KeyedWrite(obj, key, value) { + _super.call(this); + this.obj = obj; + this.key = key; + this.value = value; + } + KeyedWrite.prototype.visit = function(visitor) { + return visitor.visitKeyedWrite(this); + }; + return KeyedWrite; + })(AST); + exports.KeyedWrite = KeyedWrite; + var BindingPipe = (function(_super) { + __extends(BindingPipe, _super); + function BindingPipe(exp, name, args) { + _super.call(this); + this.exp = exp; + this.name = name; + this.args = args; + } + BindingPipe.prototype.visit = function(visitor) { + return visitor.visitPipe(this); + }; + return BindingPipe; + })(AST); + exports.BindingPipe = BindingPipe; + var LiteralPrimitive = (function(_super) { + __extends(LiteralPrimitive, _super); + function LiteralPrimitive(value) { + _super.call(this); + this.value = value; + } + LiteralPrimitive.prototype.visit = function(visitor) { + return visitor.visitLiteralPrimitive(this); + }; + return LiteralPrimitive; + })(AST); + exports.LiteralPrimitive = LiteralPrimitive; + var LiteralArray = (function(_super) { + __extends(LiteralArray, _super); + function LiteralArray(expressions) { + _super.call(this); + this.expressions = expressions; + } + LiteralArray.prototype.visit = function(visitor) { + return visitor.visitLiteralArray(this); + }; + return LiteralArray; + })(AST); + exports.LiteralArray = LiteralArray; + var LiteralMap = (function(_super) { + __extends(LiteralMap, _super); + function LiteralMap(keys, values) { + _super.call(this); + this.keys = keys; + this.values = values; + } + LiteralMap.prototype.visit = function(visitor) { + return visitor.visitLiteralMap(this); + }; + return LiteralMap; + })(AST); + exports.LiteralMap = LiteralMap; + var Interpolation = (function(_super) { + __extends(Interpolation, _super); + function Interpolation(strings, expressions) { + _super.call(this); + this.strings = strings; + this.expressions = expressions; + } + Interpolation.prototype.visit = function(visitor) { + return visitor.visitInterpolation(this); + }; + return Interpolation; + })(AST); + exports.Interpolation = Interpolation; + var Binary = (function(_super) { + __extends(Binary, _super); + function Binary(operation, left, right) { + _super.call(this); + this.operation = operation; + this.left = left; + this.right = right; + } + Binary.prototype.visit = function(visitor) { + return visitor.visitBinary(this); + }; + return Binary; + })(AST); + exports.Binary = Binary; + var PrefixNot = (function(_super) { + __extends(PrefixNot, _super); + function PrefixNot(expression) { + _super.call(this); + this.expression = expression; + } + PrefixNot.prototype.visit = function(visitor) { + return visitor.visitPrefixNot(this); + }; + return PrefixNot; + })(AST); + exports.PrefixNot = PrefixNot; + var MethodCall = (function(_super) { + __extends(MethodCall, _super); + function MethodCall(receiver, name, fn, args) { + _super.call(this); + this.receiver = receiver; + this.name = name; + this.fn = fn; + this.args = args; + } + MethodCall.prototype.visit = function(visitor) { + return visitor.visitMethodCall(this); + }; + return MethodCall; + })(AST); + exports.MethodCall = MethodCall; + var SafeMethodCall = (function(_super) { + __extends(SafeMethodCall, _super); + function SafeMethodCall(receiver, name, fn, args) { + _super.call(this); + this.receiver = receiver; + this.name = name; + this.fn = fn; + this.args = args; + } + SafeMethodCall.prototype.visit = function(visitor) { + return visitor.visitSafeMethodCall(this); + }; + return SafeMethodCall; + })(AST); + exports.SafeMethodCall = SafeMethodCall; + var FunctionCall = (function(_super) { + __extends(FunctionCall, _super); + function FunctionCall(target, args) { + _super.call(this); + this.target = target; + this.args = args; + } + FunctionCall.prototype.visit = function(visitor) { + return visitor.visitFunctionCall(this); + }; + return FunctionCall; + })(AST); + exports.FunctionCall = FunctionCall; + var ASTWithSource = (function(_super) { + __extends(ASTWithSource, _super); + function ASTWithSource(ast, source, location) { + _super.call(this); + this.ast = ast; + this.source = source; + this.location = location; + } + ASTWithSource.prototype.visit = function(visitor) { + return this.ast.visit(visitor); + }; + ASTWithSource.prototype.toString = function() { + return this.source + " in " + this.location; + }; + return ASTWithSource; + })(AST); + exports.ASTWithSource = ASTWithSource; + var TemplateBinding = (function() { + function TemplateBinding(key, keyIsVar, name, expression) { + this.key = key; + this.keyIsVar = keyIsVar; + this.name = name; + this.expression = expression; + } + return TemplateBinding; + })(); + exports.TemplateBinding = TemplateBinding; + var RecursiveAstVisitor = (function() { + function RecursiveAstVisitor() {} + RecursiveAstVisitor.prototype.visitBinary = function(ast) { + ast.left.visit(this); + ast.right.visit(this); + return null; + }; + RecursiveAstVisitor.prototype.visitChain = function(ast) { + return this.visitAll(ast.expressions); + }; + RecursiveAstVisitor.prototype.visitConditional = function(ast) { + ast.condition.visit(this); + ast.trueExp.visit(this); + ast.falseExp.visit(this); + return null; + }; + RecursiveAstVisitor.prototype.visitPipe = function(ast) { + ast.exp.visit(this); + this.visitAll(ast.args); + return null; + }; + RecursiveAstVisitor.prototype.visitFunctionCall = function(ast) { + ast.target.visit(this); + this.visitAll(ast.args); + return null; + }; + RecursiveAstVisitor.prototype.visitImplicitReceiver = function(ast) { + return null; + }; + RecursiveAstVisitor.prototype.visitInterpolation = function(ast) { + return this.visitAll(ast.expressions); + }; + RecursiveAstVisitor.prototype.visitKeyedRead = function(ast) { + ast.obj.visit(this); + ast.key.visit(this); + return null; + }; + RecursiveAstVisitor.prototype.visitKeyedWrite = function(ast) { + ast.obj.visit(this); + ast.key.visit(this); + ast.value.visit(this); + return null; + }; + RecursiveAstVisitor.prototype.visitLiteralArray = function(ast) { + return this.visitAll(ast.expressions); + }; + RecursiveAstVisitor.prototype.visitLiteralMap = function(ast) { + return this.visitAll(ast.values); + }; + RecursiveAstVisitor.prototype.visitLiteralPrimitive = function(ast) { + return null; + }; + RecursiveAstVisitor.prototype.visitMethodCall = function(ast) { + ast.receiver.visit(this); + return this.visitAll(ast.args); + }; + RecursiveAstVisitor.prototype.visitPrefixNot = function(ast) { + ast.expression.visit(this); + return null; + }; + RecursiveAstVisitor.prototype.visitPropertyRead = function(ast) { + ast.receiver.visit(this); + return null; + }; + RecursiveAstVisitor.prototype.visitPropertyWrite = function(ast) { + ast.receiver.visit(this); + ast.value.visit(this); + return null; + }; + RecursiveAstVisitor.prototype.visitSafePropertyRead = function(ast) { + ast.receiver.visit(this); + return null; + }; + RecursiveAstVisitor.prototype.visitSafeMethodCall = function(ast) { + ast.receiver.visit(this); + return this.visitAll(ast.args); + }; + RecursiveAstVisitor.prototype.visitAll = function(asts) { + var _this = this; + asts.forEach(function(ast) { + return ast.visit(_this); + }); + return null; + }; + RecursiveAstVisitor.prototype.visitQuote = function(ast) { + return null; + }; + return RecursiveAstVisitor; + })(); + exports.RecursiveAstVisitor = RecursiveAstVisitor; + var AstTransformer = (function() { + function AstTransformer() {} + AstTransformer.prototype.visitImplicitReceiver = function(ast) { + return ast; + }; + AstTransformer.prototype.visitInterpolation = function(ast) { + return new Interpolation(ast.strings, this.visitAll(ast.expressions)); + }; + AstTransformer.prototype.visitLiteralPrimitive = function(ast) { + return new LiteralPrimitive(ast.value); + }; + AstTransformer.prototype.visitPropertyRead = function(ast) { + return new PropertyRead(ast.receiver.visit(this), ast.name, ast.getter); + }; + AstTransformer.prototype.visitPropertyWrite = function(ast) { + return new PropertyWrite(ast.receiver.visit(this), ast.name, ast.setter, ast.value); + }; + AstTransformer.prototype.visitSafePropertyRead = function(ast) { + return new SafePropertyRead(ast.receiver.visit(this), ast.name, ast.getter); + }; + AstTransformer.prototype.visitMethodCall = function(ast) { + return new MethodCall(ast.receiver.visit(this), ast.name, ast.fn, this.visitAll(ast.args)); + }; + AstTransformer.prototype.visitSafeMethodCall = function(ast) { + return new SafeMethodCall(ast.receiver.visit(this), ast.name, ast.fn, this.visitAll(ast.args)); + }; + AstTransformer.prototype.visitFunctionCall = function(ast) { + return new FunctionCall(ast.target.visit(this), this.visitAll(ast.args)); + }; + AstTransformer.prototype.visitLiteralArray = function(ast) { + return new LiteralArray(this.visitAll(ast.expressions)); + }; + AstTransformer.prototype.visitLiteralMap = function(ast) { + return new LiteralMap(ast.keys, this.visitAll(ast.values)); + }; + AstTransformer.prototype.visitBinary = function(ast) { + return new Binary(ast.operation, ast.left.visit(this), ast.right.visit(this)); + }; + AstTransformer.prototype.visitPrefixNot = function(ast) { + return new PrefixNot(ast.expression.visit(this)); + }; + AstTransformer.prototype.visitConditional = function(ast) { + return new Conditional(ast.condition.visit(this), ast.trueExp.visit(this), ast.falseExp.visit(this)); + }; + AstTransformer.prototype.visitPipe = function(ast) { + return new BindingPipe(ast.exp.visit(this), ast.name, this.visitAll(ast.args)); + }; + AstTransformer.prototype.visitKeyedRead = function(ast) { + return new KeyedRead(ast.obj.visit(this), ast.key.visit(this)); + }; + AstTransformer.prototype.visitKeyedWrite = function(ast) { + return new KeyedWrite(ast.obj.visit(this), ast.key.visit(this), ast.value.visit(this)); + }; + AstTransformer.prototype.visitAll = function(asts) { + var res = collection_1.ListWrapper.createFixedSize(asts.length); + for (var i = 0; i < asts.length; ++i) { + res[i] = asts[i].visit(this); + } + return res; + }; + AstTransformer.prototype.visitChain = function(ast) { + return new Chain(this.visitAll(ast.expressions)); + }; + AstTransformer.prototype.visitQuote = function(ast) { + return new Quote(ast.prefix, ast.uninterpretedExpression, ast.location); + }; + return AstTransformer; + })(); + exports.AstTransformer = AstTransformer; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/parser/lexer", ["angular2/src/core/di/decorators", "angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/facade/exceptions"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var decorators_1 = require("angular2/src/core/di/decorators"); + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + (function(TokenType) { + TokenType[TokenType["Character"] = 0] = "Character"; + TokenType[TokenType["Identifier"] = 1] = "Identifier"; + TokenType[TokenType["Keyword"] = 2] = "Keyword"; + TokenType[TokenType["String"] = 3] = "String"; + TokenType[TokenType["Operator"] = 4] = "Operator"; + TokenType[TokenType["Number"] = 5] = "Number"; + })(exports.TokenType || (exports.TokenType = {})); + var TokenType = exports.TokenType; + var Lexer = (function() { + function Lexer() {} + Lexer.prototype.tokenize = function(text) { + var scanner = new _Scanner(text); + var tokens = []; + var token = scanner.scanToken(); + while (token != null) { + tokens.push(token); + token = scanner.scanToken(); + } + return tokens; + }; + Lexer = __decorate([decorators_1.Injectable(), __metadata('design:paramtypes', [])], Lexer); + return Lexer; + })(); + exports.Lexer = Lexer; + var Token = (function() { + function Token(index, type, numValue, strValue) { + this.index = index; + this.type = type; + this.numValue = numValue; + this.strValue = strValue; + } + Token.prototype.isCharacter = function(code) { + return (this.type == TokenType.Character && this.numValue == code); + }; + Token.prototype.isNumber = function() { + return (this.type == TokenType.Number); + }; + Token.prototype.isString = function() { + return (this.type == TokenType.String); + }; + Token.prototype.isOperator = function(operater) { + return (this.type == TokenType.Operator && this.strValue == operater); + }; + Token.prototype.isIdentifier = function() { + return (this.type == TokenType.Identifier); + }; + Token.prototype.isKeyword = function() { + return (this.type == TokenType.Keyword); + }; + Token.prototype.isKeywordVar = function() { + return (this.type == TokenType.Keyword && this.strValue == "var"); + }; + Token.prototype.isKeywordNull = function() { + return (this.type == TokenType.Keyword && this.strValue == "null"); + }; + Token.prototype.isKeywordUndefined = function() { + return (this.type == TokenType.Keyword && this.strValue == "undefined"); + }; + Token.prototype.isKeywordTrue = function() { + return (this.type == TokenType.Keyword && this.strValue == "true"); + }; + Token.prototype.isKeywordFalse = function() { + return (this.type == TokenType.Keyword && this.strValue == "false"); + }; + Token.prototype.toNumber = function() { + return (this.type == TokenType.Number) ? this.numValue : -1; + }; + Token.prototype.toString = function() { + switch (this.type) { + case TokenType.Character: + case TokenType.Identifier: + case TokenType.Keyword: + case TokenType.Operator: + case TokenType.String: + return this.strValue; + case TokenType.Number: + return this.numValue.toString(); + default: + return null; + } + }; + return Token; + })(); + exports.Token = Token; + function newCharacterToken(index, code) { + return new Token(index, TokenType.Character, code, lang_1.StringWrapper.fromCharCode(code)); + } + function newIdentifierToken(index, text) { + return new Token(index, TokenType.Identifier, 0, text); + } + function newKeywordToken(index, text) { + return new Token(index, TokenType.Keyword, 0, text); + } + function newOperatorToken(index, text) { + return new Token(index, TokenType.Operator, 0, text); + } + function newStringToken(index, text) { + return new Token(index, TokenType.String, 0, text); + } + function newNumberToken(index, n) { + return new Token(index, TokenType.Number, n, ""); + } + exports.EOF = new Token(-1, TokenType.Character, 0, ""); + exports.$EOF = 0; + exports.$TAB = 9; + exports.$LF = 10; + exports.$VTAB = 11; + exports.$FF = 12; + exports.$CR = 13; + exports.$SPACE = 32; + exports.$BANG = 33; + exports.$DQ = 34; + exports.$HASH = 35; + exports.$$ = 36; + exports.$PERCENT = 37; + exports.$AMPERSAND = 38; + exports.$SQ = 39; + exports.$LPAREN = 40; + exports.$RPAREN = 41; + exports.$STAR = 42; + exports.$PLUS = 43; + exports.$COMMA = 44; + exports.$MINUS = 45; + exports.$PERIOD = 46; + exports.$SLASH = 47; + exports.$COLON = 58; + exports.$SEMICOLON = 59; + exports.$LT = 60; + exports.$EQ = 61; + exports.$GT = 62; + exports.$QUESTION = 63; + var $0 = 48; + var $9 = 57; + var $A = 65, + $E = 69, + $Z = 90; + exports.$LBRACKET = 91; + exports.$BACKSLASH = 92; + exports.$RBRACKET = 93; + var $CARET = 94; + var $_ = 95; + var $a = 97, + $e = 101, + $f = 102, + $n = 110, + $r = 114, + $t = 116, + $u = 117, + $v = 118, + $z = 122; + exports.$LBRACE = 123; + exports.$BAR = 124; + exports.$RBRACE = 125; + var $NBSP = 160; + var ScannerError = (function(_super) { + __extends(ScannerError, _super); + function ScannerError(message) { + _super.call(this); + this.message = message; + } + ScannerError.prototype.toString = function() { + return this.message; + }; + return ScannerError; + })(exceptions_1.BaseException); + exports.ScannerError = ScannerError; + var _Scanner = (function() { + function _Scanner(input) { + this.input = input; + this.peek = 0; + this.index = -1; + this.length = input.length; + this.advance(); + } + _Scanner.prototype.advance = function() { + this.peek = ++this.index >= this.length ? exports.$EOF : lang_1.StringWrapper.charCodeAt(this.input, this.index); + }; + _Scanner.prototype.scanToken = function() { + var input = this.input, + length = this.length, + peek = this.peek, + index = this.index; + while (peek <= exports.$SPACE) { + if (++index >= length) { + peek = exports.$EOF; + break; + } else { + peek = lang_1.StringWrapper.charCodeAt(input, index); + } + } + this.peek = peek; + this.index = index; + if (index >= length) { + return null; + } + if (isIdentifierStart(peek)) + return this.scanIdentifier(); + if (isDigit(peek)) + return this.scanNumber(index); + var start = index; + switch (peek) { + case exports.$PERIOD: + this.advance(); + return isDigit(this.peek) ? this.scanNumber(start) : newCharacterToken(start, exports.$PERIOD); + case exports.$LPAREN: + case exports.$RPAREN: + case exports.$LBRACE: + case exports.$RBRACE: + case exports.$LBRACKET: + case exports.$RBRACKET: + case exports.$COMMA: + case exports.$COLON: + case exports.$SEMICOLON: + return this.scanCharacter(start, peek); + case exports.$SQ: + case exports.$DQ: + return this.scanString(); + case exports.$HASH: + case exports.$PLUS: + case exports.$MINUS: + case exports.$STAR: + case exports.$SLASH: + case exports.$PERCENT: + case $CARET: + return this.scanOperator(start, lang_1.StringWrapper.fromCharCode(peek)); + case exports.$QUESTION: + return this.scanComplexOperator(start, '?', exports.$PERIOD, '.'); + case exports.$LT: + case exports.$GT: + return this.scanComplexOperator(start, lang_1.StringWrapper.fromCharCode(peek), exports.$EQ, '='); + case exports.$BANG: + case exports.$EQ: + return this.scanComplexOperator(start, lang_1.StringWrapper.fromCharCode(peek), exports.$EQ, '=', exports.$EQ, '='); + case exports.$AMPERSAND: + return this.scanComplexOperator(start, '&', exports.$AMPERSAND, '&'); + case exports.$BAR: + return this.scanComplexOperator(start, '|', exports.$BAR, '|'); + case $NBSP: + while (isWhitespace(this.peek)) + this.advance(); + return this.scanToken(); + } + this.error("Unexpected character [" + lang_1.StringWrapper.fromCharCode(peek) + "]", 0); + return null; + }; + _Scanner.prototype.scanCharacter = function(start, code) { + assert(this.peek == code); + this.advance(); + return newCharacterToken(start, code); + }; + _Scanner.prototype.scanOperator = function(start, str) { + assert(this.peek == lang_1.StringWrapper.charCodeAt(str, 0)); + assert(collection_1.SetWrapper.has(OPERATORS, str)); + this.advance(); + return newOperatorToken(start, str); + }; + _Scanner.prototype.scanComplexOperator = function(start, one, twoCode, two, threeCode, three) { + assert(this.peek == lang_1.StringWrapper.charCodeAt(one, 0)); + this.advance(); + var str = one; + if (this.peek == twoCode) { + this.advance(); + str += two; + } + if (lang_1.isPresent(threeCode) && this.peek == threeCode) { + this.advance(); + str += three; + } + assert(collection_1.SetWrapper.has(OPERATORS, str)); + return newOperatorToken(start, str); + }; + _Scanner.prototype.scanIdentifier = function() { + assert(isIdentifierStart(this.peek)); + var start = this.index; + this.advance(); + while (isIdentifierPart(this.peek)) + this.advance(); + var str = this.input.substring(start, this.index); + if (collection_1.SetWrapper.has(KEYWORDS, str)) { + return newKeywordToken(start, str); + } else { + return newIdentifierToken(start, str); + } + }; + _Scanner.prototype.scanNumber = function(start) { + assert(isDigit(this.peek)); + var simple = (this.index === start); + this.advance(); + while (true) { + if (isDigit(this.peek)) {} else if (this.peek == exports.$PERIOD) { + simple = false; + } else if (isExponentStart(this.peek)) { + this.advance(); + if (isExponentSign(this.peek)) + this.advance(); + if (!isDigit(this.peek)) + this.error('Invalid exponent', -1); + simple = false; + } else { + break; + } + this.advance(); + } + var str = this.input.substring(start, this.index); + var value = simple ? lang_1.NumberWrapper.parseIntAutoRadix(str) : lang_1.NumberWrapper.parseFloat(str); + return newNumberToken(start, value); + }; + _Scanner.prototype.scanString = function() { + assert(this.peek == exports.$SQ || this.peek == exports.$DQ); + var start = this.index; + var quote = this.peek; + this.advance(); + var buffer; + var marker = this.index; + var input = this.input; + while (this.peek != quote) { + if (this.peek == exports.$BACKSLASH) { + if (buffer == null) + buffer = new lang_1.StringJoiner(); + buffer.add(input.substring(marker, this.index)); + this.advance(); + var unescapedCode; + if (this.peek == $u) { + var hex = input.substring(this.index + 1, this.index + 5); + try { + unescapedCode = lang_1.NumberWrapper.parseInt(hex, 16); + } catch (e) { + this.error("Invalid unicode escape [\\u" + hex + "]", 0); + } + for (var i = 0; i < 5; i++) { + this.advance(); + } + } else { + unescapedCode = unescape(this.peek); + this.advance(); + } + buffer.add(lang_1.StringWrapper.fromCharCode(unescapedCode)); + marker = this.index; + } else if (this.peek == exports.$EOF) { + this.error('Unterminated quote', 0); + } else { + this.advance(); + } + } + var last = input.substring(marker, this.index); + this.advance(); + var unescaped = last; + if (buffer != null) { + buffer.add(last); + unescaped = buffer.toString(); + } + return newStringToken(start, unescaped); + }; + _Scanner.prototype.error = function(message, offset) { + var position = this.index + offset; + throw new ScannerError("Lexer Error: " + message + " at column " + position + " in expression [" + this.input + "]"); + }; + return _Scanner; + })(); + function isWhitespace(code) { + return (code >= exports.$TAB && code <= exports.$SPACE) || (code == $NBSP); + } + function isIdentifierStart(code) { + return ($a <= code && code <= $z) || ($A <= code && code <= $Z) || (code == $_) || (code == exports.$$); + } + function isIdentifier(input) { + if (input.length == 0) + return false; + var scanner = new _Scanner(input); + if (!isIdentifierStart(scanner.peek)) + return false; + scanner.advance(); + while (scanner.peek !== exports.$EOF) { + if (!isIdentifierPart(scanner.peek)) + return false; + scanner.advance(); + } + return true; + } + exports.isIdentifier = isIdentifier; + function isIdentifierPart(code) { + return ($a <= code && code <= $z) || ($A <= code && code <= $Z) || ($0 <= code && code <= $9) || (code == $_) || (code == exports.$$); + } + function isDigit(code) { + return $0 <= code && code <= $9; + } + function isExponentStart(code) { + return code == $e || code == $E; + } + function isExponentSign(code) { + return code == exports.$MINUS || code == exports.$PLUS; + } + function unescape(code) { + switch (code) { + case $n: + return exports.$LF; + case $f: + return exports.$FF; + case $r: + return exports.$CR; + case $t: + return exports.$TAB; + case $v: + return exports.$VTAB; + default: + return code; + } + } + var OPERATORS = collection_1.SetWrapper.createFromList(['+', '-', '*', '/', '%', '^', '=', '==', '!=', '===', '!==', '<', '>', '<=', '>=', '&&', '||', '&', '|', '!', '?', '#', '?.']); + var KEYWORDS = collection_1.SetWrapper.createFromList(['var', 'null', 'undefined', 'true', 'false', 'if', 'else']); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/parser/parser", ["angular2/src/core/di/decorators", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/core/change_detection/parser/lexer", "angular2/src/core/reflection/reflection", "angular2/src/core/change_detection/parser/ast"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var decorators_1 = require("angular2/src/core/di/decorators"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var lexer_1 = require("angular2/src/core/change_detection/parser/lexer"); + var reflection_1 = require("angular2/src/core/reflection/reflection"); + var ast_1 = require("angular2/src/core/change_detection/parser/ast"); + var _implicitReceiver = new ast_1.ImplicitReceiver(); + var INTERPOLATION_REGEXP = /\{\{(.*?)\}\}/g; + var ParseException = (function(_super) { + __extends(ParseException, _super); + function ParseException(message, input, errLocation, ctxLocation) { + _super.call(this, "Parser Error: " + message + " " + errLocation + " [" + input + "] in " + ctxLocation); + } + return ParseException; + })(exceptions_1.BaseException); + var Parser = (function() { + function Parser(_lexer, providedReflector) { + if (providedReflector === void 0) { + providedReflector = null; + } + this._lexer = _lexer; + this._reflector = lang_1.isPresent(providedReflector) ? providedReflector : reflection_1.reflector; + } + Parser.prototype.parseAction = function(input, location) { + this._checkNoInterpolation(input, location); + var tokens = this._lexer.tokenize(input); + var ast = new _ParseAST(input, location, tokens, this._reflector, true).parseChain(); + return new ast_1.ASTWithSource(ast, input, location); + }; + Parser.prototype.parseBinding = function(input, location) { + var ast = this._parseBindingAst(input, location); + return new ast_1.ASTWithSource(ast, input, location); + }; + Parser.prototype.parseSimpleBinding = function(input, location) { + var ast = this._parseBindingAst(input, location); + if (!SimpleExpressionChecker.check(ast)) { + throw new ParseException('Host binding expression can only contain field access and constants', input, location); + } + return new ast_1.ASTWithSource(ast, input, location); + }; + Parser.prototype._parseBindingAst = function(input, location) { + var quote = this._parseQuote(input, location); + if (lang_1.isPresent(quote)) { + return quote; + } + this._checkNoInterpolation(input, location); + var tokens = this._lexer.tokenize(input); + return new _ParseAST(input, location, tokens, this._reflector, false).parseChain(); + }; + Parser.prototype._parseQuote = function(input, location) { + if (lang_1.isBlank(input)) + return null; + var prefixSeparatorIndex = input.indexOf(':'); + if (prefixSeparatorIndex == -1) + return null; + var prefix = input.substring(0, prefixSeparatorIndex).trim(); + if (!lexer_1.isIdentifier(prefix)) + return null; + var uninterpretedExpression = input.substring(prefixSeparatorIndex + 1); + return new ast_1.Quote(prefix, uninterpretedExpression, location); + }; + Parser.prototype.parseTemplateBindings = function(input, location) { + var tokens = this._lexer.tokenize(input); + return new _ParseAST(input, location, tokens, this._reflector, false).parseTemplateBindings(); + }; + Parser.prototype.parseInterpolation = function(input, location) { + var parts = lang_1.StringWrapper.split(input, INTERPOLATION_REGEXP); + if (parts.length <= 1) { + return null; + } + var strings = []; + var expressions = []; + for (var i = 0; i < parts.length; i++) { + var part = parts[i]; + if (i % 2 === 0) { + strings.push(part); + } else if (part.trim().length > 0) { + var tokens = this._lexer.tokenize(part); + var ast = new _ParseAST(input, location, tokens, this._reflector, false).parseChain(); + expressions.push(ast); + } else { + throw new ParseException('Blank expressions are not allowed in interpolated strings', input, "at column " + this._findInterpolationErrorColumn(parts, i) + " in", location); + } + } + return new ast_1.ASTWithSource(new ast_1.Interpolation(strings, expressions), input, location); + }; + Parser.prototype.wrapLiteralPrimitive = function(input, location) { + return new ast_1.ASTWithSource(new ast_1.LiteralPrimitive(input), input, location); + }; + Parser.prototype._checkNoInterpolation = function(input, location) { + var parts = lang_1.StringWrapper.split(input, INTERPOLATION_REGEXP); + if (parts.length > 1) { + throw new ParseException('Got interpolation ({{}}) where expression was expected', input, "at column " + this._findInterpolationErrorColumn(parts, 1) + " in", location); + } + }; + Parser.prototype._findInterpolationErrorColumn = function(parts, partInErrIdx) { + var errLocation = ''; + for (var j = 0; j < partInErrIdx; j++) { + errLocation += j % 2 === 0 ? parts[j] : "{{" + parts[j] + "}}"; + } + return errLocation.length; + }; + Parser = __decorate([decorators_1.Injectable(), __metadata('design:paramtypes', [lexer_1.Lexer, reflection_1.Reflector])], Parser); + return Parser; + })(); + exports.Parser = Parser; + var _ParseAST = (function() { + function _ParseAST(input, location, tokens, reflector, parseAction) { + this.input = input; + this.location = location; + this.tokens = tokens; + this.reflector = reflector; + this.parseAction = parseAction; + this.index = 0; + } + _ParseAST.prototype.peek = function(offset) { + var i = this.index + offset; + return i < this.tokens.length ? this.tokens[i] : lexer_1.EOF; + }; + Object.defineProperty(_ParseAST.prototype, "next", { + get: function() { + return this.peek(0); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(_ParseAST.prototype, "inputIndex", { + get: function() { + return (this.index < this.tokens.length) ? this.next.index : this.input.length; + }, + enumerable: true, + configurable: true + }); + _ParseAST.prototype.advance = function() { + this.index++; + }; + _ParseAST.prototype.optionalCharacter = function(code) { + if (this.next.isCharacter(code)) { + this.advance(); + return true; + } else { + return false; + } + }; + _ParseAST.prototype.optionalKeywordVar = function() { + if (this.peekKeywordVar()) { + this.advance(); + return true; + } else { + return false; + } + }; + _ParseAST.prototype.peekKeywordVar = function() { + return this.next.isKeywordVar() || this.next.isOperator('#'); + }; + _ParseAST.prototype.expectCharacter = function(code) { + if (this.optionalCharacter(code)) + return ; + this.error("Missing expected " + lang_1.StringWrapper.fromCharCode(code)); + }; + _ParseAST.prototype.optionalOperator = function(op) { + if (this.next.isOperator(op)) { + this.advance(); + return true; + } else { + return false; + } + }; + _ParseAST.prototype.expectOperator = function(operator) { + if (this.optionalOperator(operator)) + return ; + this.error("Missing expected operator " + operator); + }; + _ParseAST.prototype.expectIdentifierOrKeyword = function() { + var n = this.next; + if (!n.isIdentifier() && !n.isKeyword()) { + this.error("Unexpected token " + n + ", expected identifier or keyword"); + } + this.advance(); + return n.toString(); + }; + _ParseAST.prototype.expectIdentifierOrKeywordOrString = function() { + var n = this.next; + if (!n.isIdentifier() && !n.isKeyword() && !n.isString()) { + this.error("Unexpected token " + n + ", expected identifier, keyword, or string"); + } + this.advance(); + return n.toString(); + }; + _ParseAST.prototype.parseChain = function() { + var exprs = []; + while (this.index < this.tokens.length) { + var expr = this.parsePipe(); + exprs.push(expr); + if (this.optionalCharacter(lexer_1.$SEMICOLON)) { + if (!this.parseAction) { + this.error("Binding expression cannot contain chained expression"); + } + while (this.optionalCharacter(lexer_1.$SEMICOLON)) {} + } else if (this.index < this.tokens.length) { + this.error("Unexpected token '" + this.next + "'"); + } + } + if (exprs.length == 0) + return new ast_1.EmptyExpr(); + if (exprs.length == 1) + return exprs[0]; + return new ast_1.Chain(exprs); + }; + _ParseAST.prototype.parsePipe = function() { + var result = this.parseExpression(); + if (this.optionalOperator("|")) { + if (this.parseAction) { + this.error("Cannot have a pipe in an action expression"); + } + do { + var name = this.expectIdentifierOrKeyword(); + var args = []; + while (this.optionalCharacter(lexer_1.$COLON)) { + args.push(this.parseExpression()); + } + result = new ast_1.BindingPipe(result, name, args); + } while (this.optionalOperator("|")); + } + return result; + }; + _ParseAST.prototype.parseExpression = function() { + return this.parseConditional(); + }; + _ParseAST.prototype.parseConditional = function() { + var start = this.inputIndex; + var result = this.parseLogicalOr(); + if (this.optionalOperator('?')) { + var yes = this.parsePipe(); + if (!this.optionalCharacter(lexer_1.$COLON)) { + var end = this.inputIndex; + var expression = this.input.substring(start, end); + this.error("Conditional expression " + expression + " requires all 3 expressions"); + } + var no = this.parsePipe(); + return new ast_1.Conditional(result, yes, no); + } else { + return result; + } + }; + _ParseAST.prototype.parseLogicalOr = function() { + var result = this.parseLogicalAnd(); + while (this.optionalOperator('||')) { + result = new ast_1.Binary('||', result, this.parseLogicalAnd()); + } + return result; + }; + _ParseAST.prototype.parseLogicalAnd = function() { + var result = this.parseEquality(); + while (this.optionalOperator('&&')) { + result = new ast_1.Binary('&&', result, this.parseEquality()); + } + return result; + }; + _ParseAST.prototype.parseEquality = function() { + var result = this.parseRelational(); + while (true) { + if (this.optionalOperator('==')) { + result = new ast_1.Binary('==', result, this.parseRelational()); + } else if (this.optionalOperator('===')) { + result = new ast_1.Binary('===', result, this.parseRelational()); + } else if (this.optionalOperator('!=')) { + result = new ast_1.Binary('!=', result, this.parseRelational()); + } else if (this.optionalOperator('!==')) { + result = new ast_1.Binary('!==', result, this.parseRelational()); + } else { + return result; + } + } + }; + _ParseAST.prototype.parseRelational = function() { + var result = this.parseAdditive(); + while (true) { + if (this.optionalOperator('<')) { + result = new ast_1.Binary('<', result, this.parseAdditive()); + } else if (this.optionalOperator('>')) { + result = new ast_1.Binary('>', result, this.parseAdditive()); + } else if (this.optionalOperator('<=')) { + result = new ast_1.Binary('<=', result, this.parseAdditive()); + } else if (this.optionalOperator('>=')) { + result = new ast_1.Binary('>=', result, this.parseAdditive()); + } else { + return result; + } + } + }; + _ParseAST.prototype.parseAdditive = function() { + var result = this.parseMultiplicative(); + while (true) { + if (this.optionalOperator('+')) { + result = new ast_1.Binary('+', result, this.parseMultiplicative()); + } else if (this.optionalOperator('-')) { + result = new ast_1.Binary('-', result, this.parseMultiplicative()); + } else { + return result; + } + } + }; + _ParseAST.prototype.parseMultiplicative = function() { + var result = this.parsePrefix(); + while (true) { + if (this.optionalOperator('*')) { + result = new ast_1.Binary('*', result, this.parsePrefix()); + } else if (this.optionalOperator('%')) { + result = new ast_1.Binary('%', result, this.parsePrefix()); + } else if (this.optionalOperator('/')) { + result = new ast_1.Binary('/', result, this.parsePrefix()); + } else { + return result; + } + } + }; + _ParseAST.prototype.parsePrefix = function() { + if (this.optionalOperator('+')) { + return this.parsePrefix(); + } else if (this.optionalOperator('-')) { + return new ast_1.Binary('-', new ast_1.LiteralPrimitive(0), this.parsePrefix()); + } else if (this.optionalOperator('!')) { + return new ast_1.PrefixNot(this.parsePrefix()); + } else { + return this.parseCallChain(); + } + }; + _ParseAST.prototype.parseCallChain = function() { + var result = this.parsePrimary(); + while (true) { + if (this.optionalCharacter(lexer_1.$PERIOD)) { + result = this.parseAccessMemberOrMethodCall(result, false); + } else if (this.optionalOperator('?.')) { + result = this.parseAccessMemberOrMethodCall(result, true); + } else if (this.optionalCharacter(lexer_1.$LBRACKET)) { + var key = this.parsePipe(); + this.expectCharacter(lexer_1.$RBRACKET); + if (this.optionalOperator("=")) { + var value = this.parseConditional(); + result = new ast_1.KeyedWrite(result, key, value); + } else { + result = new ast_1.KeyedRead(result, key); + } + } else if (this.optionalCharacter(lexer_1.$LPAREN)) { + var args = this.parseCallArguments(); + this.expectCharacter(lexer_1.$RPAREN); + result = new ast_1.FunctionCall(result, args); + } else { + return result; + } + } + }; + _ParseAST.prototype.parsePrimary = function() { + if (this.optionalCharacter(lexer_1.$LPAREN)) { + var result = this.parsePipe(); + this.expectCharacter(lexer_1.$RPAREN); + return result; + } else if (this.next.isKeywordNull() || this.next.isKeywordUndefined()) { + this.advance(); + return new ast_1.LiteralPrimitive(null); + } else if (this.next.isKeywordTrue()) { + this.advance(); + return new ast_1.LiteralPrimitive(true); + } else if (this.next.isKeywordFalse()) { + this.advance(); + return new ast_1.LiteralPrimitive(false); + } else if (this.optionalCharacter(lexer_1.$LBRACKET)) { + var elements = this.parseExpressionList(lexer_1.$RBRACKET); + this.expectCharacter(lexer_1.$RBRACKET); + return new ast_1.LiteralArray(elements); + } else if (this.next.isCharacter(lexer_1.$LBRACE)) { + return this.parseLiteralMap(); + } else if (this.next.isIdentifier()) { + return this.parseAccessMemberOrMethodCall(_implicitReceiver, false); + } else if (this.next.isNumber()) { + var value = this.next.toNumber(); + this.advance(); + return new ast_1.LiteralPrimitive(value); + } else if (this.next.isString()) { + var literalValue = this.next.toString(); + this.advance(); + return new ast_1.LiteralPrimitive(literalValue); + } else if (this.index >= this.tokens.length) { + this.error("Unexpected end of expression: " + this.input); + } else { + this.error("Unexpected token " + this.next); + } + throw new exceptions_1.BaseException("Fell through all cases in parsePrimary"); + }; + _ParseAST.prototype.parseExpressionList = function(terminator) { + var result = []; + if (!this.next.isCharacter(terminator)) { + do { + result.push(this.parsePipe()); + } while (this.optionalCharacter(lexer_1.$COMMA)); + } + return result; + }; + _ParseAST.prototype.parseLiteralMap = function() { + var keys = []; + var values = []; + this.expectCharacter(lexer_1.$LBRACE); + if (!this.optionalCharacter(lexer_1.$RBRACE)) { + do { + var key = this.expectIdentifierOrKeywordOrString(); + keys.push(key); + this.expectCharacter(lexer_1.$COLON); + values.push(this.parsePipe()); + } while (this.optionalCharacter(lexer_1.$COMMA)); + this.expectCharacter(lexer_1.$RBRACE); + } + return new ast_1.LiteralMap(keys, values); + }; + _ParseAST.prototype.parseAccessMemberOrMethodCall = function(receiver, isSafe) { + if (isSafe === void 0) { + isSafe = false; + } + var id = this.expectIdentifierOrKeyword(); + if (this.optionalCharacter(lexer_1.$LPAREN)) { + var args = this.parseCallArguments(); + this.expectCharacter(lexer_1.$RPAREN); + var fn = this.reflector.method(id); + return isSafe ? new ast_1.SafeMethodCall(receiver, id, fn, args) : new ast_1.MethodCall(receiver, id, fn, args); + } else { + if (isSafe) { + if (this.optionalOperator("=")) { + this.error("The '?.' operator cannot be used in the assignment"); + } else { + return new ast_1.SafePropertyRead(receiver, id, this.reflector.getter(id)); + } + } else { + if (this.optionalOperator("=")) { + if (!this.parseAction) { + this.error("Bindings cannot contain assignments"); + } + var value = this.parseConditional(); + return new ast_1.PropertyWrite(receiver, id, this.reflector.setter(id), value); + } else { + return new ast_1.PropertyRead(receiver, id, this.reflector.getter(id)); + } + } + } + return null; + }; + _ParseAST.prototype.parseCallArguments = function() { + if (this.next.isCharacter(lexer_1.$RPAREN)) + return []; + var positionals = []; + do { + positionals.push(this.parsePipe()); + } while (this.optionalCharacter(lexer_1.$COMMA)); + return positionals; + }; + _ParseAST.prototype.parseBlockContent = function() { + if (!this.parseAction) { + this.error("Binding expression cannot contain chained expression"); + } + var exprs = []; + while (this.index < this.tokens.length && !this.next.isCharacter(lexer_1.$RBRACE)) { + var expr = this.parseExpression(); + exprs.push(expr); + if (this.optionalCharacter(lexer_1.$SEMICOLON)) { + while (this.optionalCharacter(lexer_1.$SEMICOLON)) {} + } + } + if (exprs.length == 0) + return new ast_1.EmptyExpr(); + if (exprs.length == 1) + return exprs[0]; + return new ast_1.Chain(exprs); + }; + _ParseAST.prototype.expectTemplateBindingKey = function() { + var result = ''; + var operatorFound = false; + do { + result += this.expectIdentifierOrKeywordOrString(); + operatorFound = this.optionalOperator('-'); + if (operatorFound) { + result += '-'; + } + } while (operatorFound); + return result.toString(); + }; + _ParseAST.prototype.parseTemplateBindings = function() { + var bindings = []; + var prefix = null; + while (this.index < this.tokens.length) { + var keyIsVar = this.optionalKeywordVar(); + var key = this.expectTemplateBindingKey(); + if (!keyIsVar) { + if (prefix == null) { + prefix = key; + } else { + key = prefix + key[0].toUpperCase() + key.substring(1); + } + } + this.optionalCharacter(lexer_1.$COLON); + var name = null; + var expression = null; + if (keyIsVar) { + if (this.optionalOperator("=")) { + name = this.expectTemplateBindingKey(); + } else { + name = '\$implicit'; + } + } else if (this.next !== lexer_1.EOF && !this.peekKeywordVar()) { + var start = this.inputIndex; + var ast = this.parsePipe(); + var source = this.input.substring(start, this.inputIndex); + expression = new ast_1.ASTWithSource(ast, source, this.location); + } + bindings.push(new ast_1.TemplateBinding(key, keyIsVar, name, expression)); + if (!this.optionalCharacter(lexer_1.$SEMICOLON)) { + this.optionalCharacter(lexer_1.$COMMA); + } + } + return bindings; + }; + _ParseAST.prototype.error = function(message, index) { + if (index === void 0) { + index = null; + } + if (lang_1.isBlank(index)) + index = this.index; + var location = (index < this.tokens.length) ? "at column " + (this.tokens[index].index + 1) + " in" : "at the end of the expression"; + throw new ParseException(message, this.input, location, this.location); + }; + return _ParseAST; + })(); + exports._ParseAST = _ParseAST; + var SimpleExpressionChecker = (function() { + function SimpleExpressionChecker() { + this.simple = true; + } + SimpleExpressionChecker.check = function(ast) { + var s = new SimpleExpressionChecker(); + ast.visit(s); + return s.simple; + }; + SimpleExpressionChecker.prototype.visitImplicitReceiver = function(ast) {}; + SimpleExpressionChecker.prototype.visitInterpolation = function(ast) { + this.simple = false; + }; + SimpleExpressionChecker.prototype.visitLiteralPrimitive = function(ast) {}; + SimpleExpressionChecker.prototype.visitPropertyRead = function(ast) {}; + SimpleExpressionChecker.prototype.visitPropertyWrite = function(ast) { + this.simple = false; + }; + SimpleExpressionChecker.prototype.visitSafePropertyRead = function(ast) { + this.simple = false; + }; + SimpleExpressionChecker.prototype.visitMethodCall = function(ast) { + this.simple = false; + }; + SimpleExpressionChecker.prototype.visitSafeMethodCall = function(ast) { + this.simple = false; + }; + SimpleExpressionChecker.prototype.visitFunctionCall = function(ast) { + this.simple = false; + }; + SimpleExpressionChecker.prototype.visitLiteralArray = function(ast) { + this.visitAll(ast.expressions); + }; + SimpleExpressionChecker.prototype.visitLiteralMap = function(ast) { + this.visitAll(ast.values); + }; + SimpleExpressionChecker.prototype.visitBinary = function(ast) { + this.simple = false; + }; + SimpleExpressionChecker.prototype.visitPrefixNot = function(ast) { + this.simple = false; + }; + SimpleExpressionChecker.prototype.visitConditional = function(ast) { + this.simple = false; + }; + SimpleExpressionChecker.prototype.visitPipe = function(ast) { + this.simple = false; + }; + SimpleExpressionChecker.prototype.visitKeyedRead = function(ast) { + this.simple = false; + }; + SimpleExpressionChecker.prototype.visitKeyedWrite = function(ast) { + this.simple = false; + }; + SimpleExpressionChecker.prototype.visitAll = function(asts) { + var res = collection_1.ListWrapper.createFixedSize(asts.length); + for (var i = 0; i < asts.length; ++i) { + res[i] = asts[i].visit(this); + } + return res; + }; + SimpleExpressionChecker.prototype.visitChain = function(ast) { + this.simple = false; + }; + SimpleExpressionChecker.prototype.visitQuote = function(ast) { + this.simple = false; + }; + return SimpleExpressionChecker; + })(); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/parser/locals", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var Locals = (function() { + function Locals(parent, current) { + this.parent = parent; + this.current = current; + } + Locals.prototype.contains = function(name) { + if (this.current.has(name)) { + return true; + } + if (lang_1.isPresent(this.parent)) { + return this.parent.contains(name); + } + return false; + }; + Locals.prototype.get = function(name) { + if (this.current.has(name)) { + return this.current.get(name); + } + if (lang_1.isPresent(this.parent)) { + return this.parent.get(name); + } + throw new exceptions_1.BaseException("Cannot find '" + name + "'"); + }; + Locals.prototype.set = function(name, value) { + if (this.current.has(name)) { + this.current.set(name, value); + } else { + throw new exceptions_1.BaseException("Setting of new keys post-construction is not supported. Key: " + name + "."); + } + }; + Locals.prototype.clearValues = function() { + collection_1.MapWrapper.clearValues(this.current); + }; + return Locals; + })(); + exports.Locals = Locals; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/exceptions", ["angular2/src/facade/exceptions"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var exceptions_1 = require("angular2/src/facade/exceptions"); + var ExpressionChangedAfterItHasBeenCheckedException = (function(_super) { + __extends(ExpressionChangedAfterItHasBeenCheckedException, _super); + function ExpressionChangedAfterItHasBeenCheckedException(exp, oldValue, currValue, context) { + _super.call(this, ("Expression '" + exp + "' has changed after it was checked. ") + ("Previous value: '" + oldValue + "'. Current value: '" + currValue + "'")); + } + return ExpressionChangedAfterItHasBeenCheckedException; + })(exceptions_1.BaseException); + exports.ExpressionChangedAfterItHasBeenCheckedException = ExpressionChangedAfterItHasBeenCheckedException; + var ChangeDetectionError = (function(_super) { + __extends(ChangeDetectionError, _super); + function ChangeDetectionError(exp, originalException, originalStack, context) { + _super.call(this, originalException + " in [" + exp + "]", originalException, originalStack, context); + this.location = exp; + } + return ChangeDetectionError; + })(exceptions_1.WrappedException); + exports.ChangeDetectionError = ChangeDetectionError; + var DehydratedException = (function(_super) { + __extends(DehydratedException, _super); + function DehydratedException() { + _super.call(this, 'Attempt to detect changes on a dehydrated detector.'); + } + return DehydratedException; + })(exceptions_1.BaseException); + exports.DehydratedException = DehydratedException; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/interfaces", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var DebugContext = (function() { + function DebugContext(element, componentElement, directive, context, locals, injector) { + this.element = element; + this.componentElement = componentElement; + this.directive = directive; + this.context = context; + this.locals = locals; + this.injector = injector; + } + return DebugContext; + })(); + exports.DebugContext = DebugContext; + var ChangeDetectorGenConfig = (function() { + function ChangeDetectorGenConfig(genDebugInfo, logBindingUpdate, useJit) { + this.genDebugInfo = genDebugInfo; + this.logBindingUpdate = logBindingUpdate; + this.useJit = useJit; + } + return ChangeDetectorGenConfig; + })(); + exports.ChangeDetectorGenConfig = ChangeDetectorGenConfig; + var ChangeDetectorDefinition = (function() { + function ChangeDetectorDefinition(id, strategy, variableNames, bindingRecords, eventRecords, directiveRecords, genConfig) { + this.id = id; + this.strategy = strategy; + this.variableNames = variableNames; + this.bindingRecords = bindingRecords; + this.eventRecords = eventRecords; + this.directiveRecords = directiveRecords; + this.genConfig = genConfig; + } + return ChangeDetectorDefinition; + })(); + exports.ChangeDetectorDefinition = ChangeDetectorDefinition; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/constants", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + (function(ChangeDetectorState) { + ChangeDetectorState[ChangeDetectorState["NeverChecked"] = 0] = "NeverChecked"; + ChangeDetectorState[ChangeDetectorState["CheckedBefore"] = 1] = "CheckedBefore"; + ChangeDetectorState[ChangeDetectorState["Errored"] = 2] = "Errored"; + })(exports.ChangeDetectorState || (exports.ChangeDetectorState = {})); + var ChangeDetectorState = exports.ChangeDetectorState; + (function(ChangeDetectionStrategy) { + ChangeDetectionStrategy[ChangeDetectionStrategy["CheckOnce"] = 0] = "CheckOnce"; + ChangeDetectionStrategy[ChangeDetectionStrategy["Checked"] = 1] = "Checked"; + ChangeDetectionStrategy[ChangeDetectionStrategy["CheckAlways"] = 2] = "CheckAlways"; + ChangeDetectionStrategy[ChangeDetectionStrategy["Detached"] = 3] = "Detached"; + ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 4] = "OnPush"; + ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 5] = "Default"; + ChangeDetectionStrategy[ChangeDetectionStrategy["OnPushObserve"] = 6] = "OnPushObserve"; + })(exports.ChangeDetectionStrategy || (exports.ChangeDetectionStrategy = {})); + var ChangeDetectionStrategy = exports.ChangeDetectionStrategy; + exports.CHANGE_DETECTION_STRATEGY_VALUES = [ChangeDetectionStrategy.CheckOnce, ChangeDetectionStrategy.Checked, ChangeDetectionStrategy.CheckAlways, ChangeDetectionStrategy.Detached, ChangeDetectionStrategy.OnPush, ChangeDetectionStrategy.Default, ChangeDetectionStrategy.OnPushObserve]; + exports.CHANGE_DETECTOR_STATE_VALUES = [ChangeDetectorState.NeverChecked, ChangeDetectorState.CheckedBefore, ChangeDetectorState.Errored]; + function isDefaultChangeDetectionStrategy(changeDetectionStrategy) { + return lang_1.isBlank(changeDetectionStrategy) || changeDetectionStrategy === ChangeDetectionStrategy.Default; + } + exports.isDefaultChangeDetectionStrategy = isDefaultChangeDetectionStrategy; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/pipe_lifecycle_reflector", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function implementsOnDestroy(pipe) { + return pipe.constructor.prototype.ngOnDestroy; + } + exports.implementsOnDestroy = implementsOnDestroy; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/binding_record", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var DIRECTIVE_LIFECYCLE = "directiveLifecycle"; + var BINDING = "native"; + var DIRECTIVE = "directive"; + var ELEMENT_PROPERTY = "elementProperty"; + var ELEMENT_ATTRIBUTE = "elementAttribute"; + var ELEMENT_CLASS = "elementClass"; + var ELEMENT_STYLE = "elementStyle"; + var TEXT_NODE = "textNode"; + var EVENT = "event"; + var HOST_EVENT = "hostEvent"; + var BindingTarget = (function() { + function BindingTarget(mode, elementIndex, name, unit, debug) { + this.mode = mode; + this.elementIndex = elementIndex; + this.name = name; + this.unit = unit; + this.debug = debug; + } + BindingTarget.prototype.isDirective = function() { + return this.mode === DIRECTIVE; + }; + BindingTarget.prototype.isElementProperty = function() { + return this.mode === ELEMENT_PROPERTY; + }; + BindingTarget.prototype.isElementAttribute = function() { + return this.mode === ELEMENT_ATTRIBUTE; + }; + BindingTarget.prototype.isElementClass = function() { + return this.mode === ELEMENT_CLASS; + }; + BindingTarget.prototype.isElementStyle = function() { + return this.mode === ELEMENT_STYLE; + }; + BindingTarget.prototype.isTextNode = function() { + return this.mode === TEXT_NODE; + }; + return BindingTarget; + })(); + exports.BindingTarget = BindingTarget; + var BindingRecord = (function() { + function BindingRecord(mode, target, implicitReceiver, ast, setter, lifecycleEvent, directiveRecord) { + this.mode = mode; + this.target = target; + this.implicitReceiver = implicitReceiver; + this.ast = ast; + this.setter = setter; + this.lifecycleEvent = lifecycleEvent; + this.directiveRecord = directiveRecord; + } + BindingRecord.prototype.isDirectiveLifecycle = function() { + return this.mode === DIRECTIVE_LIFECYCLE; + }; + BindingRecord.prototype.callOnChanges = function() { + return lang_1.isPresent(this.directiveRecord) && this.directiveRecord.callOnChanges; + }; + BindingRecord.prototype.isDefaultChangeDetection = function() { + return lang_1.isBlank(this.directiveRecord) || this.directiveRecord.isDefaultChangeDetection(); + }; + BindingRecord.createDirectiveDoCheck = function(directiveRecord) { + return new BindingRecord(DIRECTIVE_LIFECYCLE, null, 0, null, null, "DoCheck", directiveRecord); + }; + BindingRecord.createDirectiveOnInit = function(directiveRecord) { + return new BindingRecord(DIRECTIVE_LIFECYCLE, null, 0, null, null, "OnInit", directiveRecord); + }; + BindingRecord.createDirectiveOnChanges = function(directiveRecord) { + return new BindingRecord(DIRECTIVE_LIFECYCLE, null, 0, null, null, "OnChanges", directiveRecord); + }; + BindingRecord.createForDirective = function(ast, propertyName, setter, directiveRecord) { + var elementIndex = directiveRecord.directiveIndex.elementIndex; + var t = new BindingTarget(DIRECTIVE, elementIndex, propertyName, null, ast.toString()); + return new BindingRecord(DIRECTIVE, t, 0, ast, setter, null, directiveRecord); + }; + BindingRecord.createForElementProperty = function(ast, elementIndex, propertyName) { + var t = new BindingTarget(ELEMENT_PROPERTY, elementIndex, propertyName, null, ast.toString()); + return new BindingRecord(BINDING, t, 0, ast, null, null, null); + }; + BindingRecord.createForElementAttribute = function(ast, elementIndex, attributeName) { + var t = new BindingTarget(ELEMENT_ATTRIBUTE, elementIndex, attributeName, null, ast.toString()); + return new BindingRecord(BINDING, t, 0, ast, null, null, null); + }; + BindingRecord.createForElementClass = function(ast, elementIndex, className) { + var t = new BindingTarget(ELEMENT_CLASS, elementIndex, className, null, ast.toString()); + return new BindingRecord(BINDING, t, 0, ast, null, null, null); + }; + BindingRecord.createForElementStyle = function(ast, elementIndex, styleName, unit) { + var t = new BindingTarget(ELEMENT_STYLE, elementIndex, styleName, unit, ast.toString()); + return new BindingRecord(BINDING, t, 0, ast, null, null, null); + }; + BindingRecord.createForHostProperty = function(directiveIndex, ast, propertyName) { + var t = new BindingTarget(ELEMENT_PROPERTY, directiveIndex.elementIndex, propertyName, null, ast.toString()); + return new BindingRecord(BINDING, t, directiveIndex, ast, null, null, null); + }; + BindingRecord.createForHostAttribute = function(directiveIndex, ast, attributeName) { + var t = new BindingTarget(ELEMENT_ATTRIBUTE, directiveIndex.elementIndex, attributeName, null, ast.toString()); + return new BindingRecord(BINDING, t, directiveIndex, ast, null, null, null); + }; + BindingRecord.createForHostClass = function(directiveIndex, ast, className) { + var t = new BindingTarget(ELEMENT_CLASS, directiveIndex.elementIndex, className, null, ast.toString()); + return new BindingRecord(BINDING, t, directiveIndex, ast, null, null, null); + }; + BindingRecord.createForHostStyle = function(directiveIndex, ast, styleName, unit) { + var t = new BindingTarget(ELEMENT_STYLE, directiveIndex.elementIndex, styleName, unit, ast.toString()); + return new BindingRecord(BINDING, t, directiveIndex, ast, null, null, null); + }; + BindingRecord.createForTextNode = function(ast, elementIndex) { + var t = new BindingTarget(TEXT_NODE, elementIndex, null, null, ast.toString()); + return new BindingRecord(BINDING, t, 0, ast, null, null, null); + }; + BindingRecord.createForEvent = function(ast, eventName, elementIndex) { + var t = new BindingTarget(EVENT, elementIndex, eventName, null, ast.toString()); + return new BindingRecord(EVENT, t, 0, ast, null, null, null); + }; + BindingRecord.createForHostEvent = function(ast, eventName, directiveRecord) { + var directiveIndex = directiveRecord.directiveIndex; + var t = new BindingTarget(HOST_EVENT, directiveIndex.elementIndex, eventName, null, ast.toString()); + return new BindingRecord(HOST_EVENT, t, directiveIndex, ast, null, null, directiveRecord); + }; + return BindingRecord; + })(); + exports.BindingRecord = BindingRecord; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/directive_record", ["angular2/src/facade/lang", "angular2/src/core/change_detection/constants"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var constants_1 = require("angular2/src/core/change_detection/constants"); + var DirectiveIndex = (function() { + function DirectiveIndex(elementIndex, directiveIndex) { + this.elementIndex = elementIndex; + this.directiveIndex = directiveIndex; + } + Object.defineProperty(DirectiveIndex.prototype, "name", { + get: function() { + return this.elementIndex + "_" + this.directiveIndex; + }, + enumerable: true, + configurable: true + }); + return DirectiveIndex; + })(); + exports.DirectiveIndex = DirectiveIndex; + var DirectiveRecord = (function() { + function DirectiveRecord(_a) { + var _b = _a === void 0 ? {} : _a, + directiveIndex = _b.directiveIndex, + callAfterContentInit = _b.callAfterContentInit, + callAfterContentChecked = _b.callAfterContentChecked, + callAfterViewInit = _b.callAfterViewInit, + callAfterViewChecked = _b.callAfterViewChecked, + callOnChanges = _b.callOnChanges, + callDoCheck = _b.callDoCheck, + callOnInit = _b.callOnInit, + changeDetection = _b.changeDetection; + this.directiveIndex = directiveIndex; + this.callAfterContentInit = lang_1.normalizeBool(callAfterContentInit); + this.callAfterContentChecked = lang_1.normalizeBool(callAfterContentChecked); + this.callOnChanges = lang_1.normalizeBool(callOnChanges); + this.callAfterViewInit = lang_1.normalizeBool(callAfterViewInit); + this.callAfterViewChecked = lang_1.normalizeBool(callAfterViewChecked); + this.callDoCheck = lang_1.normalizeBool(callDoCheck); + this.callOnInit = lang_1.normalizeBool(callOnInit); + this.changeDetection = changeDetection; + } + DirectiveRecord.prototype.isDefaultChangeDetection = function() { + return constants_1.isDefaultChangeDetectionStrategy(this.changeDetection); + }; + return DirectiveRecord; + })(); + exports.DirectiveRecord = DirectiveRecord; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/change_detector_ref", ["angular2/src/core/change_detection/constants"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var constants_1 = require("angular2/src/core/change_detection/constants"); + var ChangeDetectorRef = (function() { + function ChangeDetectorRef() {} + return ChangeDetectorRef; + })(); + exports.ChangeDetectorRef = ChangeDetectorRef; + var ChangeDetectorRef_ = (function(_super) { + __extends(ChangeDetectorRef_, _super); + function ChangeDetectorRef_(_cd) { + _super.call(this); + this._cd = _cd; + } + ChangeDetectorRef_.prototype.markForCheck = function() { + this._cd.markPathToRootAsCheckOnce(); + }; + ChangeDetectorRef_.prototype.detach = function() { + this._cd.mode = constants_1.ChangeDetectionStrategy.Detached; + }; + ChangeDetectorRef_.prototype.detectChanges = function() { + this._cd.detectChanges(); + }; + ChangeDetectorRef_.prototype.checkNoChanges = function() { + this._cd.checkNoChanges(); + }; + ChangeDetectorRef_.prototype.reattach = function() { + this._cd.mode = constants_1.ChangeDetectionStrategy.CheckAlways; + this.markForCheck(); + }; + return ChangeDetectorRef_; + })(ChangeDetectorRef); + exports.ChangeDetectorRef_ = ChangeDetectorRef_; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/observable_facade", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function isObservable(value) { + return false; + } + exports.isObservable = isObservable; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/proto_record", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + (function(RecordType) { + RecordType[RecordType["Self"] = 0] = "Self"; + RecordType[RecordType["Const"] = 1] = "Const"; + RecordType[RecordType["PrimitiveOp"] = 2] = "PrimitiveOp"; + RecordType[RecordType["PropertyRead"] = 3] = "PropertyRead"; + RecordType[RecordType["PropertyWrite"] = 4] = "PropertyWrite"; + RecordType[RecordType["Local"] = 5] = "Local"; + RecordType[RecordType["InvokeMethod"] = 6] = "InvokeMethod"; + RecordType[RecordType["InvokeClosure"] = 7] = "InvokeClosure"; + RecordType[RecordType["KeyedRead"] = 8] = "KeyedRead"; + RecordType[RecordType["KeyedWrite"] = 9] = "KeyedWrite"; + RecordType[RecordType["Pipe"] = 10] = "Pipe"; + RecordType[RecordType["Interpolate"] = 11] = "Interpolate"; + RecordType[RecordType["SafeProperty"] = 12] = "SafeProperty"; + RecordType[RecordType["CollectionLiteral"] = 13] = "CollectionLiteral"; + RecordType[RecordType["SafeMethodInvoke"] = 14] = "SafeMethodInvoke"; + RecordType[RecordType["DirectiveLifecycle"] = 15] = "DirectiveLifecycle"; + RecordType[RecordType["Chain"] = 16] = "Chain"; + RecordType[RecordType["SkipRecordsIf"] = 17] = "SkipRecordsIf"; + RecordType[RecordType["SkipRecordsIfNot"] = 18] = "SkipRecordsIfNot"; + RecordType[RecordType["SkipRecords"] = 19] = "SkipRecords"; + })(exports.RecordType || (exports.RecordType = {})); + var RecordType = exports.RecordType; + var ProtoRecord = (function() { + function ProtoRecord(mode, name, funcOrValue, args, fixedArgs, contextIndex, directiveIndex, selfIndex, bindingRecord, lastInBinding, lastInDirective, argumentToPureFunction, referencedBySelf, propertyBindingIndex) { + this.mode = mode; + this.name = name; + this.funcOrValue = funcOrValue; + this.args = args; + this.fixedArgs = fixedArgs; + this.contextIndex = contextIndex; + this.directiveIndex = directiveIndex; + this.selfIndex = selfIndex; + this.bindingRecord = bindingRecord; + this.lastInBinding = lastInBinding; + this.lastInDirective = lastInDirective; + this.argumentToPureFunction = argumentToPureFunction; + this.referencedBySelf = referencedBySelf; + this.propertyBindingIndex = propertyBindingIndex; + } + ProtoRecord.prototype.isPureFunction = function() { + return this.mode === RecordType.Interpolate || this.mode === RecordType.CollectionLiteral; + }; + ProtoRecord.prototype.isUsedByOtherRecord = function() { + return !this.lastInBinding || this.referencedBySelf; + }; + ProtoRecord.prototype.shouldBeChecked = function() { + return this.argumentToPureFunction || this.lastInBinding || this.isPureFunction() || this.isPipeRecord(); + }; + ProtoRecord.prototype.isPipeRecord = function() { + return this.mode === RecordType.Pipe; + }; + ProtoRecord.prototype.isConditionalSkipRecord = function() { + return this.mode === RecordType.SkipRecordsIfNot || this.mode === RecordType.SkipRecordsIf; + }; + ProtoRecord.prototype.isUnconditionalSkipRecord = function() { + return this.mode === RecordType.SkipRecords; + }; + ProtoRecord.prototype.isSkipRecord = function() { + return this.isConditionalSkipRecord() || this.isUnconditionalSkipRecord(); + }; + ProtoRecord.prototype.isLifeCycleRecord = function() { + return this.mode === RecordType.DirectiveLifecycle; + }; + return ProtoRecord; + })(); + exports.ProtoRecord = ProtoRecord; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/event_binding", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var EventBinding = (function() { + function EventBinding(eventName, elIndex, dirIndex, records) { + this.eventName = eventName; + this.elIndex = elIndex; + this.dirIndex = dirIndex; + this.records = records; + } + return EventBinding; + })(); + exports.EventBinding = EventBinding; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/coalesce", ["angular2/src/facade/lang", "angular2/src/facade/collection", "angular2/src/core/change_detection/proto_record"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var collection_1 = require("angular2/src/facade/collection"); + var proto_record_1 = require("angular2/src/core/change_detection/proto_record"); + function coalesce(srcRecords) { + var dstRecords = []; + var excludedIdxs = []; + var indexMap = new collection_1.Map(); + var skipDepth = 0; + var skipSources = collection_1.ListWrapper.createFixedSize(srcRecords.length); + for (var protoIndex = 0; protoIndex < srcRecords.length; protoIndex++) { + var skipRecord = skipSources[protoIndex]; + if (lang_1.isPresent(skipRecord)) { + skipDepth--; + skipRecord.fixedArgs[0] = dstRecords.length; + } + var src = srcRecords[protoIndex]; + var dst = _cloneAndUpdateIndexes(src, dstRecords, indexMap); + if (dst.isSkipRecord()) { + dstRecords.push(dst); + skipDepth++; + skipSources[dst.fixedArgs[0]] = dst; + } else { + var record = _mayBeAddRecord(dst, dstRecords, excludedIdxs, skipDepth > 0); + indexMap.set(src.selfIndex, record.selfIndex); + } + } + return _optimizeSkips(dstRecords); + } + exports.coalesce = coalesce; + function _optimizeSkips(srcRecords) { + var dstRecords = []; + var skipSources = collection_1.ListWrapper.createFixedSize(srcRecords.length); + var indexMap = new collection_1.Map(); + for (var protoIndex = 0; protoIndex < srcRecords.length; protoIndex++) { + var skipRecord = skipSources[protoIndex]; + if (lang_1.isPresent(skipRecord)) { + skipRecord.fixedArgs[0] = dstRecords.length; + } + var src = srcRecords[protoIndex]; + if (src.isSkipRecord()) { + if (src.isConditionalSkipRecord() && src.fixedArgs[0] === protoIndex + 2 && protoIndex < srcRecords.length - 1 && srcRecords[protoIndex + 1].mode === proto_record_1.RecordType.SkipRecords) { + src.mode = src.mode === proto_record_1.RecordType.SkipRecordsIf ? proto_record_1.RecordType.SkipRecordsIfNot : proto_record_1.RecordType.SkipRecordsIf; + src.fixedArgs[0] = srcRecords[protoIndex + 1].fixedArgs[0]; + protoIndex++; + } + if (src.fixedArgs[0] > protoIndex + 1) { + var dst = _cloneAndUpdateIndexes(src, dstRecords, indexMap); + dstRecords.push(dst); + skipSources[dst.fixedArgs[0]] = dst; + } + } else { + var dst = _cloneAndUpdateIndexes(src, dstRecords, indexMap); + dstRecords.push(dst); + indexMap.set(src.selfIndex, dst.selfIndex); + } + } + return dstRecords; + } + function _mayBeAddRecord(record, dstRecords, excludedIdxs, excluded) { + var match = _findFirstMatch(record, dstRecords, excludedIdxs); + if (lang_1.isPresent(match)) { + if (record.lastInBinding) { + dstRecords.push(_createSelfRecord(record, match.selfIndex, dstRecords.length + 1)); + match.referencedBySelf = true; + } else { + if (record.argumentToPureFunction) { + match.argumentToPureFunction = true; + } + } + return match; + } + if (excluded) { + excludedIdxs.push(record.selfIndex); + } + dstRecords.push(record); + return record; + } + function _findFirstMatch(record, dstRecords, excludedIdxs) { + return dstRecords.find(function(rr) { + return excludedIdxs.indexOf(rr.selfIndex) == -1 && rr.mode !== proto_record_1.RecordType.DirectiveLifecycle && _haveSameDirIndex(rr, record) && rr.mode === record.mode && lang_1.looseIdentical(rr.funcOrValue, record.funcOrValue) && rr.contextIndex === record.contextIndex && lang_1.looseIdentical(rr.name, record.name) && collection_1.ListWrapper.equals(rr.args, record.args); + }); + } + function _cloneAndUpdateIndexes(record, dstRecords, indexMap) { + var args = record.args.map(function(src) { + return _srcToDstSelfIndex(indexMap, src); + }); + var contextIndex = _srcToDstSelfIndex(indexMap, record.contextIndex); + var selfIndex = dstRecords.length + 1; + return new proto_record_1.ProtoRecord(record.mode, record.name, record.funcOrValue, args, record.fixedArgs, contextIndex, record.directiveIndex, selfIndex, record.bindingRecord, record.lastInBinding, record.lastInDirective, record.argumentToPureFunction, record.referencedBySelf, record.propertyBindingIndex); + } + function _srcToDstSelfIndex(indexMap, srcIdx) { + var dstIdx = indexMap.get(srcIdx); + return lang_1.isPresent(dstIdx) ? dstIdx : srcIdx; + } + function _createSelfRecord(r, contextIndex, selfIndex) { + return new proto_record_1.ProtoRecord(proto_record_1.RecordType.Self, "self", null, [], r.fixedArgs, contextIndex, r.directiveIndex, selfIndex, r.bindingRecord, r.lastInBinding, r.lastInDirective, false, false, r.propertyBindingIndex); + } + function _haveSameDirIndex(a, b) { + var di1 = lang_1.isBlank(a.directiveIndex) ? null : a.directiveIndex.directiveIndex; + var ei1 = lang_1.isBlank(a.directiveIndex) ? null : a.directiveIndex.elementIndex; + var di2 = lang_1.isBlank(b.directiveIndex) ? null : b.directiveIndex.directiveIndex; + var ei2 = lang_1.isBlank(b.directiveIndex) ? null : b.directiveIndex.elementIndex; + return di1 === di2 && ei1 === ei2; + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/codegen_name_util", ["angular2/src/facade/lang", "angular2/src/facade/collection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var collection_1 = require("angular2/src/facade/collection"); + var _STATE_ACCESSOR = "state"; + var _CONTEXT_ACCESSOR = "context"; + var _PROP_BINDING_INDEX = "propertyBindingIndex"; + var _DIRECTIVES_ACCESSOR = "directiveIndices"; + var _DISPATCHER_ACCESSOR = "dispatcher"; + var _LOCALS_ACCESSOR = "locals"; + var _MODE_ACCESSOR = "mode"; + var _PIPES_ACCESSOR = "pipes"; + var _PROTOS_ACCESSOR = "protos"; + exports.CONTEXT_ACCESSOR = "context"; + exports.CONTEXT_INDEX = 0; + var _FIELD_PREFIX = 'this.'; + var _whiteSpaceRegExp = /\W/g; + function sanitizeName(s) { + return lang_1.StringWrapper.replaceAll(s, _whiteSpaceRegExp, ''); + } + exports.sanitizeName = sanitizeName; + var CodegenNameUtil = (function() { + function CodegenNameUtil(_records, _eventBindings, _directiveRecords, _utilName) { + this._records = _records; + this._eventBindings = _eventBindings; + this._directiveRecords = _directiveRecords; + this._utilName = _utilName; + this._sanitizedEventNames = new collection_1.Map(); + this._sanitizedNames = collection_1.ListWrapper.createFixedSize(this._records.length + 1); + this._sanitizedNames[exports.CONTEXT_INDEX] = exports.CONTEXT_ACCESSOR; + for (var i = 0, + iLen = this._records.length; i < iLen; ++i) { + this._sanitizedNames[i + 1] = sanitizeName("" + this._records[i].name + i); + } + for (var ebIndex = 0; ebIndex < _eventBindings.length; ++ebIndex) { + var eb = _eventBindings[ebIndex]; + var names = [exports.CONTEXT_ACCESSOR]; + for (var i = 0, + iLen = eb.records.length; i < iLen; ++i) { + names.push(sanitizeName("" + eb.records[i].name + i + "_" + ebIndex)); + } + this._sanitizedEventNames.set(eb, names); + } + } + CodegenNameUtil.prototype._addFieldPrefix = function(name) { + return "" + _FIELD_PREFIX + name; + }; + CodegenNameUtil.prototype.getDispatcherName = function() { + return this._addFieldPrefix(_DISPATCHER_ACCESSOR); + }; + CodegenNameUtil.prototype.getPipesAccessorName = function() { + return this._addFieldPrefix(_PIPES_ACCESSOR); + }; + CodegenNameUtil.prototype.getProtosName = function() { + return this._addFieldPrefix(_PROTOS_ACCESSOR); + }; + CodegenNameUtil.prototype.getDirectivesAccessorName = function() { + return this._addFieldPrefix(_DIRECTIVES_ACCESSOR); + }; + CodegenNameUtil.prototype.getLocalsAccessorName = function() { + return this._addFieldPrefix(_LOCALS_ACCESSOR); + }; + CodegenNameUtil.prototype.getStateName = function() { + return this._addFieldPrefix(_STATE_ACCESSOR); + }; + CodegenNameUtil.prototype.getModeName = function() { + return this._addFieldPrefix(_MODE_ACCESSOR); + }; + CodegenNameUtil.prototype.getPropertyBindingIndex = function() { + return this._addFieldPrefix(_PROP_BINDING_INDEX); + }; + CodegenNameUtil.prototype.getLocalName = function(idx) { + return "l_" + this._sanitizedNames[idx]; + }; + CodegenNameUtil.prototype.getEventLocalName = function(eb, idx) { + return "l_" + this._sanitizedEventNames.get(eb)[idx]; + }; + CodegenNameUtil.prototype.getChangeName = function(idx) { + return "c_" + this._sanitizedNames[idx]; + }; + CodegenNameUtil.prototype.genInitLocals = function() { + var declarations = []; + var assignments = []; + for (var i = 0, + iLen = this.getFieldCount(); i < iLen; ++i) { + if (i == exports.CONTEXT_INDEX) { + declarations.push(this.getLocalName(i) + " = " + this.getFieldName(i)); + } else { + var rec = this._records[i - 1]; + if (rec.argumentToPureFunction) { + var changeName = this.getChangeName(i); + declarations.push(this.getLocalName(i) + "," + changeName); + assignments.push(changeName); + } else { + declarations.push("" + this.getLocalName(i)); + } + } + } + var assignmentsCode = collection_1.ListWrapper.isEmpty(assignments) ? '' : assignments.join('=') + " = false;"; + return "var " + declarations.join(',') + ";" + assignmentsCode; + }; + CodegenNameUtil.prototype.genInitEventLocals = function() { + var _this = this; + var res = [(this.getLocalName(exports.CONTEXT_INDEX) + " = " + this.getFieldName(exports.CONTEXT_INDEX))]; + this._sanitizedEventNames.forEach(function(names, eb) { + for (var i = 0; i < names.length; ++i) { + if (i !== exports.CONTEXT_INDEX) { + res.push("" + _this.getEventLocalName(eb, i)); + } + } + }); + return res.length > 1 ? "var " + res.join(',') + ";" : ''; + }; + CodegenNameUtil.prototype.getPreventDefaultAccesor = function() { + return "preventDefault"; + }; + CodegenNameUtil.prototype.getFieldCount = function() { + return this._sanitizedNames.length; + }; + CodegenNameUtil.prototype.getFieldName = function(idx) { + return this._addFieldPrefix(this._sanitizedNames[idx]); + }; + CodegenNameUtil.prototype.getAllFieldNames = function() { + var fieldList = []; + for (var k = 0, + kLen = this.getFieldCount(); k < kLen; ++k) { + if (k === 0 || this._records[k - 1].shouldBeChecked()) { + fieldList.push(this.getFieldName(k)); + } + } + for (var i = 0, + iLen = this._records.length; i < iLen; ++i) { + var rec = this._records[i]; + if (rec.isPipeRecord()) { + fieldList.push(this.getPipeName(rec.selfIndex)); + } + } + for (var j = 0, + jLen = this._directiveRecords.length; j < jLen; ++j) { + var dRec = this._directiveRecords[j]; + fieldList.push(this.getDirectiveName(dRec.directiveIndex)); + if (!dRec.isDefaultChangeDetection()) { + fieldList.push(this.getDetectorName(dRec.directiveIndex)); + } + } + return fieldList; + }; + CodegenNameUtil.prototype.genDehydrateFields = function() { + var fields = this.getAllFieldNames(); + collection_1.ListWrapper.removeAt(fields, exports.CONTEXT_INDEX); + if (collection_1.ListWrapper.isEmpty(fields)) + return ''; + fields.push(this._utilName + ".uninitialized;"); + return fields.join(' = '); + }; + CodegenNameUtil.prototype.genPipeOnDestroy = function() { + var _this = this; + return this._records.filter(function(r) { + return r.isPipeRecord(); + }).map(function(r) { + return (_this._utilName + ".callPipeOnDestroy(" + _this.getPipeName(r.selfIndex) + ");"); + }).join('\n'); + }; + CodegenNameUtil.prototype.getPipeName = function(idx) { + return this._addFieldPrefix(this._sanitizedNames[idx] + "_pipe"); + }; + CodegenNameUtil.prototype.getDirectiveName = function(d) { + return this._addFieldPrefix("directive_" + d.name); + }; + CodegenNameUtil.prototype.getDetectorName = function(d) { + return this._addFieldPrefix("detector_" + d.name); + }; + return CodegenNameUtil; + })(); + exports.CodegenNameUtil = CodegenNameUtil; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/codegen_facade", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function codify(obj) { + return JSON.stringify(obj); + } + exports.codify = codify; + function rawString(str) { + return "'" + str + "'"; + } + exports.rawString = rawString; + function combineGeneratedStrings(vals) { + return vals.join(' + '); + } + exports.combineGeneratedStrings = combineGeneratedStrings; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/metadata/view", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + (function(ViewEncapsulation) { + ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated"; + ViewEncapsulation[ViewEncapsulation["Native"] = 1] = "Native"; + ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None"; + })(exports.ViewEncapsulation || (exports.ViewEncapsulation = {})); + var ViewEncapsulation = exports.ViewEncapsulation; + exports.VIEW_ENCAPSULATION_VALUES = [ViewEncapsulation.Emulated, ViewEncapsulation.Native, ViewEncapsulation.None]; + var ViewMetadata = (function() { + function ViewMetadata(_a) { + var _b = _a === void 0 ? {} : _a, + templateUrl = _b.templateUrl, + template = _b.template, + directives = _b.directives, + pipes = _b.pipes, + encapsulation = _b.encapsulation, + styles = _b.styles, + styleUrls = _b.styleUrls; + this.templateUrl = templateUrl; + this.template = template; + this.styleUrls = styleUrls; + this.styles = styles; + this.directives = directives; + this.pipes = pipes; + this.encapsulation = encapsulation; + } + ViewMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object])], ViewMetadata); + return ViewMetadata; + })(); + exports.ViewMetadata = ViewMetadata; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/util", ["angular2/src/core/util/decorators"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var decorators_1 = require("angular2/src/core/util/decorators"); + exports.Class = decorators_1.Class; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/prod_mode", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + exports.enableProdMode = lang_1.enableProdMode; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/facade/promise", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var PromiseWrapper = (function() { + function PromiseWrapper() {} + PromiseWrapper.resolve = function(obj) { + return Promise.resolve(obj); + }; + PromiseWrapper.reject = function(obj, _) { + return Promise.reject(obj); + }; + PromiseWrapper.catchError = function(promise, onError) { + return promise.catch(onError); + }; + PromiseWrapper.all = function(promises) { + if (promises.length == 0) + return Promise.resolve([]); + return Promise.all(promises); + }; + PromiseWrapper.then = function(promise, success, rejection) { + return promise.then(success, rejection); + }; + PromiseWrapper.wrap = function(computation) { + return new Promise(function(res, rej) { + try { + res(computation()); + } catch (e) { + rej(e); + } + }); + }; + PromiseWrapper.scheduleMicrotask = function(computation) { + PromiseWrapper.then(PromiseWrapper.resolve(null), computation, function(_) {}); + }; + PromiseWrapper.isPromise = function(obj) { + return obj instanceof Promise; + }; + PromiseWrapper.completer = function() { + var resolve; + var reject; + var p = new Promise(function(res, rej) { + resolve = res; + reject = rej; + }); + return { + promise: p, + resolve: resolve, + reject: reject + }; + }; + return PromiseWrapper; + })(); + exports.PromiseWrapper = PromiseWrapper; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/zone/ng_zone", ["angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/facade/async", "angular2/src/core/profile/profile"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var async_1 = require("angular2/src/facade/async"); + var profile_1 = require("angular2/src/core/profile/profile"); + var NgZoneError = (function() { + function NgZoneError(error, stackTrace) { + this.error = error; + this.stackTrace = stackTrace; + } + return NgZoneError; + })(); + exports.NgZoneError = NgZoneError; + var NgZone = (function() { + function NgZone(_a) { + var enableLongStackTrace = _a.enableLongStackTrace; + this._runScope = profile_1.wtfCreateScope("NgZone#run()"); + this._microtaskScope = profile_1.wtfCreateScope("NgZone#microtask()"); + this._pendingMicrotasks = 0; + this._hasExecutedCodeInInnerZone = false; + this._nestedRun = 0; + this._inVmTurnDone = false; + this._pendingTimeouts = []; + if (lang_1.global.zone) { + this._disabled = false; + this._mountZone = lang_1.global.zone; + this._innerZone = this._createInnerZone(this._mountZone, enableLongStackTrace); + } else { + this._disabled = true; + this._mountZone = null; + } + this._onTurnStartEvents = new async_1.EventEmitter(false); + this._onTurnDoneEvents = new async_1.EventEmitter(false); + this._onEventDoneEvents = new async_1.EventEmitter(false); + this._onErrorEvents = new async_1.EventEmitter(false); + } + NgZone.prototype.overrideOnTurnStart = function(onTurnStartHook) { + this._onTurnStart = lang_1.normalizeBlank(onTurnStartHook); + }; + Object.defineProperty(NgZone.prototype, "onTurnStart", { + get: function() { + return this._onTurnStartEvents; + }, + enumerable: true, + configurable: true + }); + NgZone.prototype._notifyOnTurnStart = function(parentRun) { + var _this = this; + parentRun.call(this._innerZone, function() { + _this._onTurnStartEvents.emit(null); + }); + }; + NgZone.prototype.overrideOnTurnDone = function(onTurnDoneHook) { + this._onTurnDone = lang_1.normalizeBlank(onTurnDoneHook); + }; + Object.defineProperty(NgZone.prototype, "onTurnDone", { + get: function() { + return this._onTurnDoneEvents; + }, + enumerable: true, + configurable: true + }); + NgZone.prototype._notifyOnTurnDone = function(parentRun) { + var _this = this; + parentRun.call(this._innerZone, function() { + _this._onTurnDoneEvents.emit(null); + }); + }; + NgZone.prototype.overrideOnEventDone = function(onEventDoneFn, opt_waitForAsync) { + var _this = this; + if (opt_waitForAsync === void 0) { + opt_waitForAsync = false; + } + var normalizedOnEventDone = lang_1.normalizeBlank(onEventDoneFn); + if (opt_waitForAsync) { + this._onEventDone = function() { + if (!_this._pendingTimeouts.length) { + normalizedOnEventDone(); + } + }; + } else { + this._onEventDone = normalizedOnEventDone; + } + }; + Object.defineProperty(NgZone.prototype, "onEventDone", { + get: function() { + return this._onEventDoneEvents; + }, + enumerable: true, + configurable: true + }); + NgZone.prototype._notifyOnEventDone = function() { + var _this = this; + this.runOutsideAngular(function() { + _this._onEventDoneEvents.emit(null); + }); + }; + Object.defineProperty(NgZone.prototype, "hasPendingMicrotasks", { + get: function() { + return this._pendingMicrotasks > 0; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgZone.prototype, "hasPendingTimers", { + get: function() { + return this._pendingTimeouts.length > 0; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgZone.prototype, "hasPendingAsyncTasks", { + get: function() { + return this.hasPendingMicrotasks || this.hasPendingTimers; + }, + enumerable: true, + configurable: true + }); + NgZone.prototype.overrideOnErrorHandler = function(errorHandler) { + this._onErrorHandler = lang_1.normalizeBlank(errorHandler); + }; + Object.defineProperty(NgZone.prototype, "onError", { + get: function() { + return this._onErrorEvents; + }, + enumerable: true, + configurable: true + }); + NgZone.prototype.run = function(fn) { + if (this._disabled) { + return fn(); + } else { + var s = this._runScope(); + try { + return this._innerZone.run(fn); + } finally { + profile_1.wtfLeave(s); + } + } + }; + NgZone.prototype.runOutsideAngular = function(fn) { + if (this._disabled) { + return fn(); + } else { + return this._mountZone.run(fn); + } + }; + NgZone.prototype._createInnerZone = function(zone, enableLongStackTrace) { + var microtaskScope = this._microtaskScope; + var ngZone = this; + var errorHandling; + if (enableLongStackTrace) { + errorHandling = collection_1.StringMapWrapper.merge(Zone.longStackTraceZone, {onError: function(e) { + ngZone._notifyOnError(this, e); + }}); + } else { + errorHandling = {onError: function(e) { + ngZone._notifyOnError(this, e); + }}; + } + return zone.fork(errorHandling).fork({ + '$run': function(parentRun) { + return function() { + try { + ngZone._nestedRun++; + if (!ngZone._hasExecutedCodeInInnerZone) { + ngZone._hasExecutedCodeInInnerZone = true; + ngZone._notifyOnTurnStart(parentRun); + if (ngZone._onTurnStart) { + parentRun.call(ngZone._innerZone, ngZone._onTurnStart); + } + } + return parentRun.apply(this, arguments); + } finally { + ngZone._nestedRun--; + if (ngZone._pendingMicrotasks == 0 && ngZone._nestedRun == 0 && !this._inVmTurnDone) { + if (ngZone._hasExecutedCodeInInnerZone) { + try { + this._inVmTurnDone = true; + ngZone._notifyOnTurnDone(parentRun); + if (ngZone._onTurnDone) { + parentRun.call(ngZone._innerZone, ngZone._onTurnDone); + } + } finally { + this._inVmTurnDone = false; + ngZone._hasExecutedCodeInInnerZone = false; + } + } + if (ngZone._pendingMicrotasks === 0) { + ngZone._notifyOnEventDone(); + if (lang_1.isPresent(ngZone._onEventDone)) { + ngZone.runOutsideAngular(ngZone._onEventDone); + } + } + } + } + }; + }, + '$scheduleMicrotask': function(parentScheduleMicrotask) { + return function(fn) { + ngZone._pendingMicrotasks++; + var microtask = function() { + var s = microtaskScope(); + try { + fn(); + } finally { + ngZone._pendingMicrotasks--; + profile_1.wtfLeave(s); + } + }; + parentScheduleMicrotask.call(this, microtask); + }; + }, + '$setTimeout': function(parentSetTimeout) { + return function(fn, delay) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var id; + var cb = function() { + fn(); + collection_1.ListWrapper.remove(ngZone._pendingTimeouts, id); + }; + id = parentSetTimeout(cb, delay, args); + ngZone._pendingTimeouts.push(id); + return id; + }; + }, + '$clearTimeout': function(parentClearTimeout) { + return function(id) { + parentClearTimeout(id); + collection_1.ListWrapper.remove(ngZone._pendingTimeouts, id); + }; + }, + _innerZone: true + }); + }; + NgZone.prototype._notifyOnError = function(zone, e) { + if (lang_1.isPresent(this._onErrorHandler) || async_1.ObservableWrapper.hasSubscribers(this._onErrorEvents)) { + var trace = [lang_1.normalizeBlank(e.stack)]; + while (zone && zone.constructedAtException) { + trace.push(zone.constructedAtException.get()); + zone = zone.parent; + } + if (async_1.ObservableWrapper.hasSubscribers(this._onErrorEvents)) { + async_1.ObservableWrapper.callEmit(this._onErrorEvents, new NgZoneError(e, trace)); + } + if (lang_1.isPresent(this._onErrorHandler)) { + this._onErrorHandler(e, trace); + } + } else { + console.log('## _notifyOnError ##'); + console.log(e.stack); + throw e; + } + }; + return NgZone; + })(); + exports.NgZone = NgZone; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/application_tokens", ["angular2/src/core/di", "angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var di_1 = require("angular2/src/core/di"); + var lang_1 = require("angular2/src/facade/lang"); + exports.APP_COMPONENT_REF_PROMISE = lang_1.CONST_EXPR(new di_1.OpaqueToken('Promise')); + exports.APP_COMPONENT = lang_1.CONST_EXPR(new di_1.OpaqueToken('AppComponent')); + exports.APP_ID = lang_1.CONST_EXPR(new di_1.OpaqueToken('AppId')); + function _appIdRandomProviderFactory() { + return "" + _randomChar() + _randomChar() + _randomChar(); + } + exports.APP_ID_RANDOM_PROVIDER = lang_1.CONST_EXPR(new di_1.Provider(exports.APP_ID, { + useFactory: _appIdRandomProviderFactory, + deps: [] + })); + function _randomChar() { + return lang_1.StringWrapper.fromCharCode(97 + lang_1.Math.floor(lang_1.Math.random() * 25)); + } + exports.PLATFORM_INITIALIZER = lang_1.CONST_EXPR(new di_1.OpaqueToken("Platform Initializer")); + exports.APP_INITIALIZER = lang_1.CONST_EXPR(new di_1.OpaqueToken("Application Initializer")); + exports.PACKAGE_ROOT_URL = lang_1.CONST_EXPR(new di_1.OpaqueToken("Application Packages Root URL")); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/testability/testability", ["angular2/src/core/di", "angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/core/zone/ng_zone", "angular2/src/facade/async"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var di_1 = require("angular2/src/core/di"); + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var ng_zone_1 = require("angular2/src/core/zone/ng_zone"); + var async_1 = require("angular2/src/facade/async"); + var Testability = (function() { + function Testability(_ngZone) { + this._pendingCount = 0; + this._callbacks = []; + this._isAngularEventPending = false; + this._watchAngularEvents(_ngZone); + } + Testability.prototype._watchAngularEvents = function(_ngZone) { + var _this = this; + async_1.ObservableWrapper.subscribe(_ngZone.onTurnStart, function(_) { + _this._isAngularEventPending = true; + }); + _ngZone.runOutsideAngular(function() { + async_1.ObservableWrapper.subscribe(_ngZone.onEventDone, function(_) { + if (!_ngZone.hasPendingTimers) { + _this._isAngularEventPending = false; + _this._runCallbacksIfReady(); + } + }); + }); + }; + Testability.prototype.increasePendingRequestCount = function() { + this._pendingCount += 1; + return this._pendingCount; + }; + Testability.prototype.decreasePendingRequestCount = function() { + this._pendingCount -= 1; + if (this._pendingCount < 0) { + throw new exceptions_1.BaseException('pending async requests below zero'); + } + this._runCallbacksIfReady(); + return this._pendingCount; + }; + Testability.prototype.isStable = function() { + return this._pendingCount == 0 && !this._isAngularEventPending; + }; + Testability.prototype._runCallbacksIfReady = function() { + var _this = this; + if (!this.isStable()) { + return ; + } + async_1.PromiseWrapper.resolve(null).then(function(_) { + while (_this._callbacks.length !== 0) { + (_this._callbacks.pop())(); + } + }); + }; + Testability.prototype.whenStable = function(callback) { + this._callbacks.push(callback); + this._runCallbacksIfReady(); + }; + Testability.prototype.getPendingRequestCount = function() { + return this._pendingCount; + }; + Testability.prototype.isAngularEventPending = function() { + return this._isAngularEventPending; + }; + Testability.prototype.findBindings = function(using, provider, exactMatch) { + return []; + }; + Testability.prototype.findProviders = function(using, provider, exactMatch) { + return []; + }; + Testability = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [ng_zone_1.NgZone])], Testability); + return Testability; + })(); + exports.Testability = Testability; + var TestabilityRegistry = (function() { + function TestabilityRegistry() { + this._applications = new collection_1.Map(); + _testabilityGetter.addToWindow(this); + } + TestabilityRegistry.prototype.registerApplication = function(token, testability) { + this._applications.set(token, testability); + }; + TestabilityRegistry.prototype.getTestability = function(elem) { + return this._applications.get(elem); + }; + TestabilityRegistry.prototype.getAllTestabilities = function() { + return collection_1.MapWrapper.values(this._applications); + }; + TestabilityRegistry.prototype.findTestabilityInTree = function(elem, findInAncestors) { + if (findInAncestors === void 0) { + findInAncestors = true; + } + return _testabilityGetter.findTestabilityInTree(this, elem, findInAncestors); + }; + TestabilityRegistry = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], TestabilityRegistry); + return TestabilityRegistry; + })(); + exports.TestabilityRegistry = TestabilityRegistry; + var _NoopGetTestability = (function() { + function _NoopGetTestability() {} + _NoopGetTestability.prototype.addToWindow = function(registry) {}; + _NoopGetTestability.prototype.findTestabilityInTree = function(registry, elem, findInAncestors) { + return null; + }; + _NoopGetTestability = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [])], _NoopGetTestability); + return _NoopGetTestability; + })(); + function setTestabilityGetter(getter) { + _testabilityGetter = getter; + } + exports.setTestabilityGetter = setTestabilityGetter; + var _testabilityGetter = lang_1.CONST_EXPR(new _NoopGetTestability()); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/render/api", ["angular2/src/facade/exceptions"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var exceptions_1 = require("angular2/src/facade/exceptions"); + var RenderProtoViewRef = (function() { + function RenderProtoViewRef() {} + return RenderProtoViewRef; + })(); + exports.RenderProtoViewRef = RenderProtoViewRef; + var RenderFragmentRef = (function() { + function RenderFragmentRef() {} + return RenderFragmentRef; + })(); + exports.RenderFragmentRef = RenderFragmentRef; + var RenderViewRef = (function() { + function RenderViewRef() {} + return RenderViewRef; + })(); + exports.RenderViewRef = RenderViewRef; + var RenderTemplateCmd = (function() { + function RenderTemplateCmd() {} + return RenderTemplateCmd; + })(); + exports.RenderTemplateCmd = RenderTemplateCmd; + var RenderBeginCmd = (function(_super) { + __extends(RenderBeginCmd, _super); + function RenderBeginCmd() { + _super.apply(this, arguments); + } + Object.defineProperty(RenderBeginCmd.prototype, "ngContentIndex", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + Object.defineProperty(RenderBeginCmd.prototype, "isBound", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + return RenderBeginCmd; + })(RenderTemplateCmd); + exports.RenderBeginCmd = RenderBeginCmd; + var RenderTextCmd = (function(_super) { + __extends(RenderTextCmd, _super); + function RenderTextCmd() { + _super.apply(this, arguments); + } + Object.defineProperty(RenderTextCmd.prototype, "value", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + return RenderTextCmd; + })(RenderBeginCmd); + exports.RenderTextCmd = RenderTextCmd; + var RenderNgContentCmd = (function(_super) { + __extends(RenderNgContentCmd, _super); + function RenderNgContentCmd() { + _super.apply(this, arguments); + } + Object.defineProperty(RenderNgContentCmd.prototype, "index", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + Object.defineProperty(RenderNgContentCmd.prototype, "ngContentIndex", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + return RenderNgContentCmd; + })(RenderTemplateCmd); + exports.RenderNgContentCmd = RenderNgContentCmd; + var RenderBeginElementCmd = (function(_super) { + __extends(RenderBeginElementCmd, _super); + function RenderBeginElementCmd() { + _super.apply(this, arguments); + } + Object.defineProperty(RenderBeginElementCmd.prototype, "name", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + Object.defineProperty(RenderBeginElementCmd.prototype, "attrNameAndValues", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + Object.defineProperty(RenderBeginElementCmd.prototype, "eventTargetAndNames", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + return RenderBeginElementCmd; + })(RenderBeginCmd); + exports.RenderBeginElementCmd = RenderBeginElementCmd; + var RenderBeginComponentCmd = (function(_super) { + __extends(RenderBeginComponentCmd, _super); + function RenderBeginComponentCmd() { + _super.apply(this, arguments); + } + Object.defineProperty(RenderBeginComponentCmd.prototype, "templateId", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + return RenderBeginComponentCmd; + })(RenderBeginElementCmd); + exports.RenderBeginComponentCmd = RenderBeginComponentCmd; + var RenderEmbeddedTemplateCmd = (function(_super) { + __extends(RenderEmbeddedTemplateCmd, _super); + function RenderEmbeddedTemplateCmd() { + _super.apply(this, arguments); + } + Object.defineProperty(RenderEmbeddedTemplateCmd.prototype, "isMerged", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + Object.defineProperty(RenderEmbeddedTemplateCmd.prototype, "children", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + return RenderEmbeddedTemplateCmd; + })(RenderBeginElementCmd); + exports.RenderEmbeddedTemplateCmd = RenderEmbeddedTemplateCmd; + var RenderViewWithFragments = (function() { + function RenderViewWithFragments(viewRef, fragmentRefs) { + this.viewRef = viewRef; + this.fragmentRefs = fragmentRefs; + } + return RenderViewWithFragments; + })(); + exports.RenderViewWithFragments = RenderViewWithFragments; + var RenderComponentTemplate = (function() { + function RenderComponentTemplate(id, shortId, encapsulation, commands, styles) { + this.id = id; + this.shortId = shortId; + this.encapsulation = encapsulation; + this.commands = commands; + this.styles = styles; + } + return RenderComponentTemplate; + })(); + exports.RenderComponentTemplate = RenderComponentTemplate; + var Renderer = (function() { + function Renderer() {} + return Renderer; + })(); + exports.Renderer = Renderer; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/pipes/pipe_provider", ["angular2/src/core/di/provider", "angular2/src/core/di"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var provider_1 = require("angular2/src/core/di/provider"); + var di_1 = require("angular2/src/core/di"); + var PipeProvider = (function(_super) { + __extends(PipeProvider, _super); + function PipeProvider(name, pure, key, resolvedFactories, multiBinding) { + _super.call(this, key, resolvedFactories, multiBinding); + this.name = name; + this.pure = pure; + } + PipeProvider.createFromType = function(type, metadata) { + var provider = new di_1.Provider(type, {useClass: type}); + var rb = provider_1.resolveProvider(provider); + return new PipeProvider(metadata.name, metadata.pure, rb.key, rb.resolvedFactories, rb.multiProvider); + }; + return PipeProvider; + })(provider_1.ResolvedProvider_); + exports.PipeProvider = PipeProvider; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/pipes", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var SelectedPipe = (function() { + function SelectedPipe(pipe, pure) { + this.pipe = pipe; + this.pure = pure; + } + return SelectedPipe; + })(); + exports.SelectedPipe = SelectedPipe; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/view_ref", ["angular2/src/facade/lang", "angular2/src/facade/exceptions"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + function internalView(viewRef) { + return viewRef._view; + } + exports.internalView = internalView; + function internalProtoView(protoViewRef) { + return lang_1.isPresent(protoViewRef) ? protoViewRef._protoView : null; + } + exports.internalProtoView = internalProtoView; + var ViewRef = (function() { + function ViewRef() {} + Object.defineProperty(ViewRef.prototype, "changeDetectorRef", { + get: function() { + return exceptions_1.unimplemented(); + }, + set: function(value) { + exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + return ViewRef; + })(); + exports.ViewRef = ViewRef; + var ViewRef_ = (function(_super) { + __extends(ViewRef_, _super); + function ViewRef_(_view) { + _super.call(this); + this._changeDetectorRef = null; + this._view = _view; + } + Object.defineProperty(ViewRef_.prototype, "render", { + get: function() { + return this._view.render; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ViewRef_.prototype, "renderFragment", { + get: function() { + return this._view.renderFragment; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ViewRef_.prototype, "changeDetectorRef", { + get: function() { + if (this._changeDetectorRef === null) { + this._changeDetectorRef = this._view.changeDetector.ref; + } + return this._changeDetectorRef; + }, + enumerable: true, + configurable: true + }); + ViewRef_.prototype.setLocal = function(variableName, value) { + this._view.setLocal(variableName, value); + }; + return ViewRef_; + })(ViewRef); + exports.ViewRef_ = ViewRef_; + var ProtoViewRef = (function() { + function ProtoViewRef() {} + return ProtoViewRef; + })(); + exports.ProtoViewRef = ProtoViewRef; + var ProtoViewRef_ = (function(_super) { + __extends(ProtoViewRef_, _super); + function ProtoViewRef_(_protoView) { + _super.call(this); + this._protoView = _protoView; + } + return ProtoViewRef_; + })(ProtoViewRef); + exports.ProtoViewRef_ = ProtoViewRef_; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/render/util", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var CAMEL_CASE_REGEXP = /([A-Z])/g; + var DASH_CASE_REGEXP = /-([a-z])/g; + function camelCaseToDashCase(input) { + return lang_1.StringWrapper.replaceAllMapped(input, CAMEL_CASE_REGEXP, function(m) { + return '-' + m[1].toLowerCase(); + }); + } + exports.camelCaseToDashCase = camelCaseToDashCase; + function dashCaseToCamelCase(input) { + return lang_1.StringWrapper.replaceAllMapped(input, DASH_CASE_REGEXP, function(m) { + return m[1].toUpperCase(); + }); + } + exports.dashCaseToCamelCase = dashCaseToCamelCase; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/element_binder", ["angular2/src/facade/lang", "angular2/src/facade/exceptions"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var ElementBinder = (function() { + function ElementBinder(index, parent, distanceToParent, protoElementInjector, componentDirective, nestedProtoView) { + this.index = index; + this.parent = parent; + this.distanceToParent = distanceToParent; + this.protoElementInjector = protoElementInjector; + this.componentDirective = componentDirective; + this.nestedProtoView = nestedProtoView; + if (lang_1.isBlank(index)) { + throw new exceptions_1.BaseException('null index not allowed.'); + } + } + return ElementBinder; + })(); + exports.ElementBinder = ElementBinder; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/element_ref", ["angular2/src/facade/exceptions"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var exceptions_1 = require("angular2/src/facade/exceptions"); + var ElementRef = (function() { + function ElementRef() {} + Object.defineProperty(ElementRef.prototype, "nativeElement", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + Object.defineProperty(ElementRef.prototype, "renderView", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + return ElementRef; + })(); + exports.ElementRef = ElementRef; + var ElementRef_ = (function(_super) { + __extends(ElementRef_, _super); + function ElementRef_(parentView, boundElementIndex, _renderer) { + _super.call(this); + this.parentView = parentView; + this.boundElementIndex = boundElementIndex; + this._renderer = _renderer; + } + Object.defineProperty(ElementRef_.prototype, "renderView", { + get: function() { + return this.parentView.render; + }, + set: function(value) { + exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ElementRef_.prototype, "nativeElement", { + get: function() { + return this._renderer.getNativeElementSync(this); + }, + enumerable: true, + configurable: true + }); + return ElementRef_; + })(ElementRef); + exports.ElementRef_ = ElementRef_; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/template_ref", ["angular2/src/core/linker/view_ref"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var view_ref_1 = require("angular2/src/core/linker/view_ref"); + var TemplateRef = (function() { + function TemplateRef() {} + return TemplateRef; + })(); + exports.TemplateRef = TemplateRef; + var TemplateRef_ = (function(_super) { + __extends(TemplateRef_, _super); + function TemplateRef_(elementRef) { + _super.call(this); + this.elementRef = elementRef; + } + TemplateRef_.prototype._getProtoView = function() { + var elementRef = this.elementRef; + var parentView = view_ref_1.internalView(elementRef.parentView); + return parentView.proto.elementBinders[elementRef.boundElementIndex - parentView.elementOffset].nestedProtoView; + }; + Object.defineProperty(TemplateRef_.prototype, "protoViewRef", { + get: function() { + return this._getProtoView().ref; + }, + enumerable: true, + configurable: true + }); + TemplateRef_.prototype.hasLocal = function(name) { + return this._getProtoView().templateVariableBindings.has(name); + }; + return TemplateRef_; + })(TemplateRef); + exports.TemplateRef_ = TemplateRef_; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/view_pool", ["angular2/src/core/di", "angular2/src/facade/lang", "angular2/src/facade/collection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var di_1 = require("angular2/src/core/di"); + var lang_1 = require("angular2/src/facade/lang"); + var collection_1 = require("angular2/src/facade/collection"); + exports.APP_VIEW_POOL_CAPACITY = lang_1.CONST_EXPR(new di_1.OpaqueToken('AppViewPool.viewPoolCapacity')); + var AppViewPool = (function() { + function AppViewPool(poolCapacityPerProtoView) { + this._pooledViewsPerProtoView = new collection_1.Map(); + this._poolCapacityPerProtoView = poolCapacityPerProtoView; + } + AppViewPool.prototype.getView = function(protoView) { + var pooledViews = this._pooledViewsPerProtoView.get(protoView); + if (lang_1.isPresent(pooledViews) && pooledViews.length > 0) { + return pooledViews.pop(); + } + return null; + }; + AppViewPool.prototype.returnView = function(view) { + var protoView = view.proto; + var pooledViews = this._pooledViewsPerProtoView.get(protoView); + if (lang_1.isBlank(pooledViews)) { + pooledViews = []; + this._pooledViewsPerProtoView.set(protoView, pooledViews); + } + var haveRemainingCapacity = pooledViews.length < this._poolCapacityPerProtoView; + if (haveRemainingCapacity) { + pooledViews.push(view); + } + return haveRemainingCapacity; + }; + AppViewPool = __decorate([di_1.Injectable(), __param(0, di_1.Inject(exports.APP_VIEW_POOL_CAPACITY)), __metadata('design:paramtypes', [Object])], AppViewPool); + return AppViewPool; + })(); + exports.AppViewPool = AppViewPool; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/view_listener", ["angular2/src/core/di"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var di_1 = require("angular2/src/core/di"); + var AppViewListener = (function() { + function AppViewListener() {} + AppViewListener.prototype.onViewCreated = function(view) {}; + AppViewListener.prototype.onViewDestroyed = function(view) {}; + AppViewListener = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], AppViewListener); + return AppViewListener; + })(); + exports.AppViewListener = AppViewListener; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/view_container_ref", ["angular2/src/facade/collection", "angular2/src/facade/exceptions", "angular2/src/facade/lang", "angular2/src/core/linker/view_ref"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var collection_1 = require("angular2/src/facade/collection"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var lang_1 = require("angular2/src/facade/lang"); + var view_ref_1 = require("angular2/src/core/linker/view_ref"); + var ViewContainerRef = (function() { + function ViewContainerRef() {} + ViewContainerRef.prototype.clear = function() { + for (var i = this.length - 1; i >= 0; i--) { + this.remove(i); + } + }; + Object.defineProperty(ViewContainerRef.prototype, "length", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + return ViewContainerRef; + })(); + exports.ViewContainerRef = ViewContainerRef; + var ViewContainerRef_ = (function(_super) { + __extends(ViewContainerRef_, _super); + function ViewContainerRef_(viewManager, element) { + _super.call(this); + this.viewManager = viewManager; + this.element = element; + } + ViewContainerRef_.prototype._getViews = function() { + var element = this.element; + var vc = view_ref_1.internalView(element.parentView).viewContainers[element.boundElementIndex]; + return lang_1.isPresent(vc) ? vc.views : []; + }; + ViewContainerRef_.prototype.get = function(index) { + return this._getViews()[index].ref; + }; + Object.defineProperty(ViewContainerRef_.prototype, "length", { + get: function() { + return this._getViews().length; + }, + enumerable: true, + configurable: true + }); + ViewContainerRef_.prototype.createEmbeddedView = function(templateRef, index) { + if (index === void 0) { + index = -1; + } + if (index == -1) + index = this.length; + return this.viewManager.createEmbeddedViewInContainer(this.element, index, templateRef); + }; + ViewContainerRef_.prototype.createHostView = function(protoViewRef, index, dynamicallyCreatedProviders) { + if (protoViewRef === void 0) { + protoViewRef = null; + } + if (index === void 0) { + index = -1; + } + if (dynamicallyCreatedProviders === void 0) { + dynamicallyCreatedProviders = null; + } + if (index == -1) + index = this.length; + return this.viewManager.createHostViewInContainer(this.element, index, protoViewRef, dynamicallyCreatedProviders); + }; + ViewContainerRef_.prototype.insert = function(viewRef, index) { + if (index === void 0) { + index = -1; + } + if (index == -1) + index = this.length; + return this.viewManager.attachViewInContainer(this.element, index, viewRef); + }; + ViewContainerRef_.prototype.indexOf = function(viewRef) { + return collection_1.ListWrapper.indexOf(this._getViews(), view_ref_1.internalView(viewRef)); + }; + ViewContainerRef_.prototype.remove = function(index) { + if (index === void 0) { + index = -1; + } + if (index == -1) + index = this.length - 1; + this.viewManager.destroyViewInContainer(this.element, index); + }; + ViewContainerRef_.prototype.detach = function(index) { + if (index === void 0) { + index = -1; + } + if (index == -1) + index = this.length - 1; + return this.viewManager.detachViewInContainer(this.element, index); + }; + return ViewContainerRef_; + })(ViewContainerRef); + exports.ViewContainerRef_ = ViewContainerRef_; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/interfaces", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + (function(LifecycleHooks) { + LifecycleHooks[LifecycleHooks["OnInit"] = 0] = "OnInit"; + LifecycleHooks[LifecycleHooks["OnDestroy"] = 1] = "OnDestroy"; + LifecycleHooks[LifecycleHooks["DoCheck"] = 2] = "DoCheck"; + LifecycleHooks[LifecycleHooks["OnChanges"] = 3] = "OnChanges"; + LifecycleHooks[LifecycleHooks["AfterContentInit"] = 4] = "AfterContentInit"; + LifecycleHooks[LifecycleHooks["AfterContentChecked"] = 5] = "AfterContentChecked"; + LifecycleHooks[LifecycleHooks["AfterViewInit"] = 6] = "AfterViewInit"; + LifecycleHooks[LifecycleHooks["AfterViewChecked"] = 7] = "AfterViewChecked"; + })(exports.LifecycleHooks || (exports.LifecycleHooks = {})); + var LifecycleHooks = exports.LifecycleHooks; + exports.LIFECYCLE_HOOKS_VALUES = [LifecycleHooks.OnInit, LifecycleHooks.OnDestroy, LifecycleHooks.DoCheck, LifecycleHooks.OnChanges, LifecycleHooks.AfterContentInit, LifecycleHooks.AfterContentChecked, LifecycleHooks.AfterViewInit, LifecycleHooks.AfterViewChecked]; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/query_list", ["angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/facade/async"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var async_1 = require("angular2/src/facade/async"); + var QueryList = (function() { + function QueryList() { + this._results = []; + this._emitter = new async_1.EventEmitter(); + } + Object.defineProperty(QueryList.prototype, "changes", { + get: function() { + return this._emitter; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(QueryList.prototype, "length", { + get: function() { + return this._results.length; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(QueryList.prototype, "first", { + get: function() { + return collection_1.ListWrapper.first(this._results); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(QueryList.prototype, "last", { + get: function() { + return collection_1.ListWrapper.last(this._results); + }, + enumerable: true, + configurable: true + }); + QueryList.prototype.map = function(fn) { + return this._results.map(fn); + }; + QueryList.prototype.filter = function(fn) { + return this._results.filter(fn); + }; + QueryList.prototype.reduce = function(fn, init) { + return this._results.reduce(fn, init); + }; + QueryList.prototype.toArray = function() { + return collection_1.ListWrapper.clone(this._results); + }; + QueryList.prototype[lang_1.getSymbolIterator()] = function() { + return this._results[lang_1.getSymbolIterator()](); + }; + QueryList.prototype.toString = function() { + return this._results.toString(); + }; + QueryList.prototype.reset = function(res) { + this._results = res; + }; + QueryList.prototype.notifyOnChanges = function() { + this._emitter.emit(this); + }; + return QueryList; + })(); + exports.QueryList = QueryList; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/event_config", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + exports.EVENT_TARGET_SEPARATOR = ':'; + var EventConfig = (function() { + function EventConfig(fieldName, eventName, isLongForm) { + this.fieldName = fieldName; + this.eventName = eventName; + this.isLongForm = isLongForm; + } + EventConfig.parse = function(eventConfig) { + var fieldName = eventConfig, + eventName = eventConfig, + isLongForm = false; + var separatorIdx = eventConfig.indexOf(exports.EVENT_TARGET_SEPARATOR); + if (separatorIdx > -1) { + fieldName = eventConfig.substring(0, separatorIdx).trim(); + eventName = eventConfig.substring(separatorIdx + 1).trim(); + isLongForm = true; + } + return new EventConfig(fieldName, eventName, isLongForm); + }; + EventConfig.prototype.getFullName = function() { + return this.isLongForm ? "" + this.fieldName + exports.EVENT_TARGET_SEPARATOR + this.eventName : this.eventName; + }; + return EventConfig; + })(); + exports.EventConfig = EventConfig; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/directive_resolver", ["angular2/src/core/di", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/core/metadata", "angular2/src/core/reflection/reflection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var di_1 = require("angular2/src/core/di"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var metadata_1 = require("angular2/src/core/metadata"); + var reflection_1 = require("angular2/src/core/reflection/reflection"); + function _isDirectiveMetadata(type) { + return type instanceof metadata_1.DirectiveMetadata; + } + var DirectiveResolver = (function() { + function DirectiveResolver() {} + DirectiveResolver.prototype.resolve = function(type) { + var typeMetadata = reflection_1.reflector.annotations(di_1.resolveForwardRef(type)); + if (lang_1.isPresent(typeMetadata)) { + var metadata = typeMetadata.find(_isDirectiveMetadata); + if (lang_1.isPresent(metadata)) { + var propertyMetadata = reflection_1.reflector.propMetadata(type); + return this._mergeWithPropertyMetadata(metadata, propertyMetadata); + } + } + throw new exceptions_1.BaseException("No Directive annotation found on " + lang_1.stringify(type)); + }; + DirectiveResolver.prototype._mergeWithPropertyMetadata = function(dm, propertyMetadata) { + var inputs = []; + var outputs = []; + var host = {}; + var queries = {}; + collection_1.StringMapWrapper.forEach(propertyMetadata, function(metadata, propName) { + metadata.forEach(function(a) { + if (a instanceof metadata_1.InputMetadata) { + if (lang_1.isPresent(a.bindingPropertyName)) { + inputs.push(propName + ": " + a.bindingPropertyName); + } else { + inputs.push(propName); + } + } + if (a instanceof metadata_1.OutputMetadata) { + if (lang_1.isPresent(a.bindingPropertyName)) { + outputs.push(propName + ": " + a.bindingPropertyName); + } else { + outputs.push(propName); + } + } + if (a instanceof metadata_1.HostBindingMetadata) { + if (lang_1.isPresent(a.hostPropertyName)) { + host[("[" + a.hostPropertyName + "]")] = propName; + } else { + host[("[" + propName + "]")] = propName; + } + } + if (a instanceof metadata_1.HostListenerMetadata) { + var args = lang_1.isPresent(a.args) ? a.args.join(', ') : ''; + host[("(" + a.eventName + ")")] = propName + "(" + args + ")"; + } + if (a instanceof metadata_1.ContentChildrenMetadata) { + queries[propName] = a; + } + if (a instanceof metadata_1.ViewChildrenMetadata) { + queries[propName] = a; + } + if (a instanceof metadata_1.ContentChildMetadata) { + queries[propName] = a; + } + if (a instanceof metadata_1.ViewChildMetadata) { + queries[propName] = a; + } + }); + }); + return this._merge(dm, inputs, outputs, host, queries); + }; + DirectiveResolver.prototype._merge = function(dm, inputs, outputs, host, queries) { + var mergedInputs = lang_1.isPresent(dm.inputs) ? collection_1.ListWrapper.concat(dm.inputs, inputs) : inputs; + var mergedOutputs = lang_1.isPresent(dm.outputs) ? collection_1.ListWrapper.concat(dm.outputs, outputs) : outputs; + var mergedHost = lang_1.isPresent(dm.host) ? collection_1.StringMapWrapper.merge(dm.host, host) : host; + var mergedQueries = lang_1.isPresent(dm.queries) ? collection_1.StringMapWrapper.merge(dm.queries, queries) : queries; + if (dm instanceof metadata_1.ComponentMetadata) { + return new metadata_1.ComponentMetadata({ + selector: dm.selector, + inputs: mergedInputs, + outputs: mergedOutputs, + host: mergedHost, + exportAs: dm.exportAs, + moduleId: dm.moduleId, + queries: mergedQueries, + changeDetection: dm.changeDetection, + providers: dm.providers, + viewProviders: dm.viewProviders + }); + } else { + return new metadata_1.DirectiveMetadata({ + selector: dm.selector, + inputs: mergedInputs, + outputs: mergedOutputs, + host: mergedHost, + exportAs: dm.exportAs, + queries: mergedQueries, + providers: dm.providers + }); + } + }; + DirectiveResolver = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], DirectiveResolver); + return DirectiveResolver; + })(); + exports.DirectiveResolver = DirectiveResolver; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/view_resolver", ["angular2/src/core/di", "angular2/src/core/metadata/view", "angular2/src/core/metadata/directives", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/core/reflection/reflection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var di_1 = require("angular2/src/core/di"); + var view_1 = require("angular2/src/core/metadata/view"); + var directives_1 = require("angular2/src/core/metadata/directives"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var reflection_1 = require("angular2/src/core/reflection/reflection"); + var ViewResolver = (function() { + function ViewResolver() { + this._cache = new collection_1.Map(); + } + ViewResolver.prototype.resolve = function(component) { + var view = this._cache.get(component); + if (lang_1.isBlank(view)) { + view = this._resolve(component); + this._cache.set(component, view); + } + return view; + }; + ViewResolver.prototype._resolve = function(component) { + var compMeta; + var viewMeta; + reflection_1.reflector.annotations(component).forEach(function(m) { + if (m instanceof view_1.ViewMetadata) { + viewMeta = m; + } + if (m instanceof directives_1.ComponentMetadata) { + compMeta = m; + } + }); + if (lang_1.isPresent(compMeta)) { + if (lang_1.isBlank(compMeta.template) && lang_1.isBlank(compMeta.templateUrl) && lang_1.isBlank(viewMeta)) { + throw new exceptions_1.BaseException("Component '" + lang_1.stringify(component) + "' must have either 'template', 'templateUrl', or '@View' set."); + } else if (lang_1.isPresent(compMeta.template) && lang_1.isPresent(viewMeta)) { + this._throwMixingViewAndComponent("template", component); + } else if (lang_1.isPresent(compMeta.templateUrl) && lang_1.isPresent(viewMeta)) { + this._throwMixingViewAndComponent("templateUrl", component); + } else if (lang_1.isPresent(compMeta.directives) && lang_1.isPresent(viewMeta)) { + this._throwMixingViewAndComponent("directives", component); + } else if (lang_1.isPresent(compMeta.pipes) && lang_1.isPresent(viewMeta)) { + this._throwMixingViewAndComponent("pipes", component); + } else if (lang_1.isPresent(compMeta.encapsulation) && lang_1.isPresent(viewMeta)) { + this._throwMixingViewAndComponent("encapsulation", component); + } else if (lang_1.isPresent(compMeta.styles) && lang_1.isPresent(viewMeta)) { + this._throwMixingViewAndComponent("styles", component); + } else if (lang_1.isPresent(compMeta.styleUrls) && lang_1.isPresent(viewMeta)) { + this._throwMixingViewAndComponent("styleUrls", component); + } else if (lang_1.isPresent(viewMeta)) { + return viewMeta; + } else { + return new view_1.ViewMetadata({ + templateUrl: compMeta.templateUrl, + template: compMeta.template, + directives: compMeta.directives, + pipes: compMeta.pipes, + encapsulation: compMeta.encapsulation, + styles: compMeta.styles, + styleUrls: compMeta.styleUrls + }); + } + } else { + if (lang_1.isBlank(viewMeta)) { + throw new exceptions_1.BaseException("No View decorator found on component '" + lang_1.stringify(component) + "'"); + } else { + return viewMeta; + } + } + return null; + }; + ViewResolver.prototype._throwMixingViewAndComponent = function(propertyName, component) { + throw new exceptions_1.BaseException("Component '" + lang_1.stringify(component) + "' cannot have both '" + propertyName + "' and '@View' set at the same time\""); + }; + ViewResolver = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], ViewResolver); + return ViewResolver; + })(); + exports.ViewResolver = ViewResolver; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/pipe_resolver", ["angular2/src/core/di", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/core/metadata", "angular2/src/core/reflection/reflection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var di_1 = require("angular2/src/core/di"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var metadata_1 = require("angular2/src/core/metadata"); + var reflection_1 = require("angular2/src/core/reflection/reflection"); + function _isPipeMetadata(type) { + return type instanceof metadata_1.PipeMetadata; + } + var PipeResolver = (function() { + function PipeResolver() {} + PipeResolver.prototype.resolve = function(type) { + var metas = reflection_1.reflector.annotations(di_1.resolveForwardRef(type)); + if (lang_1.isPresent(metas)) { + var annotation = metas.find(_isPipeMetadata); + if (lang_1.isPresent(annotation)) { + return annotation; + } + } + throw new exceptions_1.BaseException("No Pipe decorator found on " + lang_1.stringify(type)); + }; + PipeResolver = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], PipeResolver); + return PipeResolver; + })(); + exports.PipeResolver = PipeResolver; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/platform_directives_and_pipes", ["angular2/src/core/di", "angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var di_1 = require("angular2/src/core/di"); + var lang_1 = require("angular2/src/facade/lang"); + exports.PLATFORM_DIRECTIVES = lang_1.CONST_EXPR(new di_1.OpaqueToken("Platform Directives")); + exports.PLATFORM_PIPES = lang_1.CONST_EXPR(new di_1.OpaqueToken("Platform Pipes")); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/template_commands", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/core/render/api", "angular2/src/core/metadata", "angular2/src/core/metadata"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var api_1 = require("angular2/src/core/render/api"); + var metadata_1 = require("angular2/src/core/metadata"); + var metadata_2 = require("angular2/src/core/metadata"); + exports.ViewEncapsulation = metadata_2.ViewEncapsulation; + var CompiledHostTemplate = (function() { + function CompiledHostTemplate(template) { + this.template = template; + } + CompiledHostTemplate = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [CompiledComponentTemplate])], CompiledHostTemplate); + return CompiledHostTemplate; + })(); + exports.CompiledHostTemplate = CompiledHostTemplate; + var CompiledComponentTemplate = (function() { + function CompiledComponentTemplate(id, changeDetectorFactory, commands, styles) { + this.id = id; + this.changeDetectorFactory = changeDetectorFactory; + this.commands = commands; + this.styles = styles; + } + CompiledComponentTemplate = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [String, Function, Array, Array])], CompiledComponentTemplate); + return CompiledComponentTemplate; + })(); + exports.CompiledComponentTemplate = CompiledComponentTemplate; + var EMPTY_ARR = lang_1.CONST_EXPR([]); + var TextCmd = (function() { + function TextCmd(value, isBound, ngContentIndex) { + this.value = value; + this.isBound = isBound; + this.ngContentIndex = ngContentIndex; + } + TextCmd.prototype.visit = function(visitor, context) { + return visitor.visitText(this, context); + }; + TextCmd = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [String, Boolean, Number])], TextCmd); + return TextCmd; + })(); + exports.TextCmd = TextCmd; + var NgContentCmd = (function() { + function NgContentCmd(index, ngContentIndex) { + this.index = index; + this.ngContentIndex = ngContentIndex; + this.isBound = false; + } + NgContentCmd.prototype.visit = function(visitor, context) { + return visitor.visitNgContent(this, context); + }; + NgContentCmd = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Number, Number])], NgContentCmd); + return NgContentCmd; + })(); + exports.NgContentCmd = NgContentCmd; + var IBeginElementCmd = (function(_super) { + __extends(IBeginElementCmd, _super); + function IBeginElementCmd() { + _super.apply(this, arguments); + } + Object.defineProperty(IBeginElementCmd.prototype, "variableNameAndValues", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(IBeginElementCmd.prototype, "eventTargetAndNames", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(IBeginElementCmd.prototype, "directives", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + return IBeginElementCmd; + })(api_1.RenderBeginElementCmd); + exports.IBeginElementCmd = IBeginElementCmd; + var BeginElementCmd = (function() { + function BeginElementCmd(name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, directives, isBound, ngContentIndex) { + this.name = name; + this.attrNameAndValues = attrNameAndValues; + this.eventTargetAndNames = eventTargetAndNames; + this.variableNameAndValues = variableNameAndValues; + this.directives = directives; + this.isBound = isBound; + this.ngContentIndex = ngContentIndex; + } + BeginElementCmd.prototype.visit = function(visitor, context) { + return visitor.visitBeginElement(this, context); + }; + BeginElementCmd = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [String, Array, Array, Array, Array, Boolean, Number])], BeginElementCmd); + return BeginElementCmd; + })(); + exports.BeginElementCmd = BeginElementCmd; + var EndElementCmd = (function() { + function EndElementCmd() {} + EndElementCmd.prototype.visit = function(visitor, context) { + return visitor.visitEndElement(context); + }; + EndElementCmd = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [])], EndElementCmd); + return EndElementCmd; + })(); + exports.EndElementCmd = EndElementCmd; + var BeginComponentCmd = (function() { + function BeginComponentCmd(name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, directives, encapsulation, ngContentIndex, templateGetter) { + this.name = name; + this.attrNameAndValues = attrNameAndValues; + this.eventTargetAndNames = eventTargetAndNames; + this.variableNameAndValues = variableNameAndValues; + this.directives = directives; + this.encapsulation = encapsulation; + this.ngContentIndex = ngContentIndex; + this.templateGetter = templateGetter; + this.isBound = true; + } + Object.defineProperty(BeginComponentCmd.prototype, "templateId", { + get: function() { + return this.templateGetter().id; + }, + enumerable: true, + configurable: true + }); + BeginComponentCmd.prototype.visit = function(visitor, context) { + return visitor.visitBeginComponent(this, context); + }; + BeginComponentCmd = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [String, Array, Array, Array, Array, Number, Number, Function])], BeginComponentCmd); + return BeginComponentCmd; + })(); + exports.BeginComponentCmd = BeginComponentCmd; + var EndComponentCmd = (function() { + function EndComponentCmd() {} + EndComponentCmd.prototype.visit = function(visitor, context) { + return visitor.visitEndComponent(context); + }; + EndComponentCmd = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [])], EndComponentCmd); + return EndComponentCmd; + })(); + exports.EndComponentCmd = EndComponentCmd; + var EmbeddedTemplateCmd = (function() { + function EmbeddedTemplateCmd(attrNameAndValues, variableNameAndValues, directives, isMerged, ngContentIndex, changeDetectorFactory, children) { + this.attrNameAndValues = attrNameAndValues; + this.variableNameAndValues = variableNameAndValues; + this.directives = directives; + this.isMerged = isMerged; + this.ngContentIndex = ngContentIndex; + this.changeDetectorFactory = changeDetectorFactory; + this.children = children; + this.isBound = true; + this.name = null; + this.eventTargetAndNames = EMPTY_ARR; + } + EmbeddedTemplateCmd.prototype.visit = function(visitor, context) { + return visitor.visitEmbeddedTemplate(this, context); + }; + EmbeddedTemplateCmd = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Array, Array, Array, Boolean, Number, Function, Array])], EmbeddedTemplateCmd); + return EmbeddedTemplateCmd; + })(); + exports.EmbeddedTemplateCmd = EmbeddedTemplateCmd; + function visitAllCommands(visitor, cmds, context) { + if (context === void 0) { + context = null; + } + for (var i = 0; i < cmds.length; i++) { + cmds[i].visit(visitor, context); + } + } + exports.visitAllCommands = visitAllCommands; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/console", ["angular2/src/core/di", "angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var di_1 = require("angular2/src/core/di"); + var lang_1 = require("angular2/src/facade/lang"); + var Console = (function() { + function Console() {} + Console.prototype.log = function(message) { + lang_1.print(message); + }; + Console = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], Console); + return Console; + })(); + exports.Console = Console; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/zone", ["angular2/src/core/zone/ng_zone"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var ng_zone_1 = require("angular2/src/core/zone/ng_zone"); + exports.NgZone = ng_zone_1.NgZone; + exports.NgZoneError = ng_zone_1.NgZoneError; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/render", ["angular2/src/core/render/api"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var api_1 = require("angular2/src/core/render/api"); + exports.Renderer = api_1.Renderer; + exports.RenderViewRef = api_1.RenderViewRef; + exports.RenderProtoViewRef = api_1.RenderProtoViewRef; + exports.RenderFragmentRef = api_1.RenderFragmentRef; + exports.RenderViewWithFragments = api_1.RenderViewWithFragments; + exports.RenderTemplateCmd = api_1.RenderTemplateCmd; + exports.RenderTextCmd = api_1.RenderTextCmd; + exports.RenderNgContentCmd = api_1.RenderNgContentCmd; + exports.RenderBeginElementCmd = api_1.RenderBeginElementCmd; + exports.RenderBeginComponentCmd = api_1.RenderBeginComponentCmd; + exports.RenderEmbeddedTemplateCmd = api_1.RenderEmbeddedTemplateCmd; + exports.RenderBeginCmd = api_1.RenderBeginCmd; + exports.RenderComponentTemplate = api_1.RenderComponentTemplate; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker", ["angular2/src/core/linker/directive_resolver", "angular2/src/core/linker/view_resolver", "angular2/src/core/linker/compiler", "angular2/src/core/linker/view_manager", "angular2/src/core/linker/query_list", "angular2/src/core/linker/dynamic_component_loader", "angular2/src/core/linker/element_ref", "angular2/src/core/linker/template_ref", "angular2/src/core/linker/view_ref", "angular2/src/core/linker/view_container_ref", "angular2/src/core/linker/dynamic_component_loader"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var directive_resolver_1 = require("angular2/src/core/linker/directive_resolver"); + exports.DirectiveResolver = directive_resolver_1.DirectiveResolver; + var view_resolver_1 = require("angular2/src/core/linker/view_resolver"); + exports.ViewResolver = view_resolver_1.ViewResolver; + var compiler_1 = require("angular2/src/core/linker/compiler"); + exports.Compiler = compiler_1.Compiler; + var view_manager_1 = require("angular2/src/core/linker/view_manager"); + exports.AppViewManager = view_manager_1.AppViewManager; + var query_list_1 = require("angular2/src/core/linker/query_list"); + exports.QueryList = query_list_1.QueryList; + var dynamic_component_loader_1 = require("angular2/src/core/linker/dynamic_component_loader"); + exports.DynamicComponentLoader = dynamic_component_loader_1.DynamicComponentLoader; + var element_ref_1 = require("angular2/src/core/linker/element_ref"); + exports.ElementRef = element_ref_1.ElementRef; + var template_ref_1 = require("angular2/src/core/linker/template_ref"); + exports.TemplateRef = template_ref_1.TemplateRef; + var view_ref_1 = require("angular2/src/core/linker/view_ref"); + exports.ViewRef = view_ref_1.ViewRef; + exports.ProtoViewRef = view_ref_1.ProtoViewRef; + var view_container_ref_1 = require("angular2/src/core/linker/view_container_ref"); + exports.ViewContainerRef = view_container_ref_1.ViewContainerRef; + var dynamic_component_loader_2 = require("angular2/src/core/linker/dynamic_component_loader"); + exports.ComponentRef = dynamic_component_loader_2.ComponentRef; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/debug/debug_element", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/core/linker/view", "angular2/src/core/linker/view_ref"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var view_1 = require("angular2/src/core/linker/view"); + var view_ref_1 = require("angular2/src/core/linker/view_ref"); + var DebugElement = (function() { + function DebugElement() {} + Object.defineProperty(DebugElement.prototype, "componentInstance", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + Object.defineProperty(DebugElement.prototype, "nativeElement", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + Object.defineProperty(DebugElement.prototype, "elementRef", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + Object.defineProperty(DebugElement.prototype, "children", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + Object.defineProperty(DebugElement.prototype, "componentViewChildren", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + DebugElement.prototype.query = function(predicate, scope) { + if (scope === void 0) { + scope = Scope.all; + } + var results = this.queryAll(predicate, scope); + return results.length > 0 ? results[0] : null; + }; + DebugElement.prototype.queryAll = function(predicate, scope) { + if (scope === void 0) { + scope = Scope.all; + } + var elementsInScope = scope(this); + return elementsInScope.filter(predicate); + }; + return DebugElement; + })(); + exports.DebugElement = DebugElement; + var DebugElement_ = (function(_super) { + __extends(DebugElement_, _super); + function DebugElement_(_parentView, _boundElementIndex) { + _super.call(this); + this._parentView = _parentView; + this._boundElementIndex = _boundElementIndex; + this._elementInjector = this._parentView.elementInjectors[this._boundElementIndex]; + } + Object.defineProperty(DebugElement_.prototype, "componentInstance", { + get: function() { + if (!lang_1.isPresent(this._elementInjector)) { + return null; + } + return this._elementInjector.getComponent(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DebugElement_.prototype, "nativeElement", { + get: function() { + return this.elementRef.nativeElement; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DebugElement_.prototype, "elementRef", { + get: function() { + return this._parentView.elementRefs[this._boundElementIndex]; + }, + enumerable: true, + configurable: true + }); + DebugElement_.prototype.getDirectiveInstance = function(directiveIndex) { + return this._elementInjector.getDirectiveAtIndex(directiveIndex); + }; + Object.defineProperty(DebugElement_.prototype, "children", { + get: function() { + return this._getChildElements(this._parentView, this._boundElementIndex); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DebugElement_.prototype, "componentViewChildren", { + get: function() { + var shadowView = this._parentView.getNestedView(this._boundElementIndex); + if (!lang_1.isPresent(shadowView) || shadowView.proto.type !== view_1.ViewType.COMPONENT) { + return []; + } + return this._getChildElements(shadowView, null); + }, + enumerable: true, + configurable: true + }); + DebugElement_.prototype.triggerEventHandler = function(eventName, eventObj) { + this._parentView.triggerEventHandlers(eventName, eventObj, this._boundElementIndex); + }; + DebugElement_.prototype.hasDirective = function(type) { + if (!lang_1.isPresent(this._elementInjector)) { + return false; + } + return this._elementInjector.hasDirective(type); + }; + DebugElement_.prototype.inject = function(type) { + if (!lang_1.isPresent(this._elementInjector)) { + return null; + } + return this._elementInjector.get(type); + }; + DebugElement_.prototype.getLocal = function(name) { + return this._parentView.locals.get(name); + }; + DebugElement_.prototype._getChildElements = function(view, parentBoundElementIndex) { + var _this = this; + var els = []; + var parentElementBinder = null; + if (lang_1.isPresent(parentBoundElementIndex)) { + parentElementBinder = view.proto.elementBinders[parentBoundElementIndex - view.elementOffset]; + } + for (var i = 0; i < view.proto.elementBinders.length; ++i) { + var binder = view.proto.elementBinders[i]; + if (binder.parent == parentElementBinder) { + els.push(new DebugElement_(view, view.elementOffset + i)); + var views = view.viewContainers[view.elementOffset + i]; + if (lang_1.isPresent(views)) { + views.views.forEach(function(nextView) { + els = els.concat(_this._getChildElements(nextView, null)); + }); + } + } + } + return els; + }; + return DebugElement_; + })(DebugElement); + exports.DebugElement_ = DebugElement_; + function inspectElement(elementRef) { + return new DebugElement_(view_ref_1.internalView(elementRef.parentView), elementRef.boundElementIndex); + } + exports.inspectElement = inspectElement; + function asNativeElements(arr) { + return arr.map(function(debugEl) { + return debugEl.nativeElement; + }); + } + exports.asNativeElements = asNativeElements; + var Scope = (function() { + function Scope() {} + Scope.all = function(debugElement) { + var scope = []; + scope.push(debugElement); + debugElement.children.forEach(function(child) { + return scope = scope.concat(Scope.all(child)); + }); + debugElement.componentViewChildren.forEach(function(child) { + return scope = scope.concat(Scope.all(child)); + }); + return scope; + }; + Scope.light = function(debugElement) { + var scope = []; + debugElement.children.forEach(function(child) { + scope.push(child); + scope = scope.concat(Scope.light(child)); + }); + return scope; + }; + Scope.view = function(debugElement) { + var scope = []; + debugElement.componentViewChildren.forEach(function(child) { + scope.push(child); + scope = scope.concat(Scope.light(child)); + }); + return scope; + }; + return Scope; + })(); + exports.Scope = Scope; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/platform_common_providers", ["angular2/src/facade/lang", "angular2/src/core/di", "angular2/src/core/console", "angular2/src/core/reflection/reflection", "angular2/src/core/testability/testability"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var di_1 = require("angular2/src/core/di"); + var console_1 = require("angular2/src/core/console"); + var reflection_1 = require("angular2/src/core/reflection/reflection"); + var testability_1 = require("angular2/src/core/testability/testability"); + function _reflector() { + return reflection_1.reflector; + } + exports.PLATFORM_COMMON_PROVIDERS = lang_1.CONST_EXPR([new di_1.Provider(reflection_1.Reflector, { + useFactory: _reflector, + deps: [] + }), testability_1.TestabilityRegistry, console_1.Console]); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/application_common_providers", ["angular2/src/facade/lang", "angular2/src/core/di", "angular2/src/core/application_tokens", "angular2/src/core/change_detection/change_detection", "angular2/src/core/linker/view_pool", "angular2/src/core/linker/view_manager", "angular2/src/core/linker/view_manager", "angular2/src/core/linker/view_manager_utils", "angular2/src/core/linker/view_resolver", "angular2/src/core/linker/view_listener", "angular2/src/core/linker/proto_view_factory", "angular2/src/core/linker/directive_resolver", "angular2/src/core/linker/pipe_resolver", "angular2/src/core/linker/compiler", "angular2/src/core/linker/compiler", "angular2/src/core/linker/dynamic_component_loader", "angular2/src/core/linker/dynamic_component_loader"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var di_1 = require("angular2/src/core/di"); + var application_tokens_1 = require("angular2/src/core/application_tokens"); + var change_detection_1 = require("angular2/src/core/change_detection/change_detection"); + var view_pool_1 = require("angular2/src/core/linker/view_pool"); + var view_manager_1 = require("angular2/src/core/linker/view_manager"); + var view_manager_2 = require("angular2/src/core/linker/view_manager"); + var view_manager_utils_1 = require("angular2/src/core/linker/view_manager_utils"); + var view_resolver_1 = require("angular2/src/core/linker/view_resolver"); + var view_listener_1 = require("angular2/src/core/linker/view_listener"); + var proto_view_factory_1 = require("angular2/src/core/linker/proto_view_factory"); + var directive_resolver_1 = require("angular2/src/core/linker/directive_resolver"); + var pipe_resolver_1 = require("angular2/src/core/linker/pipe_resolver"); + var compiler_1 = require("angular2/src/core/linker/compiler"); + var compiler_2 = require("angular2/src/core/linker/compiler"); + var dynamic_component_loader_1 = require("angular2/src/core/linker/dynamic_component_loader"); + var dynamic_component_loader_2 = require("angular2/src/core/linker/dynamic_component_loader"); + exports.APPLICATION_COMMON_PROVIDERS = lang_1.CONST_EXPR([new di_1.Provider(compiler_1.Compiler, {useClass: compiler_2.Compiler_}), application_tokens_1.APP_ID_RANDOM_PROVIDER, view_pool_1.AppViewPool, new di_1.Provider(view_pool_1.APP_VIEW_POOL_CAPACITY, {useValue: 10000}), new di_1.Provider(view_manager_1.AppViewManager, {useClass: view_manager_2.AppViewManager_}), view_manager_utils_1.AppViewManagerUtils, view_listener_1.AppViewListener, proto_view_factory_1.ProtoViewFactory, view_resolver_1.ViewResolver, new di_1.Provider(change_detection_1.IterableDiffers, {useValue: change_detection_1.defaultIterableDiffers}), new di_1.Provider(change_detection_1.KeyValueDiffers, {useValue: change_detection_1.defaultKeyValueDiffers}), directive_resolver_1.DirectiveResolver, pipe_resolver_1.PipeResolver, new di_1.Provider(dynamic_component_loader_1.DynamicComponentLoader, {useClass: dynamic_component_loader_2.DynamicComponentLoader_})]); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/dom/events/event_manager", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/core/di", "angular2/src/core/zone/ng_zone", "angular2/src/facade/collection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var di_1 = require("angular2/src/core/di"); + var ng_zone_1 = require("angular2/src/core/zone/ng_zone"); + var collection_1 = require("angular2/src/facade/collection"); + exports.EVENT_MANAGER_PLUGINS = lang_1.CONST_EXPR(new di_1.OpaqueToken("EventManagerPlugins")); + var EventManager = (function() { + function EventManager(plugins, _zone) { + var _this = this; + this._zone = _zone; + plugins.forEach(function(p) { + return p.manager = _this; + }); + this._plugins = collection_1.ListWrapper.reversed(plugins); + } + EventManager.prototype.addEventListener = function(element, eventName, handler) { + var plugin = this._findPluginFor(eventName); + plugin.addEventListener(element, eventName, handler); + }; + EventManager.prototype.addGlobalEventListener = function(target, eventName, handler) { + var plugin = this._findPluginFor(eventName); + return plugin.addGlobalEventListener(target, eventName, handler); + }; + EventManager.prototype.getZone = function() { + return this._zone; + }; + EventManager.prototype._findPluginFor = function(eventName) { + var plugins = this._plugins; + for (var i = 0; i < plugins.length; i++) { + var plugin = plugins[i]; + if (plugin.supports(eventName)) { + return plugin; + } + } + throw new exceptions_1.BaseException("No event manager plugin found for event " + eventName); + }; + EventManager = __decorate([di_1.Injectable(), __param(0, di_1.Inject(exports.EVENT_MANAGER_PLUGINS)), __metadata('design:paramtypes', [Array, ng_zone_1.NgZone])], EventManager); + return EventManager; + })(); + exports.EventManager = EventManager; + var EventManagerPlugin = (function() { + function EventManagerPlugin() {} + EventManagerPlugin.prototype.supports = function(eventName) { + return false; + }; + EventManagerPlugin.prototype.addEventListener = function(element, eventName, handler) { + throw "not implemented"; + }; + EventManagerPlugin.prototype.addGlobalEventListener = function(element, eventName, handler) { + throw "not implemented"; + }; + return EventManagerPlugin; + })(); + exports.EventManagerPlugin = EventManagerPlugin; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/render/view", ["angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/core/render/api"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var api_1 = require("angular2/src/core/render/api"); + var DefaultProtoViewRef = (function(_super) { + __extends(DefaultProtoViewRef, _super); + function DefaultProtoViewRef(template, cmds) { + _super.call(this); + this.template = template; + this.cmds = cmds; + } + return DefaultProtoViewRef; + })(api_1.RenderProtoViewRef); + exports.DefaultProtoViewRef = DefaultProtoViewRef; + var DefaultRenderFragmentRef = (function(_super) { + __extends(DefaultRenderFragmentRef, _super); + function DefaultRenderFragmentRef(nodes) { + _super.call(this); + this.nodes = nodes; + } + return DefaultRenderFragmentRef; + })(api_1.RenderFragmentRef); + exports.DefaultRenderFragmentRef = DefaultRenderFragmentRef; + var DefaultRenderView = (function(_super) { + __extends(DefaultRenderView, _super); + function DefaultRenderView(fragments, boundTextNodes, boundElements, nativeShadowRoots, globalEventAdders, rootContentInsertionPoints) { + _super.call(this); + this.fragments = fragments; + this.boundTextNodes = boundTextNodes; + this.boundElements = boundElements; + this.nativeShadowRoots = nativeShadowRoots; + this.globalEventAdders = globalEventAdders; + this.rootContentInsertionPoints = rootContentInsertionPoints; + this.hydrated = false; + this.eventDispatcher = null; + this.globalEventRemovers = null; + } + DefaultRenderView.prototype.hydrate = function() { + if (this.hydrated) + throw new exceptions_1.BaseException('The view is already hydrated.'); + this.hydrated = true; + this.globalEventRemovers = collection_1.ListWrapper.createFixedSize(this.globalEventAdders.length); + for (var i = 0; i < this.globalEventAdders.length; i++) { + this.globalEventRemovers[i] = this.globalEventAdders[i](); + } + }; + DefaultRenderView.prototype.dehydrate = function() { + if (!this.hydrated) + throw new exceptions_1.BaseException('The view is already dehydrated.'); + for (var i = 0; i < this.globalEventRemovers.length; i++) { + this.globalEventRemovers[i](); + } + this.globalEventRemovers = null; + this.hydrated = false; + }; + DefaultRenderView.prototype.setEventDispatcher = function(dispatcher) { + this.eventDispatcher = dispatcher; + }; + DefaultRenderView.prototype.dispatchRenderEvent = function(boundElementIndex, eventName, event) { + var allowDefaultBehavior = true; + if (lang_1.isPresent(this.eventDispatcher)) { + var locals = new collection_1.Map(); + locals.set('$event', event); + allowDefaultBehavior = this.eventDispatcher.dispatchRenderEvent(boundElementIndex, eventName, locals); + } + return allowDefaultBehavior; + }; + return DefaultRenderView; + })(api_1.RenderViewRef); + exports.DefaultRenderView = DefaultRenderView; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/dom/events/dom_events", ["angular2/src/platform/dom/dom_adapter", "angular2/core", "angular2/src/platform/dom/events/event_manager"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); + var core_1 = require("angular2/core"); + var event_manager_1 = require("angular2/src/platform/dom/events/event_manager"); + var DomEventsPlugin = (function(_super) { + __extends(DomEventsPlugin, _super); + function DomEventsPlugin() { + _super.apply(this, arguments); + } + DomEventsPlugin.prototype.supports = function(eventName) { + return true; + }; + DomEventsPlugin.prototype.addEventListener = function(element, eventName, handler) { + var zone = this.manager.getZone(); + var outsideHandler = function(event) { + return zone.run(function() { + return handler(event); + }); + }; + this.manager.getZone().runOutsideAngular(function() { + dom_adapter_1.DOM.on(element, eventName, outsideHandler); + }); + }; + DomEventsPlugin.prototype.addGlobalEventListener = function(target, eventName, handler) { + var element = dom_adapter_1.DOM.getGlobalEventTarget(target); + var zone = this.manager.getZone(); + var outsideHandler = function(event) { + return zone.run(function() { + return handler(event); + }); + }; + return this.manager.getZone().runOutsideAngular(function() { + return dom_adapter_1.DOM.onAndCancel(element, eventName, outsideHandler); + }); + }; + DomEventsPlugin = __decorate([core_1.Injectable(), __metadata('design:paramtypes', [])], DomEventsPlugin); + return DomEventsPlugin; + })(event_manager_1.EventManagerPlugin); + exports.DomEventsPlugin = DomEventsPlugin; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/dom/debug/by", ["angular2/src/facade/lang", "angular2/src/platform/dom/dom_adapter"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); + var By = (function() { + function By() {} + By.all = function() { + return function(debugElement) { + return true; + }; + }; + By.css = function(selector) { + return function(debugElement) { + return lang_1.isPresent(debugElement.nativeElement) ? dom_adapter_1.DOM.elementMatches(debugElement.nativeElement, selector) : false; + }; + }; + By.directive = function(type) { + return function(debugElement) { + return debugElement.hasDirective(type); + }; + }; + return By; + })(); + exports.By = By; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/dom/debug/debug_element_view_listener", ["angular2/src/facade/lang", "angular2/src/facade/collection", "angular2/src/core/di", "angular2/src/core/linker/view_listener", "angular2/src/platform/dom/dom_adapter", "angular2/src/core/render/api", "angular2/src/core/debug/debug_element"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var collection_1 = require("angular2/src/facade/collection"); + var di_1 = require("angular2/src/core/di"); + var view_listener_1 = require("angular2/src/core/linker/view_listener"); + var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); + var api_1 = require("angular2/src/core/render/api"); + var debug_element_1 = require("angular2/src/core/debug/debug_element"); + var NG_ID_PROPERTY = 'ngid'; + var INSPECT_GLOBAL_NAME = 'ng.probe'; + var NG_ID_SEPARATOR = '#'; + var _allIdsByView = new collection_1.Map(); + var _allViewsById = new collection_1.Map(); + var _nextId = 0; + function _setElementId(element, indices) { + if (lang_1.isPresent(element) && dom_adapter_1.DOM.isElementNode(element)) { + dom_adapter_1.DOM.setData(element, NG_ID_PROPERTY, indices.join(NG_ID_SEPARATOR)); + } + } + function _getElementId(element) { + var elId = dom_adapter_1.DOM.getData(element, NG_ID_PROPERTY); + if (lang_1.isPresent(elId)) { + return elId.split(NG_ID_SEPARATOR).map(function(partStr) { + return lang_1.NumberWrapper.parseInt(partStr, 10); + }); + } else { + return null; + } + } + function inspectNativeElement(element) { + var elId = _getElementId(element); + if (lang_1.isPresent(elId)) { + var view = _allViewsById.get(elId[0]); + if (lang_1.isPresent(view)) { + return new debug_element_1.DebugElement_(view, elId[1]); + } + } + return null; + } + exports.inspectNativeElement = inspectNativeElement; + var DebugElementViewListener = (function() { + function DebugElementViewListener(_renderer) { + this._renderer = _renderer; + dom_adapter_1.DOM.setGlobalVar(INSPECT_GLOBAL_NAME, inspectNativeElement); + } + DebugElementViewListener.prototype.onViewCreated = function(view) { + var viewId = _nextId++; + _allViewsById.set(viewId, view); + _allIdsByView.set(view, viewId); + for (var i = 0; i < view.elementRefs.length; i++) { + var el = view.elementRefs[i]; + _setElementId(this._renderer.getNativeElementSync(el), [viewId, i]); + } + }; + DebugElementViewListener.prototype.onViewDestroyed = function(view) { + var viewId = _allIdsByView.get(view); + _allIdsByView.delete(view); + _allViewsById.delete(viewId); + }; + DebugElementViewListener = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [api_1.Renderer])], DebugElementViewListener); + return DebugElementViewListener; + })(); + exports.DebugElementViewListener = DebugElementViewListener; + exports.ELEMENT_PROBE_PROVIDERS = lang_1.CONST_EXPR([DebugElementViewListener, lang_1.CONST_EXPR(new di_1.Provider(view_listener_1.AppViewListener, {useExisting: DebugElementViewListener}))]); + exports.ELEMENT_PROBE_BINDINGS = exports.ELEMENT_PROBE_PROVIDERS; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/dom/dom_adapter", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + exports.DOM = null; + function setRootDomAdapter(adapter) { + if (lang_1.isBlank(exports.DOM)) { + exports.DOM = adapter; + } + } + exports.setRootDomAdapter = setRootDomAdapter; + var DomAdapter = (function() { + function DomAdapter() {} + return DomAdapter; + })(); + exports.DomAdapter = DomAdapter; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/di/decorators", ["angular2/src/core/di/metadata", "angular2/src/core/util/decorators"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var metadata_1 = require("angular2/src/core/di/metadata"); + var decorators_1 = require("angular2/src/core/util/decorators"); + exports.Inject = decorators_1.makeParamDecorator(metadata_1.InjectMetadata); + exports.Optional = decorators_1.makeParamDecorator(metadata_1.OptionalMetadata); + exports.Injectable = decorators_1.makeDecorator(metadata_1.InjectableMetadata); + exports.Self = decorators_1.makeParamDecorator(metadata_1.SelfMetadata); + exports.Host = decorators_1.makeParamDecorator(metadata_1.HostMetadata); + exports.SkipSelf = decorators_1.makeParamDecorator(metadata_1.SkipSelfMetadata); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/facade/exceptions", ["angular2/src/facade/exception_handler", "angular2/src/facade/exception_handler"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var exception_handler_1 = require("angular2/src/facade/exception_handler"); + var exception_handler_2 = require("angular2/src/facade/exception_handler"); + exports.ExceptionHandler = exception_handler_2.ExceptionHandler; + var BaseException = (function(_super) { + __extends(BaseException, _super); + function BaseException(message) { + if (message === void 0) { + message = "--"; + } + _super.call(this, message); + this.message = message; + this.stack = (new Error(message)).stack; + } + BaseException.prototype.toString = function() { + return this.message; + }; + return BaseException; + })(Error); + exports.BaseException = BaseException; + var WrappedException = (function(_super) { + __extends(WrappedException, _super); + function WrappedException(_wrapperMessage, _originalException, _originalStack, _context) { + _super.call(this, _wrapperMessage); + this._wrapperMessage = _wrapperMessage; + this._originalException = _originalException; + this._originalStack = _originalStack; + this._context = _context; + this._wrapperStack = (new Error(_wrapperMessage)).stack; + } + Object.defineProperty(WrappedException.prototype, "wrapperMessage", { + get: function() { + return this._wrapperMessage; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WrappedException.prototype, "wrapperStack", { + get: function() { + return this._wrapperStack; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WrappedException.prototype, "originalException", { + get: function() { + return this._originalException; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WrappedException.prototype, "originalStack", { + get: function() { + return this._originalStack; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WrappedException.prototype, "context", { + get: function() { + return this._context; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WrappedException.prototype, "message", { + get: function() { + return exception_handler_1.ExceptionHandler.exceptionToString(this); + }, + enumerable: true, + configurable: true + }); + WrappedException.prototype.toString = function() { + return this.message; + }; + return WrappedException; + })(Error); + exports.WrappedException = WrappedException; + function makeTypeError(message) { + return new TypeError(message); + } + exports.makeTypeError = makeTypeError; + function unimplemented() { + throw new BaseException('unimplemented'); + } + exports.unimplemented = unimplemented; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/reflection/reflection", ["angular2/src/core/reflection/reflector", "angular2/src/core/reflection/reflector", "angular2/src/core/reflection/reflection_capabilities"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var reflector_1 = require("angular2/src/core/reflection/reflector"); + var reflector_2 = require("angular2/src/core/reflection/reflector"); + exports.Reflector = reflector_2.Reflector; + exports.ReflectionInfo = reflector_2.ReflectionInfo; + var reflection_capabilities_1 = require("angular2/src/core/reflection/reflection_capabilities"); + exports.reflector = new reflector_1.Reflector(new reflection_capabilities_1.ReflectionCapabilities()); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/di/key", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/core/di/type_literal", "angular2/src/core/di/forward_ref", "angular2/src/core/di/type_literal"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var type_literal_1 = require("angular2/src/core/di/type_literal"); + var forward_ref_1 = require("angular2/src/core/di/forward_ref"); + var type_literal_2 = require("angular2/src/core/di/type_literal"); + exports.TypeLiteral = type_literal_2.TypeLiteral; + var Key = (function() { + function Key(token, id) { + this.token = token; + this.id = id; + if (lang_1.isBlank(token)) { + throw new exceptions_1.BaseException('Token must be defined!'); + } + } + Object.defineProperty(Key.prototype, "displayName", { + get: function() { + return lang_1.stringify(this.token); + }, + enumerable: true, + configurable: true + }); + Key.get = function(token) { + return _globalKeyRegistry.get(forward_ref_1.resolveForwardRef(token)); + }; + Object.defineProperty(Key, "numberOfKeys", { + get: function() { + return _globalKeyRegistry.numberOfKeys; + }, + enumerable: true, + configurable: true + }); + return Key; + })(); + exports.Key = Key; + var KeyRegistry = (function() { + function KeyRegistry() { + this._allKeys = new Map(); + } + KeyRegistry.prototype.get = function(token) { + if (token instanceof Key) + return token; + var theToken = token; + if (token instanceof type_literal_1.TypeLiteral) { + theToken = token.type; + } + token = theToken; + if (this._allKeys.has(token)) { + return this._allKeys.get(token); + } + var newKey = new Key(token, Key.numberOfKeys); + this._allKeys.set(token, newKey); + return newKey; + }; + Object.defineProperty(KeyRegistry.prototype, "numberOfKeys", { + get: function() { + return this._allKeys.size; + }, + enumerable: true, + configurable: true + }); + return KeyRegistry; + })(); + exports.KeyRegistry = KeyRegistry; + var _globalKeyRegistry = new KeyRegistry(); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/animate/animation", ["angular2/src/facade/lang", "angular2/src/facade/math", "angular2/src/platform/dom/util", "angular2/src/facade/collection", "angular2/src/platform/dom/dom_adapter"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var math_1 = require("angular2/src/facade/math"); + var util_1 = require("angular2/src/platform/dom/util"); + var collection_1 = require("angular2/src/facade/collection"); + var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); + var Animation = (function() { + function Animation(element, data, browserDetails) { + var _this = this; + this.element = element; + this.data = data; + this.browserDetails = browserDetails; + this.callbacks = []; + this.eventClearFunctions = []; + this.completed = false; + this._stringPrefix = ''; + this.startTime = lang_1.DateWrapper.toMillis(lang_1.DateWrapper.now()); + this._stringPrefix = dom_adapter_1.DOM.getAnimationPrefix(); + this.setup(); + this.wait(function(timestamp) { + return _this.start(); + }); + } + Object.defineProperty(Animation.prototype, "totalTime", { + get: function() { + var delay = this.computedDelay != null ? this.computedDelay : 0; + var duration = this.computedDuration != null ? this.computedDuration : 0; + return delay + duration; + }, + enumerable: true, + configurable: true + }); + Animation.prototype.wait = function(callback) { + this.browserDetails.raf(callback, 2); + }; + Animation.prototype.setup = function() { + if (this.data.fromStyles != null) + this.applyStyles(this.data.fromStyles); + if (this.data.duration != null) + this.applyStyles({'transitionDuration': this.data.duration.toString() + 'ms'}); + if (this.data.delay != null) + this.applyStyles({'transitionDelay': this.data.delay.toString() + 'ms'}); + }; + Animation.prototype.start = function() { + this.addClasses(this.data.classesToAdd); + this.addClasses(this.data.animationClasses); + this.removeClasses(this.data.classesToRemove); + if (this.data.toStyles != null) + this.applyStyles(this.data.toStyles); + var computedStyles = dom_adapter_1.DOM.getComputedStyle(this.element); + this.computedDelay = math_1.Math.max(this.parseDurationString(computedStyles.getPropertyValue(this._stringPrefix + 'transition-delay')), this.parseDurationString(this.element.style.getPropertyValue(this._stringPrefix + 'transition-delay'))); + this.computedDuration = math_1.Math.max(this.parseDurationString(computedStyles.getPropertyValue(this._stringPrefix + 'transition-duration')), this.parseDurationString(this.element.style.getPropertyValue(this._stringPrefix + 'transition-duration'))); + this.addEvents(); + }; + Animation.prototype.applyStyles = function(styles) { + var _this = this; + collection_1.StringMapWrapper.forEach(styles, function(value, key) { + var dashCaseKey = util_1.camelCaseToDashCase(key); + if (lang_1.isPresent(dom_adapter_1.DOM.getStyle(_this.element, dashCaseKey))) { + dom_adapter_1.DOM.setStyle(_this.element, dashCaseKey, value.toString()); + } else { + dom_adapter_1.DOM.setStyle(_this.element, _this._stringPrefix + dashCaseKey, value.toString()); + } + }); + }; + Animation.prototype.addClasses = function(classes) { + for (var i = 0, + len = classes.length; i < len; i++) + dom_adapter_1.DOM.addClass(this.element, classes[i]); + }; + Animation.prototype.removeClasses = function(classes) { + for (var i = 0, + len = classes.length; i < len; i++) + dom_adapter_1.DOM.removeClass(this.element, classes[i]); + }; + Animation.prototype.addEvents = function() { + var _this = this; + if (this.totalTime > 0) { + this.eventClearFunctions.push(dom_adapter_1.DOM.onAndCancel(this.element, dom_adapter_1.DOM.getTransitionEnd(), function(event) { + return _this.handleAnimationEvent(event); + })); + } else { + this.handleAnimationCompleted(); + } + }; + Animation.prototype.handleAnimationEvent = function(event) { + var elapsedTime = math_1.Math.round(event.elapsedTime * 1000); + if (!this.browserDetails.elapsedTimeIncludesDelay) + elapsedTime += this.computedDelay; + event.stopPropagation(); + if (elapsedTime >= this.totalTime) + this.handleAnimationCompleted(); + }; + Animation.prototype.handleAnimationCompleted = function() { + this.removeClasses(this.data.animationClasses); + this.callbacks.forEach(function(callback) { + return callback(); + }); + this.callbacks = []; + this.eventClearFunctions.forEach(function(fn) { + return fn(); + }); + this.eventClearFunctions = []; + this.completed = true; + }; + Animation.prototype.onComplete = function(callback) { + if (this.completed) { + callback(); + } else { + this.callbacks.push(callback); + } + return this; + }; + Animation.prototype.parseDurationString = function(duration) { + var maxValue = 0; + if (duration == null || duration.length < 2) { + return maxValue; + } else if (duration.substring(duration.length - 2) == 'ms') { + var value = lang_1.NumberWrapper.parseInt(this.stripLetters(duration), 10); + if (value > maxValue) + maxValue = value; + } else if (duration.substring(duration.length - 1) == 's') { + var ms = lang_1.NumberWrapper.parseFloat(this.stripLetters(duration)) * 1000; + var value = math_1.Math.floor(ms); + if (value > maxValue) + maxValue = value; + } + return maxValue; + }; + Animation.prototype.stripLetters = function(str) { + return lang_1.StringWrapper.replaceAll(str, lang_1.RegExpWrapper.create('[^0-9]+$', ''), ''); + }; + return Animation; + })(); + exports.Animation = Animation; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/dom/shared_styles_host", ["angular2/src/platform/dom/dom_adapter", "angular2/src/core/di", "angular2/src/facade/collection", "angular2/src/platform/dom/dom_tokens"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); + var di_1 = require("angular2/src/core/di"); + var collection_1 = require("angular2/src/facade/collection"); + var dom_tokens_1 = require("angular2/src/platform/dom/dom_tokens"); + var SharedStylesHost = (function() { + function SharedStylesHost() { + this._styles = []; + this._stylesSet = new Set(); + } + SharedStylesHost.prototype.addStyles = function(styles) { + var _this = this; + var additions = []; + styles.forEach(function(style) { + if (!collection_1.SetWrapper.has(_this._stylesSet, style)) { + _this._stylesSet.add(style); + _this._styles.push(style); + additions.push(style); + } + }); + this.onStylesAdded(additions); + }; + SharedStylesHost.prototype.onStylesAdded = function(additions) {}; + SharedStylesHost.prototype.getAllStyles = function() { + return this._styles; + }; + SharedStylesHost = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], SharedStylesHost); + return SharedStylesHost; + })(); + exports.SharedStylesHost = SharedStylesHost; + var DomSharedStylesHost = (function(_super) { + __extends(DomSharedStylesHost, _super); + function DomSharedStylesHost(doc) { + _super.call(this); + this._hostNodes = new Set(); + this._hostNodes.add(doc.head); + } + DomSharedStylesHost.prototype._addStylesToHost = function(styles, host) { + for (var i = 0; i < styles.length; i++) { + var style = styles[i]; + dom_adapter_1.DOM.appendChild(host, dom_adapter_1.DOM.createStyleElement(style)); + } + }; + DomSharedStylesHost.prototype.addHost = function(hostNode) { + this._addStylesToHost(this._styles, hostNode); + this._hostNodes.add(hostNode); + }; + DomSharedStylesHost.prototype.removeHost = function(hostNode) { + collection_1.SetWrapper.delete(this._hostNodes, hostNode); + }; + DomSharedStylesHost.prototype.onStylesAdded = function(additions) { + var _this = this; + this._hostNodes.forEach(function(hostNode) { + _this._addStylesToHost(additions, hostNode); + }); + }; + DomSharedStylesHost = __decorate([di_1.Injectable(), __param(0, di_1.Inject(dom_tokens_1.DOCUMENT)), __metadata('design:paramtypes', [Object])], DomSharedStylesHost); + return DomSharedStylesHost; + })(SharedStylesHost); + exports.DomSharedStylesHost = DomSharedStylesHost; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/profile/profile", ["angular2/src/core/profile/wtf_impl"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var impl = require("angular2/src/core/profile/wtf_impl"); + exports.wtfEnabled = impl.detectWTF(); + function noopScope(arg0, arg1) { + return null; + } + exports.wtfCreateScope = exports.wtfEnabled ? impl.createScope : function(signature, flags) { + return noopScope; + }; + exports.wtfLeave = exports.wtfEnabled ? impl.leave : function(s, r) { + return r; + }; + exports.wtfStartTimeRange = exports.wtfEnabled ? impl.startTimeRange : function(rangeType, action) { + return null; + }; + exports.wtfEndTimeRange = exports.wtfEnabled ? impl.endTimeRange : function(r) { + return null; + }; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/change_detection_util", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/core/change_detection/constants", "angular2/src/core/change_detection/pipe_lifecycle_reflector", "angular2/src/core/change_detection/binding_record", "angular2/src/core/change_detection/directive_record"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var constants_1 = require("angular2/src/core/change_detection/constants"); + var pipe_lifecycle_reflector_1 = require("angular2/src/core/change_detection/pipe_lifecycle_reflector"); + var binding_record_1 = require("angular2/src/core/change_detection/binding_record"); + var directive_record_1 = require("angular2/src/core/change_detection/directive_record"); + var WrappedValue = (function() { + function WrappedValue(wrapped) { + this.wrapped = wrapped; + } + WrappedValue.wrap = function(value) { + var w = _wrappedValues[_wrappedIndex++ % 5]; + w.wrapped = value; + return w; + }; + return WrappedValue; + })(); + exports.WrappedValue = WrappedValue; + var _wrappedValues = [new WrappedValue(null), new WrappedValue(null), new WrappedValue(null), new WrappedValue(null), new WrappedValue(null)]; + var _wrappedIndex = 0; + var SimpleChange = (function() { + function SimpleChange(previousValue, currentValue) { + this.previousValue = previousValue; + this.currentValue = currentValue; + } + SimpleChange.prototype.isFirstChange = function() { + return this.previousValue === ChangeDetectionUtil.uninitialized; + }; + return SimpleChange; + })(); + exports.SimpleChange = SimpleChange; + var _simpleChangesIndex = 0; + var _simpleChanges = [new SimpleChange(null, null), new SimpleChange(null, null), new SimpleChange(null, null), new SimpleChange(null, null), new SimpleChange(null, null), new SimpleChange(null, null), new SimpleChange(null, null), new SimpleChange(null, null), new SimpleChange(null, null), new SimpleChange(null, null), new SimpleChange(null, null), new SimpleChange(null, null), new SimpleChange(null, null), new SimpleChange(null, null), new SimpleChange(null, null), new SimpleChange(null, null), new SimpleChange(null, null), new SimpleChange(null, null), new SimpleChange(null, null), new SimpleChange(null, null)]; + function _simpleChange(previousValue, currentValue) { + var index = _simpleChangesIndex++ % 20; + var s = _simpleChanges[index]; + s.previousValue = previousValue; + s.currentValue = currentValue; + return s; + } + var ChangeDetectionUtil = (function() { + function ChangeDetectionUtil() {} + ChangeDetectionUtil.arrayFn0 = function() { + return []; + }; + ChangeDetectionUtil.arrayFn1 = function(a1) { + return [a1]; + }; + ChangeDetectionUtil.arrayFn2 = function(a1, a2) { + return [a1, a2]; + }; + ChangeDetectionUtil.arrayFn3 = function(a1, a2, a3) { + return [a1, a2, a3]; + }; + ChangeDetectionUtil.arrayFn4 = function(a1, a2, a3, a4) { + return [a1, a2, a3, a4]; + }; + ChangeDetectionUtil.arrayFn5 = function(a1, a2, a3, a4, a5) { + return [a1, a2, a3, a4, a5]; + }; + ChangeDetectionUtil.arrayFn6 = function(a1, a2, a3, a4, a5, a6) { + return [a1, a2, a3, a4, a5, a6]; + }; + ChangeDetectionUtil.arrayFn7 = function(a1, a2, a3, a4, a5, a6, a7) { + return [a1, a2, a3, a4, a5, a6, a7]; + }; + ChangeDetectionUtil.arrayFn8 = function(a1, a2, a3, a4, a5, a6, a7, a8) { + return [a1, a2, a3, a4, a5, a6, a7, a8]; + }; + ChangeDetectionUtil.arrayFn9 = function(a1, a2, a3, a4, a5, a6, a7, a8, a9) { + return [a1, a2, a3, a4, a5, a6, a7, a8, a9]; + }; + ChangeDetectionUtil.operation_negate = function(value) { + return !value; + }; + ChangeDetectionUtil.operation_add = function(left, right) { + return left + right; + }; + ChangeDetectionUtil.operation_subtract = function(left, right) { + return left - right; + }; + ChangeDetectionUtil.operation_multiply = function(left, right) { + return left * right; + }; + ChangeDetectionUtil.operation_divide = function(left, right) { + return left / right; + }; + ChangeDetectionUtil.operation_remainder = function(left, right) { + return left % right; + }; + ChangeDetectionUtil.operation_equals = function(left, right) { + return left == right; + }; + ChangeDetectionUtil.operation_not_equals = function(left, right) { + return left != right; + }; + ChangeDetectionUtil.operation_identical = function(left, right) { + return left === right; + }; + ChangeDetectionUtil.operation_not_identical = function(left, right) { + return left !== right; + }; + ChangeDetectionUtil.operation_less_then = function(left, right) { + return left < right; + }; + ChangeDetectionUtil.operation_greater_then = function(left, right) { + return left > right; + }; + ChangeDetectionUtil.operation_less_or_equals_then = function(left, right) { + return left <= right; + }; + ChangeDetectionUtil.operation_greater_or_equals_then = function(left, right) { + return left >= right; + }; + ChangeDetectionUtil.cond = function(cond, trueVal, falseVal) { + return cond ? trueVal : falseVal; + }; + ChangeDetectionUtil.mapFn = function(keys) { + function buildMap(values) { + var res = collection_1.StringMapWrapper.create(); + for (var i = 0; i < keys.length; ++i) { + collection_1.StringMapWrapper.set(res, keys[i], values[i]); + } + return res; + } + switch (keys.length) { + case 0: + return function() { + return []; + }; + case 1: + return function(a1) { + return buildMap([a1]); + }; + case 2: + return function(a1, a2) { + return buildMap([a1, a2]); + }; + case 3: + return function(a1, a2, a3) { + return buildMap([a1, a2, a3]); + }; + case 4: + return function(a1, a2, a3, a4) { + return buildMap([a1, a2, a3, a4]); + }; + case 5: + return function(a1, a2, a3, a4, a5) { + return buildMap([a1, a2, a3, a4, a5]); + }; + case 6: + return function(a1, a2, a3, a4, a5, a6) { + return buildMap([a1, a2, a3, a4, a5, a6]); + }; + case 7: + return function(a1, a2, a3, a4, a5, a6, a7) { + return buildMap([a1, a2, a3, a4, a5, a6, a7]); + }; + case 8: + return function(a1, a2, a3, a4, a5, a6, a7, a8) { + return buildMap([a1, a2, a3, a4, a5, a6, a7, a8]); + }; + case 9: + return function(a1, a2, a3, a4, a5, a6, a7, a8, a9) { + return buildMap([a1, a2, a3, a4, a5, a6, a7, a8, a9]); + }; + default: + throw new exceptions_1.BaseException("Does not support literal maps with more than 9 elements"); + } + }; + ChangeDetectionUtil.keyedAccess = function(obj, args) { + return obj[args[0]]; + }; + ChangeDetectionUtil.unwrapValue = function(value) { + if (value instanceof WrappedValue) { + return value.wrapped; + } else { + return value; + } + }; + ChangeDetectionUtil.changeDetectionMode = function(strategy) { + return constants_1.isDefaultChangeDetectionStrategy(strategy) ? constants_1.ChangeDetectionStrategy.CheckAlways : constants_1.ChangeDetectionStrategy.CheckOnce; + }; + ChangeDetectionUtil.simpleChange = function(previousValue, currentValue) { + return _simpleChange(previousValue, currentValue); + }; + ChangeDetectionUtil.isValueBlank = function(value) { + return lang_1.isBlank(value); + }; + ChangeDetectionUtil.s = function(value) { + return lang_1.isPresent(value) ? "" + value : ''; + }; + ChangeDetectionUtil.protoByIndex = function(protos, selfIndex) { + return selfIndex < 1 ? null : protos[selfIndex - 1]; + }; + ChangeDetectionUtil.callPipeOnDestroy = function(selectedPipe) { + if (pipe_lifecycle_reflector_1.implementsOnDestroy(selectedPipe.pipe)) { + selectedPipe.pipe.ngOnDestroy(); + } + }; + ChangeDetectionUtil.bindingTarget = function(mode, elementIndex, name, unit, debug) { + return new binding_record_1.BindingTarget(mode, elementIndex, name, unit, debug); + }; + ChangeDetectionUtil.directiveIndex = function(elementIndex, directiveIndex) { + return new directive_record_1.DirectiveIndex(elementIndex, directiveIndex); + }; + ChangeDetectionUtil.looseNotIdentical = function(a, b) { + return !lang_1.looseIdentical(a, b); + }; + ChangeDetectionUtil.uninitialized = lang_1.CONST_EXPR(new Object()); + return ChangeDetectionUtil; + })(); + exports.ChangeDetectionUtil = ChangeDetectionUtil; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/abstract_change_detector", ["angular2/src/facade/lang", "angular2/src/facade/collection", "angular2/src/core/change_detection/change_detection_util", "angular2/src/core/change_detection/change_detector_ref", "angular2/src/core/change_detection/exceptions", "angular2/src/core/change_detection/constants", "angular2/src/core/profile/profile", "angular2/src/core/change_detection/observable_facade"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var collection_1 = require("angular2/src/facade/collection"); + var change_detection_util_1 = require("angular2/src/core/change_detection/change_detection_util"); + var change_detector_ref_1 = require("angular2/src/core/change_detection/change_detector_ref"); + var exceptions_1 = require("angular2/src/core/change_detection/exceptions"); + var constants_1 = require("angular2/src/core/change_detection/constants"); + var profile_1 = require("angular2/src/core/profile/profile"); + var observable_facade_1 = require("angular2/src/core/change_detection/observable_facade"); + var _scope_check = profile_1.wtfCreateScope("ChangeDetector#check(ascii id, bool throwOnChange)"); + var _Context = (function() { + function _Context(element, componentElement, context, locals, injector, expression) { + this.element = element; + this.componentElement = componentElement; + this.context = context; + this.locals = locals; + this.injector = injector; + this.expression = expression; + } + return _Context; + })(); + var AbstractChangeDetector = (function() { + function AbstractChangeDetector(id, dispatcher, numberOfPropertyProtoRecords, bindingTargets, directiveIndices, strategy) { + this.id = id; + this.dispatcher = dispatcher; + this.numberOfPropertyProtoRecords = numberOfPropertyProtoRecords; + this.bindingTargets = bindingTargets; + this.directiveIndices = directiveIndices; + this.strategy = strategy; + this.contentChildren = []; + this.viewChildren = []; + this.state = constants_1.ChangeDetectorState.NeverChecked; + this.locals = null; + this.mode = null; + this.pipes = null; + this.ref = new change_detector_ref_1.ChangeDetectorRef_(this); + } + AbstractChangeDetector.prototype.addContentChild = function(cd) { + this.contentChildren.push(cd); + cd.parent = this; + }; + AbstractChangeDetector.prototype.removeContentChild = function(cd) { + collection_1.ListWrapper.remove(this.contentChildren, cd); + }; + AbstractChangeDetector.prototype.addViewChild = function(cd) { + this.viewChildren.push(cd); + cd.parent = this; + }; + AbstractChangeDetector.prototype.removeViewChild = function(cd) { + collection_1.ListWrapper.remove(this.viewChildren, cd); + }; + AbstractChangeDetector.prototype.remove = function() { + this.parent.removeContentChild(this); + }; + AbstractChangeDetector.prototype.handleEvent = function(eventName, elIndex, locals) { + var res = this.handleEventInternal(eventName, elIndex, locals); + this.markPathToRootAsCheckOnce(); + return res; + }; + AbstractChangeDetector.prototype.handleEventInternal = function(eventName, elIndex, locals) { + return false; + }; + AbstractChangeDetector.prototype.detectChanges = function() { + this.runDetectChanges(false); + }; + AbstractChangeDetector.prototype.checkNoChanges = function() { + if (lang_1.assertionsEnabled()) { + this.runDetectChanges(true); + } + }; + AbstractChangeDetector.prototype.runDetectChanges = function(throwOnChange) { + if (this.mode === constants_1.ChangeDetectionStrategy.Detached || this.mode === constants_1.ChangeDetectionStrategy.Checked || this.state === constants_1.ChangeDetectorState.Errored) + return ; + var s = _scope_check(this.id, throwOnChange); + this.detectChangesInRecords(throwOnChange); + this._detectChangesContentChildren(throwOnChange); + if (!throwOnChange) + this.afterContentLifecycleCallbacks(); + this._detectChangesInViewChildren(throwOnChange); + if (!throwOnChange) + this.afterViewLifecycleCallbacks(); + if (this.mode === constants_1.ChangeDetectionStrategy.CheckOnce) + this.mode = constants_1.ChangeDetectionStrategy.Checked; + this.state = constants_1.ChangeDetectorState.CheckedBefore; + profile_1.wtfLeave(s); + }; + AbstractChangeDetector.prototype.detectChangesInRecords = function(throwOnChange) { + if (!this.hydrated()) { + this.throwDehydratedError(); + } + try { + this.detectChangesInRecordsInternal(throwOnChange); + } catch (e) { + if (!(e instanceof exceptions_1.ExpressionChangedAfterItHasBeenCheckedException)) { + this.state = constants_1.ChangeDetectorState.Errored; + } + this._throwError(e, e.stack); + } + }; + AbstractChangeDetector.prototype.detectChangesInRecordsInternal = function(throwOnChange) {}; + AbstractChangeDetector.prototype.hydrate = function(context, locals, directives, pipes) { + this.mode = change_detection_util_1.ChangeDetectionUtil.changeDetectionMode(this.strategy); + this.context = context; + if (this.strategy === constants_1.ChangeDetectionStrategy.OnPushObserve) { + this.observeComponent(context); + } + this.locals = locals; + this.pipes = pipes; + this.hydrateDirectives(directives); + this.state = constants_1.ChangeDetectorState.NeverChecked; + }; + AbstractChangeDetector.prototype.hydrateDirectives = function(directives) {}; + AbstractChangeDetector.prototype.dehydrate = function() { + this.dehydrateDirectives(true); + if (this.strategy === constants_1.ChangeDetectionStrategy.OnPushObserve) { + this._unsubsribeFromObservables(); + } + this.context = null; + this.locals = null; + this.pipes = null; + }; + AbstractChangeDetector.prototype.dehydrateDirectives = function(destroyPipes) {}; + AbstractChangeDetector.prototype.hydrated = function() { + return lang_1.isPresent(this.context); + }; + AbstractChangeDetector.prototype.afterContentLifecycleCallbacks = function() { + this.dispatcher.notifyAfterContentChecked(); + this.afterContentLifecycleCallbacksInternal(); + }; + AbstractChangeDetector.prototype.afterContentLifecycleCallbacksInternal = function() {}; + AbstractChangeDetector.prototype.afterViewLifecycleCallbacks = function() { + this.dispatcher.notifyAfterViewChecked(); + this.afterViewLifecycleCallbacksInternal(); + }; + AbstractChangeDetector.prototype.afterViewLifecycleCallbacksInternal = function() {}; + AbstractChangeDetector.prototype._detectChangesContentChildren = function(throwOnChange) { + var c = this.contentChildren; + for (var i = 0; i < c.length; ++i) { + c[i].runDetectChanges(throwOnChange); + } + }; + AbstractChangeDetector.prototype._detectChangesInViewChildren = function(throwOnChange) { + var c = this.viewChildren; + for (var i = 0; i < c.length; ++i) { + c[i].runDetectChanges(throwOnChange); + } + }; + AbstractChangeDetector.prototype.markAsCheckOnce = function() { + this.mode = constants_1.ChangeDetectionStrategy.CheckOnce; + }; + AbstractChangeDetector.prototype.markPathToRootAsCheckOnce = function() { + var c = this; + while (lang_1.isPresent(c) && c.mode !== constants_1.ChangeDetectionStrategy.Detached) { + if (c.mode === constants_1.ChangeDetectionStrategy.Checked) + c.mode = constants_1.ChangeDetectionStrategy.CheckOnce; + c = c.parent; + } + }; + AbstractChangeDetector.prototype._unsubsribeFromObservables = function() { + if (lang_1.isPresent(this.subscriptions)) { + for (var i = 0; i < this.subscriptions.length; ++i) { + var s = this.subscriptions[i]; + if (lang_1.isPresent(this.subscriptions[i])) { + s.cancel(); + this.subscriptions[i] = null; + } + } + } + }; + AbstractChangeDetector.prototype.observeValue = function(value, index) { + var _this = this; + if (observable_facade_1.isObservable(value)) { + this._createArrayToStoreObservables(); + if (lang_1.isBlank(this.subscriptions[index])) { + this.streams[index] = value.changes; + this.subscriptions[index] = value.changes.listen(function(_) { + return _this.ref.markForCheck(); + }); + } else if (this.streams[index] !== value.changes) { + this.subscriptions[index].cancel(); + this.streams[index] = value.changes; + this.subscriptions[index] = value.changes.listen(function(_) { + return _this.ref.markForCheck(); + }); + } + } + return value; + }; + AbstractChangeDetector.prototype.observeDirective = function(value, index) { + var _this = this; + if (observable_facade_1.isObservable(value)) { + this._createArrayToStoreObservables(); + var arrayIndex = this.numberOfPropertyProtoRecords + index + 2; + this.streams[arrayIndex] = value.changes; + this.subscriptions[arrayIndex] = value.changes.listen(function(_) { + return _this.ref.markForCheck(); + }); + } + return value; + }; + AbstractChangeDetector.prototype.observeComponent = function(value) { + var _this = this; + if (observable_facade_1.isObservable(value)) { + this._createArrayToStoreObservables(); + var index = this.numberOfPropertyProtoRecords + 1; + this.streams[index] = value.changes; + this.subscriptions[index] = value.changes.listen(function(_) { + return _this.ref.markForCheck(); + }); + } + return value; + }; + AbstractChangeDetector.prototype._createArrayToStoreObservables = function() { + if (lang_1.isBlank(this.subscriptions)) { + this.subscriptions = collection_1.ListWrapper.createFixedSize(this.numberOfPropertyProtoRecords + this.directiveIndices.length + 2); + this.streams = collection_1.ListWrapper.createFixedSize(this.numberOfPropertyProtoRecords + this.directiveIndices.length + 2); + } + }; + AbstractChangeDetector.prototype.getDirectiveFor = function(directives, index) { + return directives.getDirectiveFor(this.directiveIndices[index]); + }; + AbstractChangeDetector.prototype.getDetectorFor = function(directives, index) { + return directives.getDetectorFor(this.directiveIndices[index]); + }; + AbstractChangeDetector.prototype.notifyDispatcher = function(value) { + this.dispatcher.notifyOnBinding(this._currentBinding(), value); + }; + AbstractChangeDetector.prototype.logBindingUpdate = function(value) { + this.dispatcher.logBindingUpdate(this._currentBinding(), value); + }; + AbstractChangeDetector.prototype.addChange = function(changes, oldValue, newValue) { + if (lang_1.isBlank(changes)) { + changes = {}; + } + changes[this._currentBinding().name] = change_detection_util_1.ChangeDetectionUtil.simpleChange(oldValue, newValue); + return changes; + }; + AbstractChangeDetector.prototype._throwError = function(exception, stack) { + var error; + try { + var c = this.dispatcher.getDebugContext(this._currentBinding().elementIndex, null); + var context = lang_1.isPresent(c) ? new _Context(c.element, c.componentElement, c.context, c.locals, c.injector, this._currentBinding().debug) : null; + error = new exceptions_1.ChangeDetectionError(this._currentBinding().debug, exception, stack, context); + } catch (e) { + error = new exceptions_1.ChangeDetectionError(null, exception, stack, null); + } + throw error; + }; + AbstractChangeDetector.prototype.throwOnChangeError = function(oldValue, newValue) { + throw new exceptions_1.ExpressionChangedAfterItHasBeenCheckedException(this._currentBinding().debug, oldValue, newValue, null); + }; + AbstractChangeDetector.prototype.throwDehydratedError = function() { + throw new exceptions_1.DehydratedException(); + }; + AbstractChangeDetector.prototype._currentBinding = function() { + return this.bindingTargets[this.propertyBindingIndex]; + }; + return AbstractChangeDetector; + })(); + exports.AbstractChangeDetector = AbstractChangeDetector; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/codegen_logic_util", ["angular2/src/facade/lang", "angular2/src/core/change_detection/codegen_facade", "angular2/src/core/change_detection/proto_record", "angular2/src/core/change_detection/constants", "angular2/src/facade/exceptions"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var codegen_facade_1 = require("angular2/src/core/change_detection/codegen_facade"); + var proto_record_1 = require("angular2/src/core/change_detection/proto_record"); + var constants_1 = require("angular2/src/core/change_detection/constants"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var CodegenLogicUtil = (function() { + function CodegenLogicUtil(_names, _utilName, _changeDetectorStateName, _changeDetection) { + this._names = _names; + this._utilName = _utilName; + this._changeDetectorStateName = _changeDetectorStateName; + this._changeDetection = _changeDetection; + } + CodegenLogicUtil.prototype.genPropertyBindingEvalValue = function(protoRec) { + var _this = this; + return this._genEvalValue(protoRec, function(idx) { + return _this._names.getLocalName(idx); + }, this._names.getLocalsAccessorName()); + }; + CodegenLogicUtil.prototype.genEventBindingEvalValue = function(eventRecord, protoRec) { + var _this = this; + return this._genEvalValue(protoRec, function(idx) { + return _this._names.getEventLocalName(eventRecord, idx); + }, "locals"); + }; + CodegenLogicUtil.prototype._genEvalValue = function(protoRec, getLocalName, localsAccessor) { + var context = (protoRec.contextIndex == -1) ? this._names.getDirectiveName(protoRec.directiveIndex) : getLocalName(protoRec.contextIndex); + var argString = protoRec.args.map(function(arg) { + return getLocalName(arg); + }).join(", "); + var rhs; + switch (protoRec.mode) { + case proto_record_1.RecordType.Self: + rhs = context; + break; + case proto_record_1.RecordType.Const: + rhs = codegen_facade_1.codify(protoRec.funcOrValue); + break; + case proto_record_1.RecordType.PropertyRead: + rhs = this._observe(context + "." + protoRec.name, protoRec); + break; + case proto_record_1.RecordType.SafeProperty: + var read = this._observe(context + "." + protoRec.name, protoRec); + rhs = this._utilName + ".isValueBlank(" + context + ") ? null : " + this._observe(read, protoRec); + break; + case proto_record_1.RecordType.PropertyWrite: + rhs = context + "." + protoRec.name + " = " + getLocalName(protoRec.args[0]); + break; + case proto_record_1.RecordType.Local: + rhs = this._observe(localsAccessor + ".get(" + codegen_facade_1.rawString(protoRec.name) + ")", protoRec); + break; + case proto_record_1.RecordType.InvokeMethod: + rhs = this._observe(context + "." + protoRec.name + "(" + argString + ")", protoRec); + break; + case proto_record_1.RecordType.SafeMethodInvoke: + var invoke = context + "." + protoRec.name + "(" + argString + ")"; + rhs = this._utilName + ".isValueBlank(" + context + ") ? null : " + this._observe(invoke, protoRec); + break; + case proto_record_1.RecordType.InvokeClosure: + rhs = context + "(" + argString + ")"; + break; + case proto_record_1.RecordType.PrimitiveOp: + rhs = this._utilName + "." + protoRec.name + "(" + argString + ")"; + break; + case proto_record_1.RecordType.CollectionLiteral: + rhs = this._utilName + "." + protoRec.name + "(" + argString + ")"; + break; + case proto_record_1.RecordType.Interpolate: + rhs = this._genInterpolation(protoRec); + break; + case proto_record_1.RecordType.KeyedRead: + rhs = this._observe(context + "[" + getLocalName(protoRec.args[0]) + "]", protoRec); + break; + case proto_record_1.RecordType.KeyedWrite: + rhs = context + "[" + getLocalName(protoRec.args[0]) + "] = " + getLocalName(protoRec.args[1]); + break; + case proto_record_1.RecordType.Chain: + rhs = 'null'; + break; + default: + throw new exceptions_1.BaseException("Unknown operation " + protoRec.mode); + } + return getLocalName(protoRec.selfIndex) + " = " + rhs + ";"; + }; + CodegenLogicUtil.prototype._observe = function(exp, rec) { + if (this._changeDetection === constants_1.ChangeDetectionStrategy.OnPushObserve) { + return "this.observeValue(" + exp + ", " + rec.selfIndex + ")"; + } else { + return exp; + } + }; + CodegenLogicUtil.prototype.genPropertyBindingTargets = function(propertyBindingTargets, genDebugInfo) { + var _this = this; + var bs = propertyBindingTargets.map(function(b) { + if (lang_1.isBlank(b)) + return "null"; + var debug = genDebugInfo ? codegen_facade_1.codify(b.debug) : "null"; + return _this._utilName + ".bindingTarget(" + codegen_facade_1.codify(b.mode) + ", " + b.elementIndex + ", " + codegen_facade_1.codify(b.name) + ", " + codegen_facade_1.codify(b.unit) + ", " + debug + ")"; + }); + return "[" + bs.join(", ") + "]"; + }; + CodegenLogicUtil.prototype.genDirectiveIndices = function(directiveRecords) { + var _this = this; + var bs = directiveRecords.map(function(b) { + return (_this._utilName + ".directiveIndex(" + b.directiveIndex.elementIndex + ", " + b.directiveIndex.directiveIndex + ")"); + }); + return "[" + bs.join(", ") + "]"; + }; + CodegenLogicUtil.prototype._genInterpolation = function(protoRec) { + var iVals = []; + for (var i = 0; i < protoRec.args.length; ++i) { + iVals.push(codegen_facade_1.codify(protoRec.fixedArgs[i])); + iVals.push(this._utilName + ".s(" + this._names.getLocalName(protoRec.args[i]) + ")"); + } + iVals.push(codegen_facade_1.codify(protoRec.fixedArgs[protoRec.args.length])); + return codegen_facade_1.combineGeneratedStrings(iVals); + }; + CodegenLogicUtil.prototype.genHydrateDirectives = function(directiveRecords) { + var res = []; + for (var i = 0; i < directiveRecords.length; ++i) { + var r = directiveRecords[i]; + res.push(this._names.getDirectiveName(r.directiveIndex) + " = " + this._genReadDirective(i) + ";"); + } + return res.join("\n"); + }; + CodegenLogicUtil.prototype._genReadDirective = function(index) { + if (this._changeDetection === constants_1.ChangeDetectionStrategy.OnPushObserve) { + return "this.observeDirective(this.getDirectiveFor(directives, " + index + "), " + index + ")"; + } else { + return "this.getDirectiveFor(directives, " + index + ")"; + } + }; + CodegenLogicUtil.prototype.genHydrateDetectors = function(directiveRecords) { + var res = []; + for (var i = 0; i < directiveRecords.length; ++i) { + var r = directiveRecords[i]; + if (!r.isDefaultChangeDetection()) { + res.push(this._names.getDetectorName(r.directiveIndex) + " = this.getDetectorFor(directives, " + i + ");"); + } + } + return res.join("\n"); + }; + CodegenLogicUtil.prototype.genContentLifecycleCallbacks = function(directiveRecords) { + var res = []; + var eq = lang_1.IS_DART ? '==' : '==='; + for (var i = directiveRecords.length - 1; i >= 0; --i) { + var dir = directiveRecords[i]; + if (dir.callAfterContentInit) { + res.push("if(" + this._names.getStateName() + " " + eq + " " + this._changeDetectorStateName + ".NeverChecked) " + this._names.getDirectiveName(dir.directiveIndex) + ".ngAfterContentInit();"); + } + if (dir.callAfterContentChecked) { + res.push(this._names.getDirectiveName(dir.directiveIndex) + ".ngAfterContentChecked();"); + } + } + return res; + }; + CodegenLogicUtil.prototype.genViewLifecycleCallbacks = function(directiveRecords) { + var res = []; + var eq = lang_1.IS_DART ? '==' : '==='; + for (var i = directiveRecords.length - 1; i >= 0; --i) { + var dir = directiveRecords[i]; + if (dir.callAfterViewInit) { + res.push("if(" + this._names.getStateName() + " " + eq + " " + this._changeDetectorStateName + ".NeverChecked) " + this._names.getDirectiveName(dir.directiveIndex) + ".ngAfterViewInit();"); + } + if (dir.callAfterViewChecked) { + res.push(this._names.getDirectiveName(dir.directiveIndex) + ".ngAfterViewChecked();"); + } + } + return res; + }; + return CodegenLogicUtil; + })(); + exports.CodegenLogicUtil = CodegenLogicUtil; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/pipes/pipes", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/core/change_detection/pipes"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var cd = require("angular2/src/core/change_detection/pipes"); + var ProtoPipes = (function() { + function ProtoPipes(config) { + this.config = config; + this.config = config; + } + ProtoPipes.fromProviders = function(providers) { + var config = {}; + providers.forEach(function(b) { + return config[b.name] = b; + }); + return new ProtoPipes(config); + }; + ProtoPipes.prototype.get = function(name) { + var provider = this.config[name]; + if (lang_1.isBlank(provider)) + throw new exceptions_1.BaseException("Cannot find pipe '" + name + "'."); + return provider; + }; + return ProtoPipes; + })(); + exports.ProtoPipes = ProtoPipes; + var Pipes = (function() { + function Pipes(proto, injector) { + this.proto = proto; + this.injector = injector; + this._config = {}; + } + Pipes.prototype.get = function(name) { + var cached = collection_1.StringMapWrapper.get(this._config, name); + if (lang_1.isPresent(cached)) + return cached; + var p = this.proto.get(name); + var transform = this.injector.instantiateResolved(p); + var res = new cd.SelectedPipe(transform, p.pure); + if (p.pure) { + collection_1.StringMapWrapper.set(this._config, name, res); + } + return res; + }; + return Pipes; + })(); + exports.Pipes = Pipes; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/view", ["angular2/src/facade/collection", "angular2/src/core/change_detection/change_detection", "angular2/src/core/change_detection/interfaces", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/core/linker/view_ref", "angular2/src/core/render/util", "angular2/src/core/linker/view_ref", "angular2/src/core/change_detection/interfaces"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var collection_1 = require("angular2/src/facade/collection"); + var change_detection_1 = require("angular2/src/core/change_detection/change_detection"); + var interfaces_1 = require("angular2/src/core/change_detection/interfaces"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var view_ref_1 = require("angular2/src/core/linker/view_ref"); + var util_1 = require("angular2/src/core/render/util"); + var view_ref_2 = require("angular2/src/core/linker/view_ref"); + var interfaces_2 = require("angular2/src/core/change_detection/interfaces"); + exports.DebugContext = interfaces_2.DebugContext; + var REFLECT_PREFIX = 'ng-reflect-'; + (function(ViewType) { + ViewType[ViewType["HOST"] = 0] = "HOST"; + ViewType[ViewType["COMPONENT"] = 1] = "COMPONENT"; + ViewType[ViewType["EMBEDDED"] = 2] = "EMBEDDED"; + })(exports.ViewType || (exports.ViewType = {})); + var ViewType = exports.ViewType; + var AppViewContainer = (function() { + function AppViewContainer() { + this.views = []; + } + return AppViewContainer; + })(); + exports.AppViewContainer = AppViewContainer; + var AppView = (function() { + function AppView(renderer, proto, viewOffset, elementOffset, textOffset, protoLocals, render, renderFragment, containerElementInjector) { + this.renderer = renderer; + this.proto = proto; + this.viewOffset = viewOffset; + this.elementOffset = elementOffset; + this.textOffset = textOffset; + this.render = render; + this.renderFragment = renderFragment; + this.containerElementInjector = containerElementInjector; + this.views = null; + this.elementInjectors = null; + this.viewContainers = null; + this.preBuiltObjects = null; + this.changeDetector = null; + this.context = null; + this.ref = new view_ref_2.ViewRef_(this); + this.locals = new change_detection_1.Locals(null, collection_1.MapWrapper.clone(protoLocals)); + } + AppView.prototype.init = function(changeDetector, elementInjectors, rootElementInjectors, preBuiltObjects, views, elementRefs, viewContainers) { + this.changeDetector = changeDetector; + this.elementInjectors = elementInjectors; + this.rootElementInjectors = rootElementInjectors; + this.preBuiltObjects = preBuiltObjects; + this.views = views; + this.elementRefs = elementRefs; + this.viewContainers = viewContainers; + }; + AppView.prototype.setLocal = function(contextName, value) { + if (!this.hydrated()) + throw new exceptions_1.BaseException('Cannot set locals on dehydrated view.'); + if (!this.proto.templateVariableBindings.has(contextName)) { + return ; + } + var templateName = this.proto.templateVariableBindings.get(contextName); + this.locals.set(templateName, value); + }; + AppView.prototype.hydrated = function() { + return lang_1.isPresent(this.context); + }; + AppView.prototype.triggerEventHandlers = function(eventName, eventObj, boundElementIndex) { + var locals = new collection_1.Map(); + locals.set('$event', eventObj); + this.dispatchEvent(boundElementIndex, eventName, locals); + }; + AppView.prototype.notifyOnBinding = function(b, currentValue) { + if (b.isTextNode()) { + this.renderer.setText(this.render, b.elementIndex + this.textOffset, currentValue); + } else { + var elementRef = this.elementRefs[this.elementOffset + b.elementIndex]; + if (b.isElementProperty()) { + this.renderer.setElementProperty(elementRef, b.name, currentValue); + } else if (b.isElementAttribute()) { + this.renderer.setElementAttribute(elementRef, b.name, lang_1.isPresent(currentValue) ? "" + currentValue : null); + } else if (b.isElementClass()) { + this.renderer.setElementClass(elementRef, b.name, currentValue); + } else if (b.isElementStyle()) { + var unit = lang_1.isPresent(b.unit) ? b.unit : ''; + this.renderer.setElementStyle(elementRef, b.name, lang_1.isPresent(currentValue) ? "" + currentValue + unit : null); + } else { + throw new exceptions_1.BaseException('Unsupported directive record'); + } + } + }; + AppView.prototype.logBindingUpdate = function(b, value) { + if (b.isDirective() || b.isElementProperty()) { + var elementRef = this.elementRefs[this.elementOffset + b.elementIndex]; + this.renderer.setBindingDebugInfo(elementRef, "" + REFLECT_PREFIX + util_1.camelCaseToDashCase(b.name), "" + value); + } + }; + AppView.prototype.notifyAfterContentChecked = function() { + var eiCount = this.proto.elementBinders.length; + var ei = this.elementInjectors; + for (var i = eiCount - 1; i >= 0; i--) { + if (lang_1.isPresent(ei[i + this.elementOffset])) + ei[i + this.elementOffset].ngAfterContentChecked(); + } + }; + AppView.prototype.notifyAfterViewChecked = function() { + var eiCount = this.proto.elementBinders.length; + var ei = this.elementInjectors; + for (var i = eiCount - 1; i >= 0; i--) { + if (lang_1.isPresent(ei[i + this.elementOffset])) + ei[i + this.elementOffset].ngAfterViewChecked(); + } + }; + AppView.prototype.getDirectiveFor = function(directive) { + var elementInjector = this.elementInjectors[this.elementOffset + directive.elementIndex]; + return elementInjector.getDirectiveAtIndex(directive.directiveIndex); + }; + AppView.prototype.getNestedView = function(boundElementIndex) { + var eli = this.elementInjectors[boundElementIndex]; + return lang_1.isPresent(eli) ? eli.getNestedView() : null; + }; + AppView.prototype.getContainerElement = function() { + return lang_1.isPresent(this.containerElementInjector) ? this.containerElementInjector.getElementRef() : null; + }; + AppView.prototype.getDebugContext = function(elementIndex, directiveIndex) { + try { + var offsettedIndex = this.elementOffset + elementIndex; + var hasRefForIndex = offsettedIndex < this.elementRefs.length; + var elementRef = hasRefForIndex ? this.elementRefs[this.elementOffset + elementIndex] : null; + var container = this.getContainerElement(); + var ei = hasRefForIndex ? this.elementInjectors[this.elementOffset + elementIndex] : null; + var element = lang_1.isPresent(elementRef) ? elementRef.nativeElement : null; + var componentElement = lang_1.isPresent(container) ? container.nativeElement : null; + var directive = lang_1.isPresent(directiveIndex) ? this.getDirectiveFor(directiveIndex) : null; + var injector = lang_1.isPresent(ei) ? ei.getInjector() : null; + return new interfaces_1.DebugContext(element, componentElement, directive, this.context, _localsToStringMap(this.locals), injector); + } catch (e) { + return null; + } + }; + AppView.prototype.getDetectorFor = function(directive) { + var childView = this.getNestedView(this.elementOffset + directive.elementIndex); + return lang_1.isPresent(childView) ? childView.changeDetector : null; + }; + AppView.prototype.invokeElementMethod = function(elementIndex, methodName, args) { + this.renderer.invokeElementMethod(this.elementRefs[elementIndex], methodName, args); + }; + AppView.prototype.dispatchRenderEvent = function(boundElementIndex, eventName, locals) { + var elementRef = this.elementRefs[boundElementIndex]; + var view = view_ref_1.internalView(elementRef.parentView); + return view.dispatchEvent(elementRef.boundElementIndex, eventName, locals); + }; + AppView.prototype.dispatchEvent = function(boundElementIndex, eventName, locals) { + try { + if (this.hydrated()) { + return !this.changeDetector.handleEvent(eventName, boundElementIndex - this.elementOffset, new change_detection_1.Locals(this.locals, locals)); + } else { + return true; + } + } catch (e) { + var c = this.getDebugContext(boundElementIndex - this.elementOffset, null); + var context = lang_1.isPresent(c) ? new _Context(c.element, c.componentElement, c.context, c.locals, c.injector) : null; + throw new EventEvaluationError(eventName, e, e.stack, context); + } + }; + Object.defineProperty(AppView.prototype, "ownBindersCount", { + get: function() { + return this.proto.elementBinders.length; + }, + enumerable: true, + configurable: true + }); + return AppView; + })(); + exports.AppView = AppView; + function _localsToStringMap(locals) { + var res = {}; + var c = locals; + while (lang_1.isPresent(c)) { + res = collection_1.StringMapWrapper.merge(res, collection_1.MapWrapper.toStringMap(c.current)); + c = c.parent; + } + return res; + } + var _Context = (function() { + function _Context(element, componentElement, context, locals, injector) { + this.element = element; + this.componentElement = componentElement; + this.context = context; + this.locals = locals; + this.injector = injector; + } + return _Context; + })(); + var EventEvaluationError = (function(_super) { + __extends(EventEvaluationError, _super); + function EventEvaluationError(eventName, originalException, originalStack, context) { + _super.call(this, "Error during evaluation of \"" + eventName + "\"", originalException, originalStack, context); + } + return EventEvaluationError; + })(exceptions_1.WrappedException); + var AppProtoViewMergeInfo = (function() { + function AppProtoViewMergeInfo(embeddedViewCount, elementCount, viewCount) { + this.embeddedViewCount = embeddedViewCount; + this.elementCount = elementCount; + this.viewCount = viewCount; + } + return AppProtoViewMergeInfo; + })(); + exports.AppProtoViewMergeInfo = AppProtoViewMergeInfo; + var AppProtoView = (function() { + function AppProtoView(templateId, templateCmds, type, isMergable, changeDetectorFactory, templateVariableBindings, pipes) { + this.templateId = templateId; + this.templateCmds = templateCmds; + this.type = type; + this.isMergable = isMergable; + this.changeDetectorFactory = changeDetectorFactory; + this.templateVariableBindings = templateVariableBindings; + this.pipes = pipes; + this.elementBinders = null; + this.mergeInfo = null; + this.variableLocations = null; + this.textBindingCount = null; + this.render = null; + this.ref = new view_ref_2.ProtoViewRef_(this); + } + AppProtoView.prototype.init = function(render, elementBinders, textBindingCount, mergeInfo, variableLocations) { + var _this = this; + this.render = render; + this.elementBinders = elementBinders; + this.textBindingCount = textBindingCount; + this.mergeInfo = mergeInfo; + this.variableLocations = variableLocations; + this.protoLocals = new collection_1.Map(); + if (lang_1.isPresent(this.templateVariableBindings)) { + this.templateVariableBindings.forEach(function(templateName, _) { + _this.protoLocals.set(templateName, null); + }); + } + if (lang_1.isPresent(variableLocations)) { + variableLocations.forEach(function(_, templateName) { + _this.protoLocals.set(templateName, null); + }); + } + }; + AppProtoView.prototype.isInitialized = function() { + return lang_1.isPresent(this.elementBinders); + }; + return AppProtoView; + })(); + exports.AppProtoView = AppProtoView; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/view_manager_utils", ["angular2/src/core/di", "angular2/src/facade/collection", "angular2/src/core/linker/element_injector", "angular2/src/facade/lang", "angular2/src/core/linker/view", "angular2/src/core/linker/element_ref", "angular2/src/core/linker/template_ref", "angular2/src/core/pipes/pipes"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var di_1 = require("angular2/src/core/di"); + var collection_1 = require("angular2/src/facade/collection"); + var eli = require("angular2/src/core/linker/element_injector"); + var lang_1 = require("angular2/src/facade/lang"); + var viewModule = require("angular2/src/core/linker/view"); + var element_ref_1 = require("angular2/src/core/linker/element_ref"); + var template_ref_1 = require("angular2/src/core/linker/template_ref"); + var pipes_1 = require("angular2/src/core/pipes/pipes"); + var AppViewManagerUtils = (function() { + function AppViewManagerUtils() {} + AppViewManagerUtils.prototype.getComponentInstance = function(parentView, boundElementIndex) { + var eli = parentView.elementInjectors[boundElementIndex]; + return eli.getComponent(); + }; + AppViewManagerUtils.prototype.createView = function(mergedParentViewProto, renderViewWithFragments, viewManager, renderer) { + var renderFragments = renderViewWithFragments.fragmentRefs; + var renderView = renderViewWithFragments.viewRef; + var elementCount = mergedParentViewProto.mergeInfo.elementCount; + var viewCount = mergedParentViewProto.mergeInfo.viewCount; + var elementRefs = collection_1.ListWrapper.createFixedSize(elementCount); + var viewContainers = collection_1.ListWrapper.createFixedSize(elementCount); + var preBuiltObjects = collection_1.ListWrapper.createFixedSize(elementCount); + var elementInjectors = collection_1.ListWrapper.createFixedSize(elementCount); + var views = collection_1.ListWrapper.createFixedSize(viewCount); + var elementOffset = 0; + var textOffset = 0; + var fragmentIdx = 0; + var containerElementIndicesByViewIndex = collection_1.ListWrapper.createFixedSize(viewCount); + for (var viewOffset = 0; viewOffset < viewCount; viewOffset++) { + var containerElementIndex = containerElementIndicesByViewIndex[viewOffset]; + var containerElementInjector = lang_1.isPresent(containerElementIndex) ? elementInjectors[containerElementIndex] : null; + var parentView = lang_1.isPresent(containerElementInjector) ? preBuiltObjects[containerElementIndex].view : null; + var protoView = lang_1.isPresent(containerElementIndex) ? parentView.proto.elementBinders[containerElementIndex - parentView.elementOffset].nestedProtoView : mergedParentViewProto; + var renderFragment = null; + if (viewOffset === 0 || protoView.type === viewModule.ViewType.EMBEDDED) { + renderFragment = renderFragments[fragmentIdx++]; + } + var currentView = new viewModule.AppView(renderer, protoView, viewOffset, elementOffset, textOffset, protoView.protoLocals, renderView, renderFragment, containerElementInjector); + views[viewOffset] = currentView; + if (lang_1.isPresent(containerElementIndex)) { + preBuiltObjects[containerElementIndex].nestedView = currentView; + } + var rootElementInjectors = []; + var nestedViewOffset = viewOffset + 1; + for (var binderIdx = 0; binderIdx < protoView.elementBinders.length; binderIdx++) { + var binder = protoView.elementBinders[binderIdx]; + var boundElementIndex = elementOffset + binderIdx; + var elementInjector = null; + if (lang_1.isPresent(binder.nestedProtoView) && binder.nestedProtoView.isMergable) { + containerElementIndicesByViewIndex[nestedViewOffset] = boundElementIndex; + nestedViewOffset += binder.nestedProtoView.mergeInfo.viewCount; + } + var protoElementInjector = binder.protoElementInjector; + if (lang_1.isPresent(protoElementInjector)) { + if (lang_1.isPresent(protoElementInjector.parent)) { + var parentElementInjector = elementInjectors[elementOffset + protoElementInjector.parent.index]; + elementInjector = protoElementInjector.instantiate(parentElementInjector); + } else { + elementInjector = protoElementInjector.instantiate(null); + rootElementInjectors.push(elementInjector); + } + } + elementInjectors[boundElementIndex] = elementInjector; + var el = new element_ref_1.ElementRef_(currentView.ref, boundElementIndex, renderer); + elementRefs[el.boundElementIndex] = el; + if (lang_1.isPresent(elementInjector)) { + var templateRef = lang_1.isPresent(binder.nestedProtoView) && binder.nestedProtoView.type === viewModule.ViewType.EMBEDDED ? new template_ref_1.TemplateRef_(el) : null; + preBuiltObjects[boundElementIndex] = new eli.PreBuiltObjects(viewManager, currentView, el, templateRef); + } + } + currentView.init(protoView.changeDetectorFactory(currentView), elementInjectors, rootElementInjectors, preBuiltObjects, views, elementRefs, viewContainers); + if (lang_1.isPresent(parentView) && protoView.type === viewModule.ViewType.COMPONENT) { + parentView.changeDetector.addViewChild(currentView.changeDetector); + } + elementOffset += protoView.elementBinders.length; + textOffset += protoView.textBindingCount; + } + return views[0]; + }; + AppViewManagerUtils.prototype.hydrateRootHostView = function(hostView, injector) { + this._hydrateView(hostView, injector, null, new Object(), null); + }; + AppViewManagerUtils.prototype.attachViewInContainer = function(parentView, boundElementIndex, contextView, contextBoundElementIndex, index, view) { + if (lang_1.isBlank(contextView)) { + contextView = parentView; + contextBoundElementIndex = boundElementIndex; + } + parentView.changeDetector.addContentChild(view.changeDetector); + var viewContainer = parentView.viewContainers[boundElementIndex]; + if (lang_1.isBlank(viewContainer)) { + viewContainer = new viewModule.AppViewContainer(); + parentView.viewContainers[boundElementIndex] = viewContainer; + } + collection_1.ListWrapper.insert(viewContainer.views, index, view); + var elementInjector = contextView.elementInjectors[contextBoundElementIndex]; + for (var i = view.rootElementInjectors.length - 1; i >= 0; i--) { + if (lang_1.isPresent(elementInjector.parent)) { + view.rootElementInjectors[i].link(elementInjector.parent); + } + } + elementInjector.traverseAndSetQueriesAsDirty(); + }; + AppViewManagerUtils.prototype.detachViewInContainer = function(parentView, boundElementIndex, index) { + var viewContainer = parentView.viewContainers[boundElementIndex]; + var view = viewContainer.views[index]; + parentView.elementInjectors[boundElementIndex].traverseAndSetQueriesAsDirty(); + view.changeDetector.remove(); + collection_1.ListWrapper.removeAt(viewContainer.views, index); + for (var i = 0; i < view.rootElementInjectors.length; ++i) { + var inj = view.rootElementInjectors[i]; + inj.unlink(); + } + }; + AppViewManagerUtils.prototype.hydrateViewInContainer = function(parentView, boundElementIndex, contextView, contextBoundElementIndex, index, imperativelyCreatedProviders) { + if (lang_1.isBlank(contextView)) { + contextView = parentView; + contextBoundElementIndex = boundElementIndex; + } + var viewContainer = parentView.viewContainers[boundElementIndex]; + var view = viewContainer.views[index]; + var elementInjector = contextView.elementInjectors[contextBoundElementIndex]; + var injector = lang_1.isPresent(imperativelyCreatedProviders) ? di_1.Injector.fromResolvedProviders(imperativelyCreatedProviders) : null; + this._hydrateView(view, injector, elementInjector.getHost(), contextView.context, contextView.locals); + }; + AppViewManagerUtils.prototype._hydrateView = function(initView, imperativelyCreatedInjector, hostElementInjector, context, parentLocals) { + var viewIdx = initView.viewOffset; + var endViewOffset = viewIdx + initView.proto.mergeInfo.viewCount - 1; + while (viewIdx <= endViewOffset) { + var currView = initView.views[viewIdx]; + var currProtoView = currView.proto; + if (currView !== initView && currView.proto.type === viewModule.ViewType.EMBEDDED) { + viewIdx += currView.proto.mergeInfo.viewCount; + } else { + if (currView !== initView) { + imperativelyCreatedInjector = null; + parentLocals = null; + hostElementInjector = currView.containerElementInjector; + context = hostElementInjector.getComponent(); + } + currView.context = context; + currView.locals.parent = parentLocals; + var binders = currProtoView.elementBinders; + for (var binderIdx = 0; binderIdx < binders.length; binderIdx++) { + var boundElementIndex = binderIdx + currView.elementOffset; + var elementInjector = initView.elementInjectors[boundElementIndex]; + if (lang_1.isPresent(elementInjector)) { + elementInjector.hydrate(imperativelyCreatedInjector, hostElementInjector, currView.preBuiltObjects[boundElementIndex]); + this._populateViewLocals(currView, elementInjector, boundElementIndex); + this._setUpEventEmitters(currView, elementInjector, boundElementIndex); + } + } + var pipes = lang_1.isPresent(hostElementInjector) ? new pipes_1.Pipes(currView.proto.pipes, hostElementInjector.getInjector()) : null; + currView.changeDetector.hydrate(currView.context, currView.locals, currView, pipes); + viewIdx++; + } + } + }; + AppViewManagerUtils.prototype._populateViewLocals = function(view, elementInjector, boundElementIdx) { + if (lang_1.isPresent(elementInjector.getDirectiveVariableBindings())) { + elementInjector.getDirectiveVariableBindings().forEach(function(directiveIndex, name) { + if (lang_1.isBlank(directiveIndex)) { + view.locals.set(name, view.elementRefs[boundElementIdx].nativeElement); + } else { + view.locals.set(name, elementInjector.getDirectiveAtIndex(directiveIndex)); + } + }); + } + }; + AppViewManagerUtils.prototype._setUpEventEmitters = function(view, elementInjector, boundElementIndex) { + var emitters = elementInjector.getEventEmitterAccessors(); + for (var directiveIndex = 0; directiveIndex < emitters.length; ++directiveIndex) { + var directiveEmitters = emitters[directiveIndex]; + var directive = elementInjector.getDirectiveAtIndex(directiveIndex); + for (var eventIndex = 0; eventIndex < directiveEmitters.length; ++eventIndex) { + var eventEmitterAccessor = directiveEmitters[eventIndex]; + eventEmitterAccessor.subscribe(view, boundElementIndex, directive); + } + } + }; + AppViewManagerUtils.prototype.dehydrateView = function(initView) { + var endViewOffset = initView.viewOffset + initView.proto.mergeInfo.viewCount - 1; + for (var viewIdx = initView.viewOffset; viewIdx <= endViewOffset; viewIdx++) { + var currView = initView.views[viewIdx]; + if (currView.hydrated()) { + if (lang_1.isPresent(currView.locals)) { + currView.locals.clearValues(); + } + currView.context = null; + currView.changeDetector.dehydrate(); + var binders = currView.proto.elementBinders; + for (var binderIdx = 0; binderIdx < binders.length; binderIdx++) { + var eli = initView.elementInjectors[currView.elementOffset + binderIdx]; + if (lang_1.isPresent(eli)) { + eli.dehydrate(); + } + } + } + } + }; + AppViewManagerUtils = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], AppViewManagerUtils); + return AppViewManagerUtils; + })(); + exports.AppViewManagerUtils = AppViewManagerUtils; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/directive_lifecycle_reflector", ["angular2/src/facade/lang", "angular2/src/core/linker/interfaces"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var interfaces_1 = require("angular2/src/core/linker/interfaces"); + function hasLifecycleHook(lcInterface, token) { + if (!(token instanceof lang_1.Type)) + return false; + var proto = token.prototype; + switch (lcInterface) { + case interfaces_1.LifecycleHooks.AfterContentInit: + return !!proto.ngAfterContentInit; + case interfaces_1.LifecycleHooks.AfterContentChecked: + return !!proto.ngAfterContentChecked; + case interfaces_1.LifecycleHooks.AfterViewInit: + return !!proto.ngAfterViewInit; + case interfaces_1.LifecycleHooks.AfterViewChecked: + return !!proto.ngAfterViewChecked; + case interfaces_1.LifecycleHooks.OnChanges: + return !!proto.ngOnChanges; + case interfaces_1.LifecycleHooks.DoCheck: + return !!proto.ngDoCheck; + case interfaces_1.LifecycleHooks.OnDestroy: + return !!proto.ngOnDestroy; + case interfaces_1.LifecycleHooks.OnInit: + return !!proto.ngOnInit; + default: + return false; + } + } + exports.hasLifecycleHook = hasLifecycleHook; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/render/view_factory", ["angular2/src/facade/lang", "angular2/src/core/render/view", "angular2/src/core/metadata", "angular2/src/facade/collection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var view_1 = require("angular2/src/core/render/view"); + var metadata_1 = require("angular2/src/core/metadata"); + var collection_1 = require("angular2/src/facade/collection"); + function encapsulateStyles(componentTemplate) { + var processedStyles = componentTemplate.styles; + if (componentTemplate.encapsulation === metadata_1.ViewEncapsulation.Emulated) { + processedStyles = collection_1.ListWrapper.createFixedSize(componentTemplate.styles.length); + for (var i = 0; i < componentTemplate.styles.length; i++) { + processedStyles[i] = lang_1.StringWrapper.replaceAll(componentTemplate.styles[i], COMPONENT_REGEX, componentTemplate.shortId); + } + } + return processedStyles; + } + exports.encapsulateStyles = encapsulateStyles; + function createRenderView(componentTemplate, cmds, inplaceElement, nodeFactory) { + var view; + var eventDispatcher = function(boundElementIndex, eventName, event) { + return view.dispatchRenderEvent(boundElementIndex, eventName, event); + }; + var context = new BuildContext(eventDispatcher, nodeFactory, inplaceElement); + context.build(componentTemplate, cmds); + var fragments = []; + for (var i = 0; i < context.fragments.length; i++) { + fragments.push(new view_1.DefaultRenderFragmentRef(context.fragments[i])); + } + view = new view_1.DefaultRenderView(fragments, context.boundTextNodes, context.boundElements, context.nativeShadowRoots, context.globalEventAdders, context.rootContentInsertionPoints); + return view; + } + exports.createRenderView = createRenderView; + var BuildContext = (function() { + function BuildContext(_eventDispatcher, factory, _inplaceElement) { + this._eventDispatcher = _eventDispatcher; + this.factory = factory; + this._inplaceElement = _inplaceElement; + this._builders = []; + this.globalEventAdders = []; + this.boundElements = []; + this.boundTextNodes = []; + this.nativeShadowRoots = []; + this.fragments = []; + this.rootContentInsertionPoints = []; + this.componentCount = 0; + this.isHost = lang_1.isPresent((_inplaceElement)); + } + BuildContext.prototype.build = function(template, cmds) { + this.enqueueRootBuilder(template, cmds); + this._build(this._builders[0]); + }; + BuildContext.prototype._build = function(builder) { + this._builders = []; + builder.build(this); + var enqueuedBuilders = this._builders; + for (var i = 0; i < enqueuedBuilders.length; i++) { + this._build(enqueuedBuilders[i]); + } + }; + BuildContext.prototype.enqueueComponentBuilder = function(component) { + this.componentCount++; + this._builders.push(new RenderViewBuilder(component, null, component.template, component.template.commands)); + }; + BuildContext.prototype.enqueueFragmentBuilder = function(parentComponent, parentTemplate, commands) { + var rootNodes = []; + this.fragments.push(rootNodes); + this._builders.push(new RenderViewBuilder(parentComponent, rootNodes, parentTemplate, commands)); + }; + BuildContext.prototype.enqueueRootBuilder = function(template, cmds) { + var rootNodes = []; + this.fragments.push(rootNodes); + this._builders.push(new RenderViewBuilder(null, rootNodes, template, cmds)); + }; + BuildContext.prototype.consumeInplaceElement = function() { + var result = this._inplaceElement; + this._inplaceElement = null; + return result; + }; + BuildContext.prototype.addEventListener = function(boundElementIndex, target, eventName) { + if (lang_1.isPresent(target)) { + var handler = createEventHandler(boundElementIndex, target + ":" + eventName, this._eventDispatcher); + this.globalEventAdders.push(createGlobalEventAdder(target, eventName, handler, this.factory)); + } else { + var handler = createEventHandler(boundElementIndex, eventName, this._eventDispatcher); + this.factory.on(this.boundElements[boundElementIndex], eventName, handler); + } + }; + return BuildContext; + })(); + function createEventHandler(boundElementIndex, eventName, eventDispatcher) { + return function($event) { + return eventDispatcher(boundElementIndex, eventName, $event); + }; + } + function createGlobalEventAdder(target, eventName, eventHandler, nodeFactory) { + return function() { + return nodeFactory.globalOn(target, eventName, eventHandler); + }; + } + var RenderViewBuilder = (function() { + function RenderViewBuilder(parentComponent, fragmentRootNodes, template, cmds) { + this.parentComponent = parentComponent; + this.fragmentRootNodes = fragmentRootNodes; + this.template = template; + this.cmds = cmds; + var rootNodesParent = lang_1.isPresent(fragmentRootNodes) ? null : parentComponent.shadowRoot; + this.parentStack = [rootNodesParent]; + } + RenderViewBuilder.prototype.build = function(context) { + var cmds = this.cmds; + for (var i = 0; i < cmds.length; i++) { + cmds[i].visit(this, context); + } + }; + Object.defineProperty(RenderViewBuilder.prototype, "parent", { + get: function() { + return this.parentStack[this.parentStack.length - 1]; + }, + enumerable: true, + configurable: true + }); + RenderViewBuilder.prototype.visitText = function(cmd, context) { + var text = context.factory.createText(cmd.value); + this._addChild(text, cmd.ngContentIndex, context); + if (cmd.isBound) { + context.boundTextNodes.push(text); + } + return null; + }; + RenderViewBuilder.prototype.visitNgContent = function(cmd, context) { + if (lang_1.isPresent(this.parentComponent)) { + if (this.parentComponent.isRoot) { + var insertionPoint = context.factory.createRootContentInsertionPoint(); + if (this.parent instanceof Component) { + context.factory.appendChild(this.parent.shadowRoot, insertionPoint); + } else { + context.factory.appendChild(this.parent, insertionPoint); + } + context.rootContentInsertionPoints.push(insertionPoint); + } else { + var projectedNodes = this.parentComponent.project(cmd.index); + for (var i = 0; i < projectedNodes.length; i++) { + var node = projectedNodes[i]; + this._addChild(node, cmd.ngContentIndex, context); + } + } + } + return null; + }; + RenderViewBuilder.prototype.visitBeginElement = function(cmd, context) { + this.parentStack.push(this._beginElement(cmd, context, null)); + return null; + }; + RenderViewBuilder.prototype.visitEndElement = function(context) { + this._endElement(); + return null; + }; + RenderViewBuilder.prototype.visitBeginComponent = function(cmd, context) { + var templateId = cmd.templateId; + var tpl = context.factory.resolveComponentTemplate(templateId); + var el = this._beginElement(cmd, context, tpl); + var root = el; + if (tpl.encapsulation === metadata_1.ViewEncapsulation.Native) { + root = context.factory.createShadowRoot(el, templateId); + context.nativeShadowRoots.push(root); + } + var isRoot = context.componentCount === 0 && context.isHost; + var component = new Component(el, root, isRoot, tpl); + context.enqueueComponentBuilder(component); + this.parentStack.push(component); + return null; + }; + RenderViewBuilder.prototype.visitEndComponent = function(context) { + this._endElement(); + return null; + }; + RenderViewBuilder.prototype.visitEmbeddedTemplate = function(cmd, context) { + var el = context.factory.createTemplateAnchor(cmd.attrNameAndValues); + this._addChild(el, cmd.ngContentIndex, context); + context.boundElements.push(el); + if (cmd.isMerged) { + context.enqueueFragmentBuilder(this.parentComponent, this.template, cmd.children); + } + return null; + }; + RenderViewBuilder.prototype._beginElement = function(cmd, context, componentTemplate) { + var el = context.consumeInplaceElement(); + var attrNameAndValues = cmd.attrNameAndValues; + var templateEmulatedEncapsulation = this.template.encapsulation === metadata_1.ViewEncapsulation.Emulated; + var componentEmulatedEncapsulation = lang_1.isPresent(componentTemplate) && componentTemplate.encapsulation === metadata_1.ViewEncapsulation.Emulated; + var newAttrLength = attrNameAndValues.length + (templateEmulatedEncapsulation ? 2 : 0) + (componentEmulatedEncapsulation ? 2 : 0); + if (newAttrLength > attrNameAndValues.length) { + var newAttrNameAndValues = collection_1.ListWrapper.createFixedSize(newAttrLength); + var attrIndex; + for (attrIndex = 0; attrIndex < attrNameAndValues.length; attrIndex++) { + newAttrNameAndValues[attrIndex] = attrNameAndValues[attrIndex]; + } + if (templateEmulatedEncapsulation) { + newAttrNameAndValues[attrIndex++] = _shimContentAttribute(this.template.shortId); + newAttrNameAndValues[attrIndex++] = ''; + } + if (componentEmulatedEncapsulation) { + newAttrNameAndValues[attrIndex++] = _shimHostAttribute(componentTemplate.shortId); + newAttrNameAndValues[attrIndex++] = ''; + } + attrNameAndValues = newAttrNameAndValues; + } + if (lang_1.isPresent(el)) { + context.factory.mergeElement(el, attrNameAndValues); + this.fragmentRootNodes.push(el); + } else { + el = context.factory.createElement(cmd.name, attrNameAndValues); + this._addChild(el, cmd.ngContentIndex, context); + } + if (cmd.isBound) { + var boundElementIndex = context.boundElements.length; + context.boundElements.push(el); + for (var i = 0; i < cmd.eventTargetAndNames.length; i += 2) { + var target = cmd.eventTargetAndNames[i]; + var eventName = cmd.eventTargetAndNames[i + 1]; + context.addEventListener(boundElementIndex, target, eventName); + } + } + return el; + }; + RenderViewBuilder.prototype._endElement = function() { + this.parentStack.pop(); + }; + RenderViewBuilder.prototype._addChild = function(node, ngContentIndex, context) { + var parent = this.parent; + if (lang_1.isPresent(parent)) { + if (parent instanceof Component) { + parent.addContentNode(ngContentIndex, node, context); + } else { + context.factory.appendChild(parent, node); + } + } else { + this.fragmentRootNodes.push(node); + } + }; + return RenderViewBuilder; + })(); + var Component = (function() { + function Component(hostElement, shadowRoot, isRoot, template) { + this.hostElement = hostElement; + this.shadowRoot = shadowRoot; + this.isRoot = isRoot; + this.template = template; + this.contentNodesByNgContentIndex = []; + } + Component.prototype.addContentNode = function(ngContentIndex, node, context) { + if (lang_1.isBlank(ngContentIndex)) { + if (this.template.encapsulation === metadata_1.ViewEncapsulation.Native) { + context.factory.appendChild(this.hostElement, node); + } + } else { + while (this.contentNodesByNgContentIndex.length <= ngContentIndex) { + this.contentNodesByNgContentIndex.push([]); + } + this.contentNodesByNgContentIndex[ngContentIndex].push(node); + } + }; + Component.prototype.project = function(ngContentIndex) { + return ngContentIndex < this.contentNodesByNgContentIndex.length ? this.contentNodesByNgContentIndex[ngContentIndex] : []; + }; + return Component; + })(); + var COMPONENT_REGEX = /%COMP%/g; + exports.COMPONENT_VARIABLE = '%COMP%'; + exports.HOST_ATTR = "_nghost-" + exports.COMPONENT_VARIABLE; + exports.CONTENT_ATTR = "_ngcontent-" + exports.COMPONENT_VARIABLE; + function _shimContentAttribute(componentShortId) { + return lang_1.StringWrapper.replaceAll(exports.CONTENT_ATTR, COMPONENT_REGEX, componentShortId); + } + function _shimHostAttribute(componentShortId) { + return lang_1.StringWrapper.replaceAll(exports.HOST_ATTR, COMPONENT_REGEX, componentShortId); + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/di/provider", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/core/reflection/reflection", "angular2/src/core/di/key", "angular2/src/core/di/metadata", "angular2/src/core/di/exceptions", "angular2/src/core/di/forward_ref"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var reflection_1 = require("angular2/src/core/reflection/reflection"); + var key_1 = require("angular2/src/core/di/key"); + var metadata_1 = require("angular2/src/core/di/metadata"); + var exceptions_2 = require("angular2/src/core/di/exceptions"); + var forward_ref_1 = require("angular2/src/core/di/forward_ref"); + var Dependency = (function() { + function Dependency(key, optional, lowerBoundVisibility, upperBoundVisibility, properties) { + this.key = key; + this.optional = optional; + this.lowerBoundVisibility = lowerBoundVisibility; + this.upperBoundVisibility = upperBoundVisibility; + this.properties = properties; + } + Dependency.fromKey = function(key) { + return new Dependency(key, false, null, null, []); + }; + return Dependency; + })(); + exports.Dependency = Dependency; + var _EMPTY_LIST = lang_1.CONST_EXPR([]); + var Provider = (function() { + function Provider(token, _a) { + var useClass = _a.useClass, + useValue = _a.useValue, + useExisting = _a.useExisting, + useFactory = _a.useFactory, + deps = _a.deps, + multi = _a.multi; + this.token = token; + this.useClass = useClass; + this.useValue = useValue; + this.useExisting = useExisting; + this.useFactory = useFactory; + this.dependencies = deps; + this._multi = multi; + } + Object.defineProperty(Provider.prototype, "multi", { + get: function() { + return lang_1.normalizeBool(this._multi); + }, + enumerable: true, + configurable: true + }); + Provider = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object, Object])], Provider); + return Provider; + })(); + exports.Provider = Provider; + var Binding = (function(_super) { + __extends(Binding, _super); + function Binding(token, _a) { + var toClass = _a.toClass, + toValue = _a.toValue, + toAlias = _a.toAlias, + toFactory = _a.toFactory, + deps = _a.deps, + multi = _a.multi; + _super.call(this, token, { + useClass: toClass, + useValue: toValue, + useExisting: toAlias, + useFactory: toFactory, + deps: deps, + multi: multi + }); + } + Object.defineProperty(Binding.prototype, "toClass", { + get: function() { + return this.useClass; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Binding.prototype, "toAlias", { + get: function() { + return this.useExisting; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Binding.prototype, "toFactory", { + get: function() { + return this.useFactory; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Binding.prototype, "toValue", { + get: function() { + return this.useValue; + }, + enumerable: true, + configurable: true + }); + Binding = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object, Object])], Binding); + return Binding; + })(Provider); + exports.Binding = Binding; + var ResolvedProvider_ = (function() { + function ResolvedProvider_(key, resolvedFactories, multiProvider) { + this.key = key; + this.resolvedFactories = resolvedFactories; + this.multiProvider = multiProvider; + } + Object.defineProperty(ResolvedProvider_.prototype, "resolvedFactory", { + get: function() { + return this.resolvedFactories[0]; + }, + enumerable: true, + configurable: true + }); + return ResolvedProvider_; + })(); + exports.ResolvedProvider_ = ResolvedProvider_; + var ResolvedFactory = (function() { + function ResolvedFactory(factory, dependencies) { + this.factory = factory; + this.dependencies = dependencies; + } + return ResolvedFactory; + })(); + exports.ResolvedFactory = ResolvedFactory; + function bind(token) { + return new ProviderBuilder(token); + } + exports.bind = bind; + function provide(token, _a) { + var useClass = _a.useClass, + useValue = _a.useValue, + useExisting = _a.useExisting, + useFactory = _a.useFactory, + deps = _a.deps, + multi = _a.multi; + return new Provider(token, { + useClass: useClass, + useValue: useValue, + useExisting: useExisting, + useFactory: useFactory, + deps: deps, + multi: multi + }); + } + exports.provide = provide; + var ProviderBuilder = (function() { + function ProviderBuilder(token) { + this.token = token; + } + ProviderBuilder.prototype.toClass = function(type) { + if (!lang_1.isType(type)) { + throw new exceptions_1.BaseException("Trying to create a class provider but \"" + lang_1.stringify(type) + "\" is not a class!"); + } + return new Provider(this.token, {useClass: type}); + }; + ProviderBuilder.prototype.toValue = function(value) { + return new Provider(this.token, {useValue: value}); + }; + ProviderBuilder.prototype.toAlias = function(aliasToken) { + if (lang_1.isBlank(aliasToken)) { + throw new exceptions_1.BaseException("Can not alias " + lang_1.stringify(this.token) + " to a blank value!"); + } + return new Provider(this.token, {useExisting: aliasToken}); + }; + ProviderBuilder.prototype.toFactory = function(factory, dependencies) { + if (!lang_1.isFunction(factory)) { + throw new exceptions_1.BaseException("Trying to create a factory provider but \"" + lang_1.stringify(factory) + "\" is not a function!"); + } + return new Provider(this.token, { + useFactory: factory, + deps: dependencies + }); + }; + return ProviderBuilder; + })(); + exports.ProviderBuilder = ProviderBuilder; + function resolveFactory(provider) { + var factoryFn; + var resolvedDeps; + if (lang_1.isPresent(provider.useClass)) { + var useClass = forward_ref_1.resolveForwardRef(provider.useClass); + factoryFn = reflection_1.reflector.factory(useClass); + resolvedDeps = _dependenciesFor(useClass); + } else if (lang_1.isPresent(provider.useExisting)) { + factoryFn = function(aliasInstance) { + return aliasInstance; + }; + resolvedDeps = [Dependency.fromKey(key_1.Key.get(provider.useExisting))]; + } else if (lang_1.isPresent(provider.useFactory)) { + factoryFn = provider.useFactory; + resolvedDeps = _constructDependencies(provider.useFactory, provider.dependencies); + } else { + factoryFn = function() { + return provider.useValue; + }; + resolvedDeps = _EMPTY_LIST; + } + return new ResolvedFactory(factoryFn, resolvedDeps); + } + exports.resolveFactory = resolveFactory; + function resolveProvider(provider) { + return new ResolvedProvider_(key_1.Key.get(provider.token), [resolveFactory(provider)], false); + } + exports.resolveProvider = resolveProvider; + function resolveProviders(providers) { + var normalized = _createListOfProviders(_normalizeProviders(providers, new Map())); + return normalized.map(function(b) { + if (b instanceof _NormalizedProvider) { + return new ResolvedProvider_(b.key, [b.resolvedFactory], false); + } else { + var arr = b; + return new ResolvedProvider_(arr[0].key, arr.map(function(_) { + return _.resolvedFactory; + }), true); + } + }); + } + exports.resolveProviders = resolveProviders; + var _NormalizedProvider = (function() { + function _NormalizedProvider(key, resolvedFactory) { + this.key = key; + this.resolvedFactory = resolvedFactory; + } + return _NormalizedProvider; + })(); + function _createListOfProviders(flattenedProviders) { + return collection_1.MapWrapper.values(flattenedProviders); + } + function _normalizeProviders(providers, res) { + providers.forEach(function(b) { + if (b instanceof lang_1.Type) { + _normalizeProvider(provide(b, {useClass: b}), res); + } else if (b instanceof Provider) { + _normalizeProvider(b, res); + } else if (b instanceof Array) { + _normalizeProviders(b, res); + } else if (b instanceof ProviderBuilder) { + throw new exceptions_2.InvalidProviderError(b.token); + } else { + throw new exceptions_2.InvalidProviderError(b); + } + }); + return res; + } + function _normalizeProvider(b, res) { + var key = key_1.Key.get(b.token); + var factory = resolveFactory(b); + var normalized = new _NormalizedProvider(key, factory); + if (b.multi) { + var existingProvider = res.get(key.id); + if (existingProvider instanceof Array) { + existingProvider.push(normalized); + } else if (lang_1.isBlank(existingProvider)) { + res.set(key.id, [normalized]); + } else { + throw new exceptions_2.MixingMultiProvidersWithRegularProvidersError(existingProvider, b); + } + } else { + var existingProvider = res.get(key.id); + if (existingProvider instanceof Array) { + throw new exceptions_2.MixingMultiProvidersWithRegularProvidersError(existingProvider, b); + } + res.set(key.id, normalized); + } + } + function _constructDependencies(factoryFunction, dependencies) { + if (lang_1.isBlank(dependencies)) { + return _dependenciesFor(factoryFunction); + } else { + var params = dependencies.map(function(t) { + return [t]; + }); + return dependencies.map(function(t) { + return _extractToken(factoryFunction, t, params); + }); + } + } + function _dependenciesFor(typeOrFunc) { + var params = reflection_1.reflector.parameters(typeOrFunc); + if (lang_1.isBlank(params)) + return []; + if (params.some(lang_1.isBlank)) { + throw new exceptions_2.NoAnnotationError(typeOrFunc, params); + } + return params.map(function(p) { + return _extractToken(typeOrFunc, p, params); + }); + } + function _extractToken(typeOrFunc, metadata, params) { + var depProps = []; + var token = null; + var optional = false; + if (!lang_1.isArray(metadata)) { + if (metadata instanceof metadata_1.InjectMetadata) { + return _createDependency(metadata.token, optional, null, null, depProps); + } else { + return _createDependency(metadata, optional, null, null, depProps); + } + } + var lowerBoundVisibility = null; + var upperBoundVisibility = null; + for (var i = 0; i < metadata.length; ++i) { + var paramMetadata = metadata[i]; + if (paramMetadata instanceof lang_1.Type) { + token = paramMetadata; + } else if (paramMetadata instanceof metadata_1.InjectMetadata) { + token = paramMetadata.token; + } else if (paramMetadata instanceof metadata_1.OptionalMetadata) { + optional = true; + } else if (paramMetadata instanceof metadata_1.SelfMetadata) { + upperBoundVisibility = paramMetadata; + } else if (paramMetadata instanceof metadata_1.HostMetadata) { + upperBoundVisibility = paramMetadata; + } else if (paramMetadata instanceof metadata_1.SkipSelfMetadata) { + lowerBoundVisibility = paramMetadata; + } else if (paramMetadata instanceof metadata_1.DependencyMetadata) { + if (lang_1.isPresent(paramMetadata.token)) { + token = paramMetadata.token; + } + depProps.push(paramMetadata); + } + } + token = forward_ref_1.resolveForwardRef(token); + if (lang_1.isPresent(token)) { + return _createDependency(token, optional, lowerBoundVisibility, upperBoundVisibility, depProps); + } else { + throw new exceptions_2.NoAnnotationError(typeOrFunc, params); + } + } + function _createDependency(token, optional, lowerBoundVisibility, upperBoundVisibility, depProps) { + return new Dependency(key_1.Key.get(token), optional, lowerBoundVisibility, upperBoundVisibility, depProps); + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/animate/css_animation_builder", ["angular2/src/animate/css_animation_options", "angular2/src/animate/animation"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var css_animation_options_1 = require("angular2/src/animate/css_animation_options"); + var animation_1 = require("angular2/src/animate/animation"); + var CssAnimationBuilder = (function() { + function CssAnimationBuilder(browserDetails) { + this.browserDetails = browserDetails; + this.data = new css_animation_options_1.CssAnimationOptions(); + } + CssAnimationBuilder.prototype.addAnimationClass = function(className) { + this.data.animationClasses.push(className); + return this; + }; + CssAnimationBuilder.prototype.addClass = function(className) { + this.data.classesToAdd.push(className); + return this; + }; + CssAnimationBuilder.prototype.removeClass = function(className) { + this.data.classesToRemove.push(className); + return this; + }; + CssAnimationBuilder.prototype.setDuration = function(duration) { + this.data.duration = duration; + return this; + }; + CssAnimationBuilder.prototype.setDelay = function(delay) { + this.data.delay = delay; + return this; + }; + CssAnimationBuilder.prototype.setStyles = function(from, to) { + return this.setFromStyles(from).setToStyles(to); + }; + CssAnimationBuilder.prototype.setFromStyles = function(from) { + this.data.fromStyles = from; + return this; + }; + CssAnimationBuilder.prototype.setToStyles = function(to) { + this.data.toStyles = to; + return this; + }; + CssAnimationBuilder.prototype.start = function(element) { + return new animation_1.Animation(element, this.data, this.browserDetails); + }; + return CssAnimationBuilder; + })(); + exports.CssAnimationBuilder = CssAnimationBuilder; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/dynamic_change_detector", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/core/change_detection/abstract_change_detector", "angular2/src/core/change_detection/change_detection_util", "angular2/src/core/change_detection/constants", "angular2/src/core/change_detection/proto_record"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var abstract_change_detector_1 = require("angular2/src/core/change_detection/abstract_change_detector"); + var change_detection_util_1 = require("angular2/src/core/change_detection/change_detection_util"); + var constants_1 = require("angular2/src/core/change_detection/constants"); + var proto_record_1 = require("angular2/src/core/change_detection/proto_record"); + var DynamicChangeDetector = (function(_super) { + __extends(DynamicChangeDetector, _super); + function DynamicChangeDetector(id, dispatcher, numberOfPropertyProtoRecords, propertyBindingTargets, directiveIndices, strategy, _records, _eventBindings, _directiveRecords, _genConfig) { + _super.call(this, id, dispatcher, numberOfPropertyProtoRecords, propertyBindingTargets, directiveIndices, strategy); + this._records = _records; + this._eventBindings = _eventBindings; + this._directiveRecords = _directiveRecords; + this._genConfig = _genConfig; + this.directives = null; + var len = _records.length + 1; + this.values = collection_1.ListWrapper.createFixedSize(len); + this.localPipes = collection_1.ListWrapper.createFixedSize(len); + this.prevContexts = collection_1.ListWrapper.createFixedSize(len); + this.changes = collection_1.ListWrapper.createFixedSize(len); + this.dehydrateDirectives(false); + } + DynamicChangeDetector.prototype.handleEventInternal = function(eventName, elIndex, locals) { + var _this = this; + var preventDefault = false; + this._matchingEventBindings(eventName, elIndex).forEach(function(rec) { + var res = _this._processEventBinding(rec, locals); + if (res === false) { + preventDefault = true; + } + }); + return preventDefault; + }; + DynamicChangeDetector.prototype._processEventBinding = function(eb, locals) { + var values = collection_1.ListWrapper.createFixedSize(eb.records.length); + values[0] = this.values[0]; + for (var protoIdx = 0; protoIdx < eb.records.length; ++protoIdx) { + var proto = eb.records[protoIdx]; + if (proto.isSkipRecord()) { + protoIdx += this._computeSkipLength(protoIdx, proto, values); + } else { + var res = this._calculateCurrValue(proto, values, locals); + if (proto.lastInBinding) { + this._markPathAsCheckOnce(proto); + return res; + } else { + this._writeSelf(proto, res, values); + } + } + } + throw new exceptions_1.BaseException("Cannot be reached"); + }; + DynamicChangeDetector.prototype._computeSkipLength = function(protoIndex, proto, values) { + if (proto.mode === proto_record_1.RecordType.SkipRecords) { + return proto.fixedArgs[0] - protoIndex - 1; + } + if (proto.mode === proto_record_1.RecordType.SkipRecordsIf) { + var condition = this._readContext(proto, values); + return condition ? proto.fixedArgs[0] - protoIndex - 1 : 0; + } + if (proto.mode === proto_record_1.RecordType.SkipRecordsIfNot) { + var condition = this._readContext(proto, values); + return condition ? 0 : proto.fixedArgs[0] - protoIndex - 1; + } + throw new exceptions_1.BaseException("Cannot be reached"); + }; + DynamicChangeDetector.prototype._markPathAsCheckOnce = function(proto) { + if (!proto.bindingRecord.isDefaultChangeDetection()) { + var dir = proto.bindingRecord.directiveRecord; + this._getDetectorFor(dir.directiveIndex).markPathToRootAsCheckOnce(); + } + }; + DynamicChangeDetector.prototype._matchingEventBindings = function(eventName, elIndex) { + return this._eventBindings.filter(function(eb) { + return eb.eventName == eventName && eb.elIndex === elIndex; + }); + }; + DynamicChangeDetector.prototype.hydrateDirectives = function(directives) { + this.values[0] = this.context; + this.directives = directives; + if (this.strategy === constants_1.ChangeDetectionStrategy.OnPushObserve) { + for (var i = 0; i < this.directiveIndices.length; ++i) { + var index = this.directiveIndices[i]; + _super.prototype.observeDirective.call(this, directives.getDirectiveFor(index), i); + } + } + }; + DynamicChangeDetector.prototype.dehydrateDirectives = function(destroyPipes) { + if (destroyPipes) { + this._destroyPipes(); + } + this.values[0] = null; + this.directives = null; + collection_1.ListWrapper.fill(this.values, change_detection_util_1.ChangeDetectionUtil.uninitialized, 1); + collection_1.ListWrapper.fill(this.changes, false); + collection_1.ListWrapper.fill(this.localPipes, null); + collection_1.ListWrapper.fill(this.prevContexts, change_detection_util_1.ChangeDetectionUtil.uninitialized); + }; + DynamicChangeDetector.prototype._destroyPipes = function() { + for (var i = 0; i < this.localPipes.length; ++i) { + if (lang_1.isPresent(this.localPipes[i])) { + change_detection_util_1.ChangeDetectionUtil.callPipeOnDestroy(this.localPipes[i]); + } + } + }; + DynamicChangeDetector.prototype.checkNoChanges = function() { + this.runDetectChanges(true); + }; + DynamicChangeDetector.prototype.detectChangesInRecordsInternal = function(throwOnChange) { + var protos = this._records; + var changes = null; + var isChanged = false; + for (var protoIdx = 0; protoIdx < protos.length; ++protoIdx) { + var proto = protos[protoIdx]; + var bindingRecord = proto.bindingRecord; + var directiveRecord = bindingRecord.directiveRecord; + if (this._firstInBinding(proto)) { + this.propertyBindingIndex = proto.propertyBindingIndex; + } + if (proto.isLifeCycleRecord()) { + if (proto.name === "DoCheck" && !throwOnChange) { + this._getDirectiveFor(directiveRecord.directiveIndex).ngDoCheck(); + } else if (proto.name === "OnInit" && !throwOnChange && this.state == constants_1.ChangeDetectorState.NeverChecked) { + this._getDirectiveFor(directiveRecord.directiveIndex).ngOnInit(); + } else if (proto.name === "OnChanges" && lang_1.isPresent(changes) && !throwOnChange) { + this._getDirectiveFor(directiveRecord.directiveIndex).ngOnChanges(changes); + } + } else if (proto.isSkipRecord()) { + protoIdx += this._computeSkipLength(protoIdx, proto, this.values); + } else { + var change = this._check(proto, throwOnChange, this.values, this.locals); + if (lang_1.isPresent(change)) { + this._updateDirectiveOrElement(change, bindingRecord); + isChanged = true; + changes = this._addChange(bindingRecord, change, changes); + } + } + if (proto.lastInDirective) { + changes = null; + if (isChanged && !bindingRecord.isDefaultChangeDetection()) { + this._getDetectorFor(directiveRecord.directiveIndex).markAsCheckOnce(); + } + isChanged = false; + } + } + }; + DynamicChangeDetector.prototype._firstInBinding = function(r) { + var prev = change_detection_util_1.ChangeDetectionUtil.protoByIndex(this._records, r.selfIndex - 1); + return lang_1.isBlank(prev) || prev.bindingRecord !== r.bindingRecord; + }; + DynamicChangeDetector.prototype.afterContentLifecycleCallbacksInternal = function() { + var dirs = this._directiveRecords; + for (var i = dirs.length - 1; i >= 0; --i) { + var dir = dirs[i]; + if (dir.callAfterContentInit && this.state == constants_1.ChangeDetectorState.NeverChecked) { + this._getDirectiveFor(dir.directiveIndex).ngAfterContentInit(); + } + if (dir.callAfterContentChecked) { + this._getDirectiveFor(dir.directiveIndex).ngAfterContentChecked(); + } + } + }; + DynamicChangeDetector.prototype.afterViewLifecycleCallbacksInternal = function() { + var dirs = this._directiveRecords; + for (var i = dirs.length - 1; i >= 0; --i) { + var dir = dirs[i]; + if (dir.callAfterViewInit && this.state == constants_1.ChangeDetectorState.NeverChecked) { + this._getDirectiveFor(dir.directiveIndex).ngAfterViewInit(); + } + if (dir.callAfterViewChecked) { + this._getDirectiveFor(dir.directiveIndex).ngAfterViewChecked(); + } + } + }; + DynamicChangeDetector.prototype._updateDirectiveOrElement = function(change, bindingRecord) { + if (lang_1.isBlank(bindingRecord.directiveRecord)) { + _super.prototype.notifyDispatcher.call(this, change.currentValue); + } else { + var directiveIndex = bindingRecord.directiveRecord.directiveIndex; + bindingRecord.setter(this._getDirectiveFor(directiveIndex), change.currentValue); + } + if (this._genConfig.logBindingUpdate) { + _super.prototype.logBindingUpdate.call(this, change.currentValue); + } + }; + DynamicChangeDetector.prototype._addChange = function(bindingRecord, change, changes) { + if (bindingRecord.callOnChanges()) { + return _super.prototype.addChange.call(this, changes, change.previousValue, change.currentValue); + } else { + return changes; + } + }; + DynamicChangeDetector.prototype._getDirectiveFor = function(directiveIndex) { + return this.directives.getDirectiveFor(directiveIndex); + }; + DynamicChangeDetector.prototype._getDetectorFor = function(directiveIndex) { + return this.directives.getDetectorFor(directiveIndex); + }; + DynamicChangeDetector.prototype._check = function(proto, throwOnChange, values, locals) { + if (proto.isPipeRecord()) { + return this._pipeCheck(proto, throwOnChange, values); + } else { + return this._referenceCheck(proto, throwOnChange, values, locals); + } + }; + DynamicChangeDetector.prototype._referenceCheck = function(proto, throwOnChange, values, locals) { + if (this._pureFuncAndArgsDidNotChange(proto)) { + this._setChanged(proto, false); + return null; + } + var currValue = this._calculateCurrValue(proto, values, locals); + if (this.strategy === constants_1.ChangeDetectionStrategy.OnPushObserve) { + _super.prototype.observeValue.call(this, currValue, proto.selfIndex); + } + if (proto.shouldBeChecked()) { + var prevValue = this._readSelf(proto, values); + if (change_detection_util_1.ChangeDetectionUtil.looseNotIdentical(prevValue, currValue)) { + if (proto.lastInBinding) { + var change = change_detection_util_1.ChangeDetectionUtil.simpleChange(prevValue, currValue); + if (throwOnChange) + this.throwOnChangeError(prevValue, currValue); + this._writeSelf(proto, currValue, values); + this._setChanged(proto, true); + return change; + } else { + this._writeSelf(proto, currValue, values); + this._setChanged(proto, true); + return null; + } + } else { + this._setChanged(proto, false); + return null; + } + } else { + this._writeSelf(proto, currValue, values); + this._setChanged(proto, true); + return null; + } + }; + DynamicChangeDetector.prototype._calculateCurrValue = function(proto, values, locals) { + switch (proto.mode) { + case proto_record_1.RecordType.Self: + return this._readContext(proto, values); + case proto_record_1.RecordType.Const: + return proto.funcOrValue; + case proto_record_1.RecordType.PropertyRead: + var context = this._readContext(proto, values); + return proto.funcOrValue(context); + case proto_record_1.RecordType.SafeProperty: + var context = this._readContext(proto, values); + return lang_1.isBlank(context) ? null : proto.funcOrValue(context); + case proto_record_1.RecordType.PropertyWrite: + var context = this._readContext(proto, values); + var value = this._readArgs(proto, values)[0]; + proto.funcOrValue(context, value); + return value; + case proto_record_1.RecordType.KeyedWrite: + var context = this._readContext(proto, values); + var key = this._readArgs(proto, values)[0]; + var value = this._readArgs(proto, values)[1]; + context[key] = value; + return value; + case proto_record_1.RecordType.Local: + return locals.get(proto.name); + case proto_record_1.RecordType.InvokeMethod: + var context = this._readContext(proto, values); + var args = this._readArgs(proto, values); + return proto.funcOrValue(context, args); + case proto_record_1.RecordType.SafeMethodInvoke: + var context = this._readContext(proto, values); + if (lang_1.isBlank(context)) { + return null; + } + var args = this._readArgs(proto, values); + return proto.funcOrValue(context, args); + case proto_record_1.RecordType.KeyedRead: + var arg = this._readArgs(proto, values)[0]; + return this._readContext(proto, values)[arg]; + case proto_record_1.RecordType.Chain: + var args = this._readArgs(proto, values); + return args[args.length - 1]; + case proto_record_1.RecordType.InvokeClosure: + return lang_1.FunctionWrapper.apply(this._readContext(proto, values), this._readArgs(proto, values)); + case proto_record_1.RecordType.Interpolate: + case proto_record_1.RecordType.PrimitiveOp: + case proto_record_1.RecordType.CollectionLiteral: + return lang_1.FunctionWrapper.apply(proto.funcOrValue, this._readArgs(proto, values)); + default: + throw new exceptions_1.BaseException("Unknown operation " + proto.mode); + } + }; + DynamicChangeDetector.prototype._pipeCheck = function(proto, throwOnChange, values) { + var context = this._readContext(proto, values); + var selectedPipe = this._pipeFor(proto, context); + if (!selectedPipe.pure || this._argsOrContextChanged(proto)) { + var args = this._readArgs(proto, values); + var currValue = selectedPipe.pipe.transform(context, args); + if (proto.shouldBeChecked()) { + var prevValue = this._readSelf(proto, values); + if (change_detection_util_1.ChangeDetectionUtil.looseNotIdentical(prevValue, currValue)) { + currValue = change_detection_util_1.ChangeDetectionUtil.unwrapValue(currValue); + if (proto.lastInBinding) { + var change = change_detection_util_1.ChangeDetectionUtil.simpleChange(prevValue, currValue); + if (throwOnChange) + this.throwOnChangeError(prevValue, currValue); + this._writeSelf(proto, currValue, values); + this._setChanged(proto, true); + return change; + } else { + this._writeSelf(proto, currValue, values); + this._setChanged(proto, true); + return null; + } + } else { + this._setChanged(proto, false); + return null; + } + } else { + this._writeSelf(proto, currValue, values); + this._setChanged(proto, true); + return null; + } + } + }; + DynamicChangeDetector.prototype._pipeFor = function(proto, context) { + var storedPipe = this._readPipe(proto); + if (lang_1.isPresent(storedPipe)) + return storedPipe; + var pipe = this.pipes.get(proto.name); + this._writePipe(proto, pipe); + return pipe; + }; + DynamicChangeDetector.prototype._readContext = function(proto, values) { + if (proto.contextIndex == -1) { + return this._getDirectiveFor(proto.directiveIndex); + } + return values[proto.contextIndex]; + }; + DynamicChangeDetector.prototype._readSelf = function(proto, values) { + return values[proto.selfIndex]; + }; + DynamicChangeDetector.prototype._writeSelf = function(proto, value, values) { + values[proto.selfIndex] = value; + }; + DynamicChangeDetector.prototype._readPipe = function(proto) { + return this.localPipes[proto.selfIndex]; + }; + DynamicChangeDetector.prototype._writePipe = function(proto, value) { + this.localPipes[proto.selfIndex] = value; + }; + DynamicChangeDetector.prototype._setChanged = function(proto, value) { + if (proto.argumentToPureFunction) + this.changes[proto.selfIndex] = value; + }; + DynamicChangeDetector.prototype._pureFuncAndArgsDidNotChange = function(proto) { + return proto.isPureFunction() && !this._argsChanged(proto); + }; + DynamicChangeDetector.prototype._argsChanged = function(proto) { + var args = proto.args; + for (var i = 0; i < args.length; ++i) { + if (this.changes[args[i]]) { + return true; + } + } + return false; + }; + DynamicChangeDetector.prototype._argsOrContextChanged = function(proto) { + return this._argsChanged(proto) || this.changes[proto.contextIndex]; + }; + DynamicChangeDetector.prototype._readArgs = function(proto, values) { + var res = collection_1.ListWrapper.createFixedSize(proto.args.length); + var args = proto.args; + for (var i = 0; i < args.length; ++i) { + res[i] = values[args[i]]; + } + return res; + }; + return DynamicChangeDetector; + })(abstract_change_detector_1.AbstractChangeDetector); + exports.DynamicChangeDetector = DynamicChangeDetector; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/change_detection_jit_generator", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/core/change_detection/abstract_change_detector", "angular2/src/core/change_detection/change_detection_util", "angular2/src/core/change_detection/proto_record", "angular2/src/core/change_detection/codegen_name_util", "angular2/src/core/change_detection/codegen_logic_util", "angular2/src/core/change_detection/codegen_facade", "angular2/src/core/change_detection/constants", "angular2/src/core/change_detection/proto_change_detector"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var abstract_change_detector_1 = require("angular2/src/core/change_detection/abstract_change_detector"); + var change_detection_util_1 = require("angular2/src/core/change_detection/change_detection_util"); + var proto_record_1 = require("angular2/src/core/change_detection/proto_record"); + var codegen_name_util_1 = require("angular2/src/core/change_detection/codegen_name_util"); + var codegen_logic_util_1 = require("angular2/src/core/change_detection/codegen_logic_util"); + var codegen_facade_1 = require("angular2/src/core/change_detection/codegen_facade"); + var constants_1 = require("angular2/src/core/change_detection/constants"); + var proto_change_detector_1 = require("angular2/src/core/change_detection/proto_change_detector"); + var IS_CHANGED_LOCAL = "isChanged"; + var CHANGES_LOCAL = "changes"; + var ChangeDetectorJITGenerator = (function() { + function ChangeDetectorJITGenerator(definition, changeDetectionUtilVarName, abstractChangeDetectorVarName, changeDetectorStateVarName) { + this.changeDetectionUtilVarName = changeDetectionUtilVarName; + this.abstractChangeDetectorVarName = abstractChangeDetectorVarName; + this.changeDetectorStateVarName = changeDetectorStateVarName; + var propertyBindingRecords = proto_change_detector_1.createPropertyRecords(definition); + var eventBindingRecords = proto_change_detector_1.createEventRecords(definition); + var propertyBindingTargets = definition.bindingRecords.map(function(b) { + return b.target; + }); + this.id = definition.id; + this.changeDetectionStrategy = definition.strategy; + this.genConfig = definition.genConfig; + this.records = propertyBindingRecords; + this.propertyBindingTargets = propertyBindingTargets; + this.eventBindings = eventBindingRecords; + this.directiveRecords = definition.directiveRecords; + this._names = new codegen_name_util_1.CodegenNameUtil(this.records, this.eventBindings, this.directiveRecords, this.changeDetectionUtilVarName); + this._logic = new codegen_logic_util_1.CodegenLogicUtil(this._names, this.changeDetectionUtilVarName, this.changeDetectorStateVarName, this.changeDetectionStrategy); + this.typeName = codegen_name_util_1.sanitizeName("ChangeDetector_" + this.id); + } + ChangeDetectorJITGenerator.prototype.generate = function() { + var factorySource = "\n " + this.generateSource() + "\n return function(dispatcher) {\n return new " + this.typeName + "(dispatcher);\n }\n "; + return new Function(this.abstractChangeDetectorVarName, this.changeDetectionUtilVarName, this.changeDetectorStateVarName, factorySource)(abstract_change_detector_1.AbstractChangeDetector, change_detection_util_1.ChangeDetectionUtil, constants_1.ChangeDetectorState); + }; + ChangeDetectorJITGenerator.prototype.generateSource = function() { + return "\n var " + this.typeName + " = function " + this.typeName + "(dispatcher) {\n " + this.abstractChangeDetectorVarName + ".call(\n this, " + JSON.stringify(this.id) + ", dispatcher, " + this.records.length + ",\n " + this.typeName + ".gen_propertyBindingTargets, " + this.typeName + ".gen_directiveIndices,\n " + codegen_facade_1.codify(this.changeDetectionStrategy) + ");\n this.dehydrateDirectives(false);\n }\n\n " + this.typeName + ".prototype = Object.create(" + this.abstractChangeDetectorVarName + ".prototype);\n\n " + this.typeName + ".prototype.detectChangesInRecordsInternal = function(throwOnChange) {\n " + this._names.genInitLocals() + "\n var " + IS_CHANGED_LOCAL + " = false;\n var " + CHANGES_LOCAL + " = null;\n\n " + this._genAllRecords(this.records) + "\n }\n\n " + this._maybeGenHandleEventInternal() + "\n\n " + this._maybeGenAfterContentLifecycleCallbacks() + "\n\n " + this._maybeGenAfterViewLifecycleCallbacks() + "\n\n " + this._maybeGenHydrateDirectives() + "\n\n " + this._maybeGenDehydrateDirectives() + "\n\n " + this._genPropertyBindingTargets() + "\n\n " + this._genDirectiveIndices() + "\n "; + }; + ChangeDetectorJITGenerator.prototype._genPropertyBindingTargets = function() { + var targets = this._logic.genPropertyBindingTargets(this.propertyBindingTargets, this.genConfig.genDebugInfo); + return this.typeName + ".gen_propertyBindingTargets = " + targets + ";"; + }; + ChangeDetectorJITGenerator.prototype._genDirectiveIndices = function() { + var indices = this._logic.genDirectiveIndices(this.directiveRecords); + return this.typeName + ".gen_directiveIndices = " + indices + ";"; + }; + ChangeDetectorJITGenerator.prototype._maybeGenHandleEventInternal = function() { + var _this = this; + if (this.eventBindings.length > 0) { + var handlers = this.eventBindings.map(function(eb) { + return _this._genEventBinding(eb); + }).join("\n"); + return "\n " + this.typeName + ".prototype.handleEventInternal = function(eventName, elIndex, locals) {\n var " + this._names.getPreventDefaultAccesor() + " = false;\n " + this._names.genInitEventLocals() + "\n " + handlers + "\n return " + this._names.getPreventDefaultAccesor() + ";\n }\n "; + } else { + return ''; + } + }; + ChangeDetectorJITGenerator.prototype._genEventBinding = function(eb) { + var _this = this; + var codes = []; + this._endOfBlockIdxs = []; + collection_1.ListWrapper.forEachWithIndex(eb.records, function(r, i) { + var code; + if (r.isConditionalSkipRecord()) { + code = _this._genConditionalSkip(r, _this._names.getEventLocalName(eb, i)); + } else if (r.isUnconditionalSkipRecord()) { + code = _this._genUnconditionalSkip(r); + } else { + code = _this._genEventBindingEval(eb, r); + } + code += _this._genEndOfSkipBlock(i); + codes.push(code); + }); + return "\n if (eventName === \"" + eb.eventName + "\" && elIndex === " + eb.elIndex + ") {\n " + codes.join("\n") + "\n }"; + }; + ChangeDetectorJITGenerator.prototype._genEventBindingEval = function(eb, r) { + if (r.lastInBinding) { + var evalRecord = this._logic.genEventBindingEvalValue(eb, r); + var markPath = this._genMarkPathToRootAsCheckOnce(r); + var prevDefault = this._genUpdatePreventDefault(eb, r); + return evalRecord + "\n" + markPath + "\n" + prevDefault; + } else { + return this._logic.genEventBindingEvalValue(eb, r); + } + }; + ChangeDetectorJITGenerator.prototype._genMarkPathToRootAsCheckOnce = function(r) { + var br = r.bindingRecord; + if (br.isDefaultChangeDetection()) { + return ""; + } else { + return this._names.getDetectorName(br.directiveRecord.directiveIndex) + ".markPathToRootAsCheckOnce();"; + } + }; + ChangeDetectorJITGenerator.prototype._genUpdatePreventDefault = function(eb, r) { + var local = this._names.getEventLocalName(eb, r.selfIndex); + return "if (" + local + " === false) { " + this._names.getPreventDefaultAccesor() + " = true};"; + }; + ChangeDetectorJITGenerator.prototype._maybeGenDehydrateDirectives = function() { + var destroyPipesCode = this._names.genPipeOnDestroy(); + if (destroyPipesCode) { + destroyPipesCode = "if (destroyPipes) { " + destroyPipesCode + " }"; + } + var dehydrateFieldsCode = this._names.genDehydrateFields(); + if (!destroyPipesCode && !dehydrateFieldsCode) + return ''; + return this.typeName + ".prototype.dehydrateDirectives = function(destroyPipes) {\n " + destroyPipesCode + "\n " + dehydrateFieldsCode + "\n }"; + }; + ChangeDetectorJITGenerator.prototype._maybeGenHydrateDirectives = function() { + var hydrateDirectivesCode = this._logic.genHydrateDirectives(this.directiveRecords); + var hydrateDetectorsCode = this._logic.genHydrateDetectors(this.directiveRecords); + if (!hydrateDirectivesCode && !hydrateDetectorsCode) + return ''; + return this.typeName + ".prototype.hydrateDirectives = function(directives) {\n " + hydrateDirectivesCode + "\n " + hydrateDetectorsCode + "\n }"; + }; + ChangeDetectorJITGenerator.prototype._maybeGenAfterContentLifecycleCallbacks = function() { + var notifications = this._logic.genContentLifecycleCallbacks(this.directiveRecords); + if (notifications.length > 0) { + var directiveNotifications = notifications.join("\n"); + return "\n " + this.typeName + ".prototype.afterContentLifecycleCallbacksInternal = function() {\n " + directiveNotifications + "\n }\n "; + } else { + return ''; + } + }; + ChangeDetectorJITGenerator.prototype._maybeGenAfterViewLifecycleCallbacks = function() { + var notifications = this._logic.genViewLifecycleCallbacks(this.directiveRecords); + if (notifications.length > 0) { + var directiveNotifications = notifications.join("\n"); + return "\n " + this.typeName + ".prototype.afterViewLifecycleCallbacksInternal = function() {\n " + directiveNotifications + "\n }\n "; + } else { + return ''; + } + }; + ChangeDetectorJITGenerator.prototype._genAllRecords = function(rs) { + var codes = []; + this._endOfBlockIdxs = []; + for (var i = 0; i < rs.length; i++) { + var code = void 0; + var r = rs[i]; + if (r.isLifeCycleRecord()) { + code = this._genDirectiveLifecycle(r); + } else if (r.isPipeRecord()) { + code = this._genPipeCheck(r); + } else if (r.isConditionalSkipRecord()) { + code = this._genConditionalSkip(r, this._names.getLocalName(r.contextIndex)); + } else if (r.isUnconditionalSkipRecord()) { + code = this._genUnconditionalSkip(r); + } else { + code = this._genReferenceCheck(r); + } + code = "\n " + this._maybeFirstInBinding(r) + "\n " + code + "\n " + this._maybeGenLastInDirective(r) + "\n " + this._genEndOfSkipBlock(i) + "\n "; + codes.push(code); + } + return codes.join("\n"); + }; + ChangeDetectorJITGenerator.prototype._genConditionalSkip = function(r, condition) { + var maybeNegate = r.mode === proto_record_1.RecordType.SkipRecordsIf ? '!' : ''; + this._endOfBlockIdxs.push(r.fixedArgs[0] - 1); + return "if (" + maybeNegate + condition + ") {"; + }; + ChangeDetectorJITGenerator.prototype._genUnconditionalSkip = function(r) { + this._endOfBlockIdxs.pop(); + this._endOfBlockIdxs.push(r.fixedArgs[0] - 1); + return "} else {"; + }; + ChangeDetectorJITGenerator.prototype._genEndOfSkipBlock = function(protoIndex) { + if (!collection_1.ListWrapper.isEmpty(this._endOfBlockIdxs)) { + var endOfBlock = collection_1.ListWrapper.last(this._endOfBlockIdxs); + if (protoIndex === endOfBlock) { + this._endOfBlockIdxs.pop(); + return '}'; + } + } + return ''; + }; + ChangeDetectorJITGenerator.prototype._genDirectiveLifecycle = function(r) { + if (r.name === "DoCheck") { + return this._genOnCheck(r); + } else if (r.name === "OnInit") { + return this._genOnInit(r); + } else if (r.name === "OnChanges") { + return this._genOnChange(r); + } else { + throw new exceptions_1.BaseException("Unknown lifecycle event '" + r.name + "'"); + } + }; + ChangeDetectorJITGenerator.prototype._genPipeCheck = function(r) { + var _this = this; + var context = this._names.getLocalName(r.contextIndex); + var argString = r.args.map(function(arg) { + return _this._names.getLocalName(arg); + }).join(", "); + var oldValue = this._names.getFieldName(r.selfIndex); + var newValue = this._names.getLocalName(r.selfIndex); + var pipe = this._names.getPipeName(r.selfIndex); + var pipeName = r.name; + var init = "\n if (" + pipe + " === " + this.changeDetectionUtilVarName + ".uninitialized) {\n " + pipe + " = " + this._names.getPipesAccessorName() + ".get('" + pipeName + "');\n }\n "; + var read = newValue + " = " + pipe + ".pipe.transform(" + context + ", [" + argString + "]);"; + var contexOrArgCheck = r.args.map(function(a) { + return _this._names.getChangeName(a); + }); + contexOrArgCheck.push(this._names.getChangeName(r.contextIndex)); + var condition = "!" + pipe + ".pure || (" + contexOrArgCheck.join(" || ") + ")"; + var check = "\n if (" + this.changeDetectionUtilVarName + ".looseNotIdentical(" + oldValue + ", " + newValue + ")) {\n " + newValue + " = " + this.changeDetectionUtilVarName + ".unwrapValue(" + newValue + ")\n " + this._genChangeMarker(r) + "\n " + this._genUpdateDirectiveOrElement(r) + "\n " + this._genAddToChanges(r) + "\n " + oldValue + " = " + newValue + ";\n }\n "; + var genCode = r.shouldBeChecked() ? "" + read + check : read; + if (r.isUsedByOtherRecord()) { + return init + " if (" + condition + ") { " + genCode + " } else { " + newValue + " = " + oldValue + "; }"; + } else { + return init + " if (" + condition + ") { " + genCode + " }"; + } + }; + ChangeDetectorJITGenerator.prototype._genReferenceCheck = function(r) { + var _this = this; + var oldValue = this._names.getFieldName(r.selfIndex); + var newValue = this._names.getLocalName(r.selfIndex); + var read = "\n " + this._logic.genPropertyBindingEvalValue(r) + "\n "; + var check = "\n if (" + this.changeDetectionUtilVarName + ".looseNotIdentical(" + oldValue + ", " + newValue + ")) {\n " + this._genChangeMarker(r) + "\n " + this._genUpdateDirectiveOrElement(r) + "\n " + this._genAddToChanges(r) + "\n " + oldValue + " = " + newValue + ";\n }\n "; + var genCode = r.shouldBeChecked() ? "" + read + check : read; + if (r.isPureFunction()) { + var condition = r.args.map(function(a) { + return _this._names.getChangeName(a); + }).join(" || "); + if (r.isUsedByOtherRecord()) { + return "if (" + condition + ") { " + genCode + " } else { " + newValue + " = " + oldValue + "; }"; + } else { + return "if (" + condition + ") { " + genCode + " }"; + } + } else { + return genCode; + } + }; + ChangeDetectorJITGenerator.prototype._genChangeMarker = function(r) { + return r.argumentToPureFunction ? this._names.getChangeName(r.selfIndex) + " = true" : ""; + }; + ChangeDetectorJITGenerator.prototype._genUpdateDirectiveOrElement = function(r) { + if (!r.lastInBinding) + return ""; + var newValue = this._names.getLocalName(r.selfIndex); + var oldValue = this._names.getFieldName(r.selfIndex); + var notifyDebug = this.genConfig.logBindingUpdate ? "this.logBindingUpdate(" + newValue + ");" : ""; + var br = r.bindingRecord; + if (br.target.isDirective()) { + var directiveProperty = this._names.getDirectiveName(br.directiveRecord.directiveIndex) + "." + br.target.name; + return "\n " + this._genThrowOnChangeCheck(oldValue, newValue) + "\n " + directiveProperty + " = " + newValue + ";\n " + notifyDebug + "\n " + IS_CHANGED_LOCAL + " = true;\n "; + } else { + return "\n " + this._genThrowOnChangeCheck(oldValue, newValue) + "\n this.notifyDispatcher(" + newValue + ");\n " + notifyDebug + "\n "; + } + }; + ChangeDetectorJITGenerator.prototype._genThrowOnChangeCheck = function(oldValue, newValue) { + if (lang_1.assertionsEnabled()) { + return "\n if(throwOnChange) {\n this.throwOnChangeError(" + oldValue + ", " + newValue + ");\n }\n "; + } else { + return ''; + } + }; + ChangeDetectorJITGenerator.prototype._genAddToChanges = function(r) { + var newValue = this._names.getLocalName(r.selfIndex); + var oldValue = this._names.getFieldName(r.selfIndex); + if (!r.bindingRecord.callOnChanges()) + return ""; + return CHANGES_LOCAL + " = this.addChange(" + CHANGES_LOCAL + ", " + oldValue + ", " + newValue + ");"; + }; + ChangeDetectorJITGenerator.prototype._maybeFirstInBinding = function(r) { + var prev = change_detection_util_1.ChangeDetectionUtil.protoByIndex(this.records, r.selfIndex - 1); + var firstInBinding = lang_1.isBlank(prev) || prev.bindingRecord !== r.bindingRecord; + return firstInBinding && !r.bindingRecord.isDirectiveLifecycle() ? this._names.getPropertyBindingIndex() + " = " + r.propertyBindingIndex + ";" : ''; + }; + ChangeDetectorJITGenerator.prototype._maybeGenLastInDirective = function(r) { + if (!r.lastInDirective) + return ""; + return "\n " + CHANGES_LOCAL + " = null;\n " + this._genNotifyOnPushDetectors(r) + "\n " + IS_CHANGED_LOCAL + " = false;\n "; + }; + ChangeDetectorJITGenerator.prototype._genOnCheck = function(r) { + var br = r.bindingRecord; + return "if (!throwOnChange) " + this._names.getDirectiveName(br.directiveRecord.directiveIndex) + ".ngDoCheck();"; + }; + ChangeDetectorJITGenerator.prototype._genOnInit = function(r) { + var br = r.bindingRecord; + return "if (!throwOnChange && " + this._names.getStateName() + " === " + this.changeDetectorStateVarName + ".NeverChecked) " + this._names.getDirectiveName(br.directiveRecord.directiveIndex) + ".ngOnInit();"; + }; + ChangeDetectorJITGenerator.prototype._genOnChange = function(r) { + var br = r.bindingRecord; + return "if (!throwOnChange && " + CHANGES_LOCAL + ") " + this._names.getDirectiveName(br.directiveRecord.directiveIndex) + ".ngOnChanges(" + CHANGES_LOCAL + ");"; + }; + ChangeDetectorJITGenerator.prototype._genNotifyOnPushDetectors = function(r) { + var br = r.bindingRecord; + if (!r.lastInDirective || br.isDefaultChangeDetection()) + return ""; + var retVal = "\n if(" + IS_CHANGED_LOCAL + ") {\n " + this._names.getDetectorName(br.directiveRecord.directiveIndex) + ".markAsCheckOnce();\n }\n "; + return retVal; + }; + return ChangeDetectorJITGenerator; + })(); + exports.ChangeDetectorJITGenerator = ChangeDetectorJITGenerator; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/view_manager", ["angular2/src/core/di", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/core/linker/view", "angular2/src/core/linker/view_ref", "angular2/src/core/render/api", "angular2/src/core/linker/view_manager_utils", "angular2/src/core/linker/view_pool", "angular2/src/core/linker/view_listener", "angular2/src/core/profile/profile", "angular2/src/core/linker/proto_view_factory"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var di_1 = require("angular2/src/core/di"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var viewModule = require("angular2/src/core/linker/view"); + var view_ref_1 = require("angular2/src/core/linker/view_ref"); + var api_1 = require("angular2/src/core/render/api"); + var view_manager_utils_1 = require("angular2/src/core/linker/view_manager_utils"); + var view_pool_1 = require("angular2/src/core/linker/view_pool"); + var view_listener_1 = require("angular2/src/core/linker/view_listener"); + var profile_1 = require("angular2/src/core/profile/profile"); + var proto_view_factory_1 = require("angular2/src/core/linker/proto_view_factory"); + var AppViewManager = (function() { + function AppViewManager() {} + AppViewManager.prototype.getHostElement = function(hostViewRef) { + var hostView = view_ref_1.internalView(hostViewRef); + if (hostView.proto.type !== viewModule.ViewType.HOST) { + throw new exceptions_1.BaseException('This operation is only allowed on host views'); + } + return hostView.elementRefs[hostView.elementOffset]; + }; + return AppViewManager; + })(); + exports.AppViewManager = AppViewManager; + var AppViewManager_ = (function(_super) { + __extends(AppViewManager_, _super); + function AppViewManager_(_viewPool, _viewListener, _utils, _renderer, _protoViewFactory) { + _super.call(this); + this._viewPool = _viewPool; + this._viewListener = _viewListener; + this._utils = _utils; + this._renderer = _renderer; + this._createRootHostViewScope = profile_1.wtfCreateScope('AppViewManager#createRootHostView()'); + this._destroyRootHostViewScope = profile_1.wtfCreateScope('AppViewManager#destroyRootHostView()'); + this._createEmbeddedViewInContainerScope = profile_1.wtfCreateScope('AppViewManager#createEmbeddedViewInContainer()'); + this._createHostViewInContainerScope = profile_1.wtfCreateScope('AppViewManager#createHostViewInContainer()'); + this._destroyViewInContainerScope = profile_1.wtfCreateScope('AppViewMananger#destroyViewInContainer()'); + this._attachViewInContainerScope = profile_1.wtfCreateScope('AppViewMananger#attachViewInContainer()'); + this._detachViewInContainerScope = profile_1.wtfCreateScope('AppViewMananger#detachViewInContainer()'); + this._protoViewFactory = _protoViewFactory; + } + AppViewManager_.prototype.getViewContainer = function(location) { + var hostView = view_ref_1.internalView(location.parentView); + return hostView.elementInjectors[location.boundElementIndex].getViewContainerRef(); + }; + AppViewManager_.prototype.getNamedElementInComponentView = function(hostLocation, variableName) { + var hostView = view_ref_1.internalView(hostLocation.parentView); + var boundElementIndex = hostLocation.boundElementIndex; + var componentView = hostView.getNestedView(boundElementIndex); + if (lang_1.isBlank(componentView)) { + throw new exceptions_1.BaseException("There is no component directive at element " + boundElementIndex); + } + var binderIdx = componentView.proto.variableLocations.get(variableName); + if (lang_1.isBlank(binderIdx)) { + throw new exceptions_1.BaseException("Could not find variable " + variableName); + } + return componentView.elementRefs[componentView.elementOffset + binderIdx]; + }; + AppViewManager_.prototype.getComponent = function(hostLocation) { + var hostView = view_ref_1.internalView(hostLocation.parentView); + var boundElementIndex = hostLocation.boundElementIndex; + return this._utils.getComponentInstance(hostView, boundElementIndex); + }; + AppViewManager_.prototype.createRootHostView = function(hostProtoViewRef, overrideSelector, injector) { + var s = this._createRootHostViewScope(); + var hostProtoView = view_ref_1.internalProtoView(hostProtoViewRef); + this._protoViewFactory.initializeProtoViewIfNeeded(hostProtoView); + var hostElementSelector = overrideSelector; + if (lang_1.isBlank(hostElementSelector)) { + hostElementSelector = hostProtoView.elementBinders[0].componentDirective.metadata.selector; + } + var renderViewWithFragments = this._renderer.createRootHostView(hostProtoView.render, hostProtoView.mergeInfo.embeddedViewCount + 1, hostElementSelector); + var hostView = this._createMainView(hostProtoView, renderViewWithFragments); + this._renderer.hydrateView(hostView.render); + this._utils.hydrateRootHostView(hostView, injector); + return profile_1.wtfLeave(s, hostView.ref); + }; + AppViewManager_.prototype.destroyRootHostView = function(hostViewRef) { + var s = this._destroyRootHostViewScope(); + var hostView = view_ref_1.internalView(hostViewRef); + this._renderer.detachFragment(hostView.renderFragment); + this._renderer.dehydrateView(hostView.render); + this._viewDehydrateRecurse(hostView); + this._viewListener.onViewDestroyed(hostView); + this._renderer.destroyView(hostView.render); + profile_1.wtfLeave(s); + }; + AppViewManager_.prototype.createEmbeddedViewInContainer = function(viewContainerLocation, index, templateRef) { + var s = this._createEmbeddedViewInContainerScope(); + var protoView = view_ref_1.internalProtoView(templateRef.protoViewRef); + if (protoView.type !== viewModule.ViewType.EMBEDDED) { + throw new exceptions_1.BaseException('This method can only be called with embedded ProtoViews!'); + } + this._protoViewFactory.initializeProtoViewIfNeeded(protoView); + return profile_1.wtfLeave(s, this._createViewInContainer(viewContainerLocation, index, protoView, templateRef.elementRef, null)); + }; + AppViewManager_.prototype.createHostViewInContainer = function(viewContainerLocation, index, protoViewRef, imperativelyCreatedInjector) { + var s = this._createHostViewInContainerScope(); + var protoView = view_ref_1.internalProtoView(protoViewRef); + if (protoView.type !== viewModule.ViewType.HOST) { + throw new exceptions_1.BaseException('This method can only be called with host ProtoViews!'); + } + this._protoViewFactory.initializeProtoViewIfNeeded(protoView); + return profile_1.wtfLeave(s, this._createViewInContainer(viewContainerLocation, index, protoView, viewContainerLocation, imperativelyCreatedInjector)); + }; + AppViewManager_.prototype._createViewInContainer = function(viewContainerLocation, index, protoView, context, imperativelyCreatedInjector) { + var parentView = view_ref_1.internalView(viewContainerLocation.parentView); + var boundElementIndex = viewContainerLocation.boundElementIndex; + var contextView = view_ref_1.internalView(context.parentView); + var contextBoundElementIndex = context.boundElementIndex; + var embeddedFragmentView = contextView.getNestedView(contextBoundElementIndex); + var view; + if (protoView.type === viewModule.ViewType.EMBEDDED && lang_1.isPresent(embeddedFragmentView) && !embeddedFragmentView.hydrated()) { + view = embeddedFragmentView; + this._attachRenderView(parentView, boundElementIndex, index, view); + } else { + view = this._createPooledView(protoView); + this._attachRenderView(parentView, boundElementIndex, index, view); + this._renderer.hydrateView(view.render); + } + this._utils.attachViewInContainer(parentView, boundElementIndex, contextView, contextBoundElementIndex, index, view); + try { + this._utils.hydrateViewInContainer(parentView, boundElementIndex, contextView, contextBoundElementIndex, index, imperativelyCreatedInjector); + } catch (e) { + this._utils.detachViewInContainer(parentView, boundElementIndex, index); + throw e; + } + return view.ref; + }; + AppViewManager_.prototype._attachRenderView = function(parentView, boundElementIndex, index, view) { + var elementRef = parentView.elementRefs[boundElementIndex]; + if (index === 0) { + this._renderer.attachFragmentAfterElement(elementRef, view.renderFragment); + } else { + var prevView = parentView.viewContainers[boundElementIndex].views[index - 1]; + this._renderer.attachFragmentAfterFragment(prevView.renderFragment, view.renderFragment); + } + }; + AppViewManager_.prototype.destroyViewInContainer = function(viewContainerLocation, index) { + var s = this._destroyViewInContainerScope(); + var parentView = view_ref_1.internalView(viewContainerLocation.parentView); + var boundElementIndex = viewContainerLocation.boundElementIndex; + this._destroyViewInContainer(parentView, boundElementIndex, index); + profile_1.wtfLeave(s); + }; + AppViewManager_.prototype.attachViewInContainer = function(viewContainerLocation, index, viewRef) { + var s = this._attachViewInContainerScope(); + var view = view_ref_1.internalView(viewRef); + var parentView = view_ref_1.internalView(viewContainerLocation.parentView); + var boundElementIndex = viewContainerLocation.boundElementIndex; + this._utils.attachViewInContainer(parentView, boundElementIndex, null, null, index, view); + this._attachRenderView(parentView, boundElementIndex, index, view); + return profile_1.wtfLeave(s, viewRef); + }; + AppViewManager_.prototype.detachViewInContainer = function(viewContainerLocation, index) { + var s = this._detachViewInContainerScope(); + var parentView = view_ref_1.internalView(viewContainerLocation.parentView); + var boundElementIndex = viewContainerLocation.boundElementIndex; + var viewContainer = parentView.viewContainers[boundElementIndex]; + var view = viewContainer.views[index]; + this._utils.detachViewInContainer(parentView, boundElementIndex, index); + this._renderer.detachFragment(view.renderFragment); + return profile_1.wtfLeave(s, view.ref); + }; + AppViewManager_.prototype._createMainView = function(protoView, renderViewWithFragments) { + var mergedParentView = this._utils.createView(protoView, renderViewWithFragments, this, this._renderer); + this._renderer.setEventDispatcher(mergedParentView.render, mergedParentView); + this._viewListener.onViewCreated(mergedParentView); + return mergedParentView; + }; + AppViewManager_.prototype._createPooledView = function(protoView) { + var view = this._viewPool.getView(protoView); + if (lang_1.isBlank(view)) { + view = this._createMainView(protoView, this._renderer.createView(protoView.render, protoView.mergeInfo.embeddedViewCount + 1)); + } + return view; + }; + AppViewManager_.prototype._destroyPooledView = function(view) { + var wasReturned = this._viewPool.returnView(view); + if (!wasReturned) { + this._viewListener.onViewDestroyed(view); + this._renderer.destroyView(view.render); + } + }; + AppViewManager_.prototype._destroyViewInContainer = function(parentView, boundElementIndex, index) { + var viewContainer = parentView.viewContainers[boundElementIndex]; + var view = viewContainer.views[index]; + this._viewDehydrateRecurse(view); + this._utils.detachViewInContainer(parentView, boundElementIndex, index); + if (view.viewOffset > 0) { + this._renderer.detachFragment(view.renderFragment); + } else { + this._renderer.dehydrateView(view.render); + this._renderer.detachFragment(view.renderFragment); + this._destroyPooledView(view); + } + }; + AppViewManager_.prototype._viewDehydrateRecurse = function(view) { + if (view.hydrated()) { + this._utils.dehydrateView(view); + } + var viewContainers = view.viewContainers; + var startViewOffset = view.viewOffset; + var endViewOffset = view.viewOffset + view.proto.mergeInfo.viewCount - 1; + var elementOffset = view.elementOffset; + for (var viewIdx = startViewOffset; viewIdx <= endViewOffset; viewIdx++) { + var currView = view.views[viewIdx]; + for (var binderIdx = 0; binderIdx < currView.proto.elementBinders.length; binderIdx++, elementOffset++) { + var vc = viewContainers[elementOffset]; + if (lang_1.isPresent(vc)) { + for (var j = vc.views.length - 1; j >= 0; j--) { + this._destroyViewInContainer(currView, elementOffset, j); + } + } + } + } + }; + AppViewManager_ = __decorate([di_1.Injectable(), __param(4, di_1.Inject(di_1.forwardRef(function() { + return proto_view_factory_1.ProtoViewFactory; + }))), __metadata('design:paramtypes', [view_pool_1.AppViewPool, view_listener_1.AppViewListener, view_manager_utils_1.AppViewManagerUtils, api_1.Renderer, Object])], AppViewManager_); + return AppViewManager_; + })(AppViewManager); + exports.AppViewManager_ = AppViewManager_; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/di/injector", ["angular2/src/facade/collection", "angular2/src/core/di/provider", "angular2/src/core/di/exceptions", "angular2/src/facade/lang", "angular2/src/core/di/key", "angular2/src/core/di/metadata"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var collection_1 = require("angular2/src/facade/collection"); + var provider_1 = require("angular2/src/core/di/provider"); + var exceptions_1 = require("angular2/src/core/di/exceptions"); + var lang_1 = require("angular2/src/facade/lang"); + var key_1 = require("angular2/src/core/di/key"); + var metadata_1 = require("angular2/src/core/di/metadata"); + var _MAX_CONSTRUCTION_COUNTER = 10; + exports.UNDEFINED = lang_1.CONST_EXPR(new Object()); + (function(Visibility) { + Visibility[Visibility["Public"] = 0] = "Public"; + Visibility[Visibility["Private"] = 1] = "Private"; + Visibility[Visibility["PublicAndPrivate"] = 2] = "PublicAndPrivate"; + })(exports.Visibility || (exports.Visibility = {})); + var Visibility = exports.Visibility; + function canSee(src, dst) { + return (src === dst) || (dst === Visibility.PublicAndPrivate || src === Visibility.PublicAndPrivate); + } + var ProtoInjectorInlineStrategy = (function() { + function ProtoInjectorInlineStrategy(protoEI, bwv) { + this.provider0 = null; + this.provider1 = null; + this.provider2 = null; + this.provider3 = null; + this.provider4 = null; + this.provider5 = null; + this.provider6 = null; + this.provider7 = null; + this.provider8 = null; + this.provider9 = null; + this.keyId0 = null; + this.keyId1 = null; + this.keyId2 = null; + this.keyId3 = null; + this.keyId4 = null; + this.keyId5 = null; + this.keyId6 = null; + this.keyId7 = null; + this.keyId8 = null; + this.keyId9 = null; + this.visibility0 = null; + this.visibility1 = null; + this.visibility2 = null; + this.visibility3 = null; + this.visibility4 = null; + this.visibility5 = null; + this.visibility6 = null; + this.visibility7 = null; + this.visibility8 = null; + this.visibility9 = null; + var length = bwv.length; + if (length > 0) { + this.provider0 = bwv[0].provider; + this.keyId0 = bwv[0].getKeyId(); + this.visibility0 = bwv[0].visibility; + } + if (length > 1) { + this.provider1 = bwv[1].provider; + this.keyId1 = bwv[1].getKeyId(); + this.visibility1 = bwv[1].visibility; + } + if (length > 2) { + this.provider2 = bwv[2].provider; + this.keyId2 = bwv[2].getKeyId(); + this.visibility2 = bwv[2].visibility; + } + if (length > 3) { + this.provider3 = bwv[3].provider; + this.keyId3 = bwv[3].getKeyId(); + this.visibility3 = bwv[3].visibility; + } + if (length > 4) { + this.provider4 = bwv[4].provider; + this.keyId4 = bwv[4].getKeyId(); + this.visibility4 = bwv[4].visibility; + } + if (length > 5) { + this.provider5 = bwv[5].provider; + this.keyId5 = bwv[5].getKeyId(); + this.visibility5 = bwv[5].visibility; + } + if (length > 6) { + this.provider6 = bwv[6].provider; + this.keyId6 = bwv[6].getKeyId(); + this.visibility6 = bwv[6].visibility; + } + if (length > 7) { + this.provider7 = bwv[7].provider; + this.keyId7 = bwv[7].getKeyId(); + this.visibility7 = bwv[7].visibility; + } + if (length > 8) { + this.provider8 = bwv[8].provider; + this.keyId8 = bwv[8].getKeyId(); + this.visibility8 = bwv[8].visibility; + } + if (length > 9) { + this.provider9 = bwv[9].provider; + this.keyId9 = bwv[9].getKeyId(); + this.visibility9 = bwv[9].visibility; + } + } + ProtoInjectorInlineStrategy.prototype.getProviderAtIndex = function(index) { + if (index == 0) + return this.provider0; + if (index == 1) + return this.provider1; + if (index == 2) + return this.provider2; + if (index == 3) + return this.provider3; + if (index == 4) + return this.provider4; + if (index == 5) + return this.provider5; + if (index == 6) + return this.provider6; + if (index == 7) + return this.provider7; + if (index == 8) + return this.provider8; + if (index == 9) + return this.provider9; + throw new exceptions_1.OutOfBoundsError(index); + }; + ProtoInjectorInlineStrategy.prototype.createInjectorStrategy = function(injector) { + return new InjectorInlineStrategy(injector, this); + }; + return ProtoInjectorInlineStrategy; + })(); + exports.ProtoInjectorInlineStrategy = ProtoInjectorInlineStrategy; + var ProtoInjectorDynamicStrategy = (function() { + function ProtoInjectorDynamicStrategy(protoInj, bwv) { + var len = bwv.length; + this.providers = collection_1.ListWrapper.createFixedSize(len); + this.keyIds = collection_1.ListWrapper.createFixedSize(len); + this.visibilities = collection_1.ListWrapper.createFixedSize(len); + for (var i = 0; i < len; i++) { + this.providers[i] = bwv[i].provider; + this.keyIds[i] = bwv[i].getKeyId(); + this.visibilities[i] = bwv[i].visibility; + } + } + ProtoInjectorDynamicStrategy.prototype.getProviderAtIndex = function(index) { + if (index < 0 || index >= this.providers.length) { + throw new exceptions_1.OutOfBoundsError(index); + } + return this.providers[index]; + }; + ProtoInjectorDynamicStrategy.prototype.createInjectorStrategy = function(ei) { + return new InjectorDynamicStrategy(this, ei); + }; + return ProtoInjectorDynamicStrategy; + })(); + exports.ProtoInjectorDynamicStrategy = ProtoInjectorDynamicStrategy; + var ProtoInjector = (function() { + function ProtoInjector(bwv) { + this.numberOfProviders = bwv.length; + this._strategy = bwv.length > _MAX_CONSTRUCTION_COUNTER ? new ProtoInjectorDynamicStrategy(this, bwv) : new ProtoInjectorInlineStrategy(this, bwv); + } + ProtoInjector.prototype.getProviderAtIndex = function(index) { + return this._strategy.getProviderAtIndex(index); + }; + return ProtoInjector; + })(); + exports.ProtoInjector = ProtoInjector; + var InjectorInlineStrategy = (function() { + function InjectorInlineStrategy(injector, protoStrategy) { + this.injector = injector; + this.protoStrategy = protoStrategy; + this.obj0 = exports.UNDEFINED; + this.obj1 = exports.UNDEFINED; + this.obj2 = exports.UNDEFINED; + this.obj3 = exports.UNDEFINED; + this.obj4 = exports.UNDEFINED; + this.obj5 = exports.UNDEFINED; + this.obj6 = exports.UNDEFINED; + this.obj7 = exports.UNDEFINED; + this.obj8 = exports.UNDEFINED; + this.obj9 = exports.UNDEFINED; + } + InjectorInlineStrategy.prototype.resetConstructionCounter = function() { + this.injector._constructionCounter = 0; + }; + InjectorInlineStrategy.prototype.instantiateProvider = function(provider, visibility) { + return this.injector._new(provider, visibility); + }; + InjectorInlineStrategy.prototype.attach = function(parent, isHost) { + var inj = this.injector; + inj._parent = parent; + inj._isHost = isHost; + }; + InjectorInlineStrategy.prototype.getObjByKeyId = function(keyId, visibility) { + var p = this.protoStrategy; + var inj = this.injector; + if (p.keyId0 === keyId && canSee(p.visibility0, visibility)) { + if (this.obj0 === exports.UNDEFINED) { + this.obj0 = inj._new(p.provider0, p.visibility0); + } + return this.obj0; + } + if (p.keyId1 === keyId && canSee(p.visibility1, visibility)) { + if (this.obj1 === exports.UNDEFINED) { + this.obj1 = inj._new(p.provider1, p.visibility1); + } + return this.obj1; + } + if (p.keyId2 === keyId && canSee(p.visibility2, visibility)) { + if (this.obj2 === exports.UNDEFINED) { + this.obj2 = inj._new(p.provider2, p.visibility2); + } + return this.obj2; + } + if (p.keyId3 === keyId && canSee(p.visibility3, visibility)) { + if (this.obj3 === exports.UNDEFINED) { + this.obj3 = inj._new(p.provider3, p.visibility3); + } + return this.obj3; + } + if (p.keyId4 === keyId && canSee(p.visibility4, visibility)) { + if (this.obj4 === exports.UNDEFINED) { + this.obj4 = inj._new(p.provider4, p.visibility4); + } + return this.obj4; + } + if (p.keyId5 === keyId && canSee(p.visibility5, visibility)) { + if (this.obj5 === exports.UNDEFINED) { + this.obj5 = inj._new(p.provider5, p.visibility5); + } + return this.obj5; + } + if (p.keyId6 === keyId && canSee(p.visibility6, visibility)) { + if (this.obj6 === exports.UNDEFINED) { + this.obj6 = inj._new(p.provider6, p.visibility6); + } + return this.obj6; + } + if (p.keyId7 === keyId && canSee(p.visibility7, visibility)) { + if (this.obj7 === exports.UNDEFINED) { + this.obj7 = inj._new(p.provider7, p.visibility7); + } + return this.obj7; + } + if (p.keyId8 === keyId && canSee(p.visibility8, visibility)) { + if (this.obj8 === exports.UNDEFINED) { + this.obj8 = inj._new(p.provider8, p.visibility8); + } + return this.obj8; + } + if (p.keyId9 === keyId && canSee(p.visibility9, visibility)) { + if (this.obj9 === exports.UNDEFINED) { + this.obj9 = inj._new(p.provider9, p.visibility9); + } + return this.obj9; + } + return exports.UNDEFINED; + }; + InjectorInlineStrategy.prototype.getObjAtIndex = function(index) { + if (index == 0) + return this.obj0; + if (index == 1) + return this.obj1; + if (index == 2) + return this.obj2; + if (index == 3) + return this.obj3; + if (index == 4) + return this.obj4; + if (index == 5) + return this.obj5; + if (index == 6) + return this.obj6; + if (index == 7) + return this.obj7; + if (index == 8) + return this.obj8; + if (index == 9) + return this.obj9; + throw new exceptions_1.OutOfBoundsError(index); + }; + InjectorInlineStrategy.prototype.getMaxNumberOfObjects = function() { + return _MAX_CONSTRUCTION_COUNTER; + }; + return InjectorInlineStrategy; + })(); + exports.InjectorInlineStrategy = InjectorInlineStrategy; + var InjectorDynamicStrategy = (function() { + function InjectorDynamicStrategy(protoStrategy, injector) { + this.protoStrategy = protoStrategy; + this.injector = injector; + this.objs = collection_1.ListWrapper.createFixedSize(protoStrategy.providers.length); + collection_1.ListWrapper.fill(this.objs, exports.UNDEFINED); + } + InjectorDynamicStrategy.prototype.resetConstructionCounter = function() { + this.injector._constructionCounter = 0; + }; + InjectorDynamicStrategy.prototype.instantiateProvider = function(provider, visibility) { + return this.injector._new(provider, visibility); + }; + InjectorDynamicStrategy.prototype.attach = function(parent, isHost) { + var inj = this.injector; + inj._parent = parent; + inj._isHost = isHost; + }; + InjectorDynamicStrategy.prototype.getObjByKeyId = function(keyId, visibility) { + var p = this.protoStrategy; + for (var i = 0; i < p.keyIds.length; i++) { + if (p.keyIds[i] === keyId && canSee(p.visibilities[i], visibility)) { + if (this.objs[i] === exports.UNDEFINED) { + this.objs[i] = this.injector._new(p.providers[i], p.visibilities[i]); + } + return this.objs[i]; + } + } + return exports.UNDEFINED; + }; + InjectorDynamicStrategy.prototype.getObjAtIndex = function(index) { + if (index < 0 || index >= this.objs.length) { + throw new exceptions_1.OutOfBoundsError(index); + } + return this.objs[index]; + }; + InjectorDynamicStrategy.prototype.getMaxNumberOfObjects = function() { + return this.objs.length; + }; + return InjectorDynamicStrategy; + })(); + exports.InjectorDynamicStrategy = InjectorDynamicStrategy; + var ProviderWithVisibility = (function() { + function ProviderWithVisibility(provider, visibility) { + this.provider = provider; + this.visibility = visibility; + } + ; + ProviderWithVisibility.prototype.getKeyId = function() { + return this.provider.key.id; + }; + return ProviderWithVisibility; + })(); + exports.ProviderWithVisibility = ProviderWithVisibility; + var Injector = (function() { + function Injector(_proto, _parent, _depProvider, _debugContext) { + if (_parent === void 0) { + _parent = null; + } + if (_depProvider === void 0) { + _depProvider = null; + } + if (_debugContext === void 0) { + _debugContext = null; + } + this._depProvider = _depProvider; + this._debugContext = _debugContext; + this._isHost = false; + this._constructionCounter = 0; + this._proto = _proto; + this._parent = _parent; + this._strategy = _proto._strategy.createInjectorStrategy(this); + } + Injector.resolve = function(providers) { + return provider_1.resolveProviders(providers); + }; + Injector.resolveAndCreate = function(providers) { + var resolvedProviders = Injector.resolve(providers); + return Injector.fromResolvedProviders(resolvedProviders); + }; + Injector.fromResolvedProviders = function(providers) { + var bd = providers.map(function(b) { + return new ProviderWithVisibility(b, Visibility.Public); + }); + var proto = new ProtoInjector(bd); + return new Injector(proto, null, null); + }; + Injector.fromResolvedBindings = function(providers) { + return Injector.fromResolvedProviders(providers); + }; + Injector.prototype.debugContext = function() { + return this._debugContext(); + }; + Injector.prototype.get = function(token) { + return this._getByKey(key_1.Key.get(token), null, null, false, Visibility.PublicAndPrivate); + }; + Injector.prototype.getOptional = function(token) { + return this._getByKey(key_1.Key.get(token), null, null, true, Visibility.PublicAndPrivate); + }; + Injector.prototype.getAt = function(index) { + return this._strategy.getObjAtIndex(index); + }; + Object.defineProperty(Injector.prototype, "parent", { + get: function() { + return this._parent; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Injector.prototype, "internalStrategy", { + get: function() { + return this._strategy; + }, + enumerable: true, + configurable: true + }); + Injector.prototype.resolveAndCreateChild = function(providers) { + var resolvedProviders = Injector.resolve(providers); + return this.createChildFromResolved(resolvedProviders); + }; + Injector.prototype.createChildFromResolved = function(providers) { + var bd = providers.map(function(b) { + return new ProviderWithVisibility(b, Visibility.Public); + }); + var proto = new ProtoInjector(bd); + var inj = new Injector(proto, null, null); + inj._parent = this; + return inj; + }; + Injector.prototype.resolveAndInstantiate = function(provider) { + return this.instantiateResolved(Injector.resolve([provider])[0]); + }; + Injector.prototype.instantiateResolved = function(provider) { + return this._instantiateProvider(provider, Visibility.PublicAndPrivate); + }; + Injector.prototype._new = function(provider, visibility) { + if (this._constructionCounter++ > this._strategy.getMaxNumberOfObjects()) { + throw new exceptions_1.CyclicDependencyError(this, provider.key); + } + return this._instantiateProvider(provider, visibility); + }; + Injector.prototype._instantiateProvider = function(provider, visibility) { + if (provider.multiProvider) { + var res = collection_1.ListWrapper.createFixedSize(provider.resolvedFactories.length); + for (var i = 0; i < provider.resolvedFactories.length; ++i) { + res[i] = this._instantiate(provider, provider.resolvedFactories[i], visibility); + } + return res; + } else { + return this._instantiate(provider, provider.resolvedFactories[0], visibility); + } + }; + Injector.prototype._instantiate = function(provider, resolvedFactory, visibility) { + var factory = resolvedFactory.factory; + var deps = resolvedFactory.dependencies; + var length = deps.length; + var d0, + d1, + d2, + d3, + d4, + d5, + d6, + d7, + d8, + d9, + d10, + d11, + d12, + d13, + d14, + d15, + d16, + d17, + d18, + d19; + try { + d0 = length > 0 ? this._getByDependency(provider, deps[0], visibility) : null; + d1 = length > 1 ? this._getByDependency(provider, deps[1], visibility) : null; + d2 = length > 2 ? this._getByDependency(provider, deps[2], visibility) : null; + d3 = length > 3 ? this._getByDependency(provider, deps[3], visibility) : null; + d4 = length > 4 ? this._getByDependency(provider, deps[4], visibility) : null; + d5 = length > 5 ? this._getByDependency(provider, deps[5], visibility) : null; + d6 = length > 6 ? this._getByDependency(provider, deps[6], visibility) : null; + d7 = length > 7 ? this._getByDependency(provider, deps[7], visibility) : null; + d8 = length > 8 ? this._getByDependency(provider, deps[8], visibility) : null; + d9 = length > 9 ? this._getByDependency(provider, deps[9], visibility) : null; + d10 = length > 10 ? this._getByDependency(provider, deps[10], visibility) : null; + d11 = length > 11 ? this._getByDependency(provider, deps[11], visibility) : null; + d12 = length > 12 ? this._getByDependency(provider, deps[12], visibility) : null; + d13 = length > 13 ? this._getByDependency(provider, deps[13], visibility) : null; + d14 = length > 14 ? this._getByDependency(provider, deps[14], visibility) : null; + d15 = length > 15 ? this._getByDependency(provider, deps[15], visibility) : null; + d16 = length > 16 ? this._getByDependency(provider, deps[16], visibility) : null; + d17 = length > 17 ? this._getByDependency(provider, deps[17], visibility) : null; + d18 = length > 18 ? this._getByDependency(provider, deps[18], visibility) : null; + d19 = length > 19 ? this._getByDependency(provider, deps[19], visibility) : null; + } catch (e) { + if (e instanceof exceptions_1.AbstractProviderError || e instanceof exceptions_1.InstantiationError) { + e.addKey(this, provider.key); + } + throw e; + } + var obj; + try { + switch (length) { + case 0: + obj = factory(); + break; + case 1: + obj = factory(d0); + break; + case 2: + obj = factory(d0, d1); + break; + case 3: + obj = factory(d0, d1, d2); + break; + case 4: + obj = factory(d0, d1, d2, d3); + break; + case 5: + obj = factory(d0, d1, d2, d3, d4); + break; + case 6: + obj = factory(d0, d1, d2, d3, d4, d5); + break; + case 7: + obj = factory(d0, d1, d2, d3, d4, d5, d6); + break; + case 8: + obj = factory(d0, d1, d2, d3, d4, d5, d6, d7); + break; + case 9: + obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8); + break; + case 10: + obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9); + break; + case 11: + obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10); + break; + case 12: + obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11); + break; + case 13: + obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12); + break; + case 14: + obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13); + break; + case 15: + obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14); + break; + case 16: + obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15); + break; + case 17: + obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16); + break; + case 18: + obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17); + break; + case 19: + obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17, d18); + break; + case 20: + obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17, d18, d19); + break; + } + } catch (e) { + throw new exceptions_1.InstantiationError(this, e, e.stack, provider.key); + } + return obj; + }; + Injector.prototype._getByDependency = function(provider, dep, providerVisibility) { + var special = lang_1.isPresent(this._depProvider) ? this._depProvider.getDependency(this, provider, dep) : exports.UNDEFINED; + if (special !== exports.UNDEFINED) { + return special; + } else { + return this._getByKey(dep.key, dep.lowerBoundVisibility, dep.upperBoundVisibility, dep.optional, providerVisibility); + } + }; + Injector.prototype._getByKey = function(key, lowerBoundVisibility, upperBoundVisibility, optional, providerVisibility) { + if (key === INJECTOR_KEY) { + return this; + } + if (upperBoundVisibility instanceof metadata_1.SelfMetadata) { + return this._getByKeySelf(key, optional, providerVisibility); + } else if (upperBoundVisibility instanceof metadata_1.HostMetadata) { + return this._getByKeyHost(key, optional, providerVisibility, lowerBoundVisibility); + } else { + return this._getByKeyDefault(key, optional, providerVisibility, lowerBoundVisibility); + } + }; + Injector.prototype._throwOrNull = function(key, optional) { + if (optional) { + return null; + } else { + throw new exceptions_1.NoProviderError(this, key); + } + }; + Injector.prototype._getByKeySelf = function(key, optional, providerVisibility) { + var obj = this._strategy.getObjByKeyId(key.id, providerVisibility); + return (obj !== exports.UNDEFINED) ? obj : this._throwOrNull(key, optional); + }; + Injector.prototype._getByKeyHost = function(key, optional, providerVisibility, lowerBoundVisibility) { + var inj = this; + if (lowerBoundVisibility instanceof metadata_1.SkipSelfMetadata) { + if (inj._isHost) { + return this._getPrivateDependency(key, optional, inj); + } else { + inj = inj._parent; + } + } + while (inj != null) { + var obj = inj._strategy.getObjByKeyId(key.id, providerVisibility); + if (obj !== exports.UNDEFINED) + return obj; + if (lang_1.isPresent(inj._parent) && inj._isHost) { + return this._getPrivateDependency(key, optional, inj); + } else { + inj = inj._parent; + } + } + return this._throwOrNull(key, optional); + }; + Injector.prototype._getPrivateDependency = function(key, optional, inj) { + var obj = inj._parent._strategy.getObjByKeyId(key.id, Visibility.Private); + return (obj !== exports.UNDEFINED) ? obj : this._throwOrNull(key, optional); + }; + Injector.prototype._getByKeyDefault = function(key, optional, providerVisibility, lowerBoundVisibility) { + var inj = this; + if (lowerBoundVisibility instanceof metadata_1.SkipSelfMetadata) { + providerVisibility = inj._isHost ? Visibility.PublicAndPrivate : Visibility.Public; + inj = inj._parent; + } + while (inj != null) { + var obj = inj._strategy.getObjByKeyId(key.id, providerVisibility); + if (obj !== exports.UNDEFINED) + return obj; + providerVisibility = inj._isHost ? Visibility.PublicAndPrivate : Visibility.Public; + inj = inj._parent; + } + return this._throwOrNull(key, optional); + }; + Object.defineProperty(Injector.prototype, "displayName", { + get: function() { + return "Injector(providers: [" + _mapProviders(this, function(b) { + return (" \"" + b.key.displayName + "\" "); + }).join(", ") + "])"; + }, + enumerable: true, + configurable: true + }); + Injector.prototype.toString = function() { + return this.displayName; + }; + return Injector; + })(); + exports.Injector = Injector; + var INJECTOR_KEY = key_1.Key.get(Injector); + function _mapProviders(injector, fn) { + var res = []; + for (var i = 0; i < injector._proto.numberOfProviders; ++i) { + res.push(fn(injector._proto.getProviderAtIndex(i))); + } + return res; + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/animate/animation_builder", ["angular2/src/core/di", "angular2/src/animate/css_animation_builder", "angular2/src/animate/browser_details"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var di_1 = require("angular2/src/core/di"); + var css_animation_builder_1 = require("angular2/src/animate/css_animation_builder"); + var browser_details_1 = require("angular2/src/animate/browser_details"); + var AnimationBuilder = (function() { + function AnimationBuilder(browserDetails) { + this.browserDetails = browserDetails; + } + AnimationBuilder.prototype.css = function() { + return new css_animation_builder_1.CssAnimationBuilder(this.browserDetails); + }; + AnimationBuilder = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [browser_details_1.BrowserDetails])], AnimationBuilder); + return AnimationBuilder; + })(); + exports.AnimationBuilder = AnimationBuilder; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/proto_change_detector", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/core/change_detection/parser/ast", "angular2/src/core/change_detection/change_detection_util", "angular2/src/core/change_detection/dynamic_change_detector", "angular2/src/core/change_detection/directive_record", "angular2/src/core/change_detection/event_binding", "angular2/src/core/change_detection/coalesce", "angular2/src/core/change_detection/proto_record"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var ast_1 = require("angular2/src/core/change_detection/parser/ast"); + var change_detection_util_1 = require("angular2/src/core/change_detection/change_detection_util"); + var dynamic_change_detector_1 = require("angular2/src/core/change_detection/dynamic_change_detector"); + var directive_record_1 = require("angular2/src/core/change_detection/directive_record"); + var event_binding_1 = require("angular2/src/core/change_detection/event_binding"); + var coalesce_1 = require("angular2/src/core/change_detection/coalesce"); + var proto_record_1 = require("angular2/src/core/change_detection/proto_record"); + var DynamicProtoChangeDetector = (function() { + function DynamicProtoChangeDetector(_definition) { + this._definition = _definition; + this._propertyBindingRecords = createPropertyRecords(_definition); + this._eventBindingRecords = createEventRecords(_definition); + this._propertyBindingTargets = this._definition.bindingRecords.map(function(b) { + return b.target; + }); + this._directiveIndices = this._definition.directiveRecords.map(function(d) { + return d.directiveIndex; + }); + } + DynamicProtoChangeDetector.prototype.instantiate = function(dispatcher) { + return new dynamic_change_detector_1.DynamicChangeDetector(this._definition.id, dispatcher, this._propertyBindingRecords.length, this._propertyBindingTargets, this._directiveIndices, this._definition.strategy, this._propertyBindingRecords, this._eventBindingRecords, this._definition.directiveRecords, this._definition.genConfig); + }; + return DynamicProtoChangeDetector; + })(); + exports.DynamicProtoChangeDetector = DynamicProtoChangeDetector; + function createPropertyRecords(definition) { + var recordBuilder = new ProtoRecordBuilder(); + collection_1.ListWrapper.forEachWithIndex(definition.bindingRecords, function(b, index) { + return recordBuilder.add(b, definition.variableNames, index); + }); + return coalesce_1.coalesce(recordBuilder.records); + } + exports.createPropertyRecords = createPropertyRecords; + function createEventRecords(definition) { + var varNames = collection_1.ListWrapper.concat(['$event'], definition.variableNames); + return definition.eventRecords.map(function(er) { + var records = _ConvertAstIntoProtoRecords.create(er, varNames); + var dirIndex = er.implicitReceiver instanceof directive_record_1.DirectiveIndex ? er.implicitReceiver : null; + return new event_binding_1.EventBinding(er.target.name, er.target.elementIndex, dirIndex, records); + }); + } + exports.createEventRecords = createEventRecords; + var ProtoRecordBuilder = (function() { + function ProtoRecordBuilder() { + this.records = []; + } + ProtoRecordBuilder.prototype.add = function(b, variableNames, bindingIndex) { + var oldLast = collection_1.ListWrapper.last(this.records); + if (lang_1.isPresent(oldLast) && oldLast.bindingRecord.directiveRecord == b.directiveRecord) { + oldLast.lastInDirective = false; + } + var numberOfRecordsBefore = this.records.length; + this._appendRecords(b, variableNames, bindingIndex); + var newLast = collection_1.ListWrapper.last(this.records); + if (lang_1.isPresent(newLast) && newLast !== oldLast) { + newLast.lastInBinding = true; + newLast.lastInDirective = true; + this._setArgumentToPureFunction(numberOfRecordsBefore); + } + }; + ProtoRecordBuilder.prototype._setArgumentToPureFunction = function(startIndex) { + var _this = this; + for (var i = startIndex; i < this.records.length; ++i) { + var rec = this.records[i]; + if (rec.isPureFunction()) { + rec.args.forEach(function(recordIndex) { + return _this.records[recordIndex - 1].argumentToPureFunction = true; + }); + } + if (rec.mode === proto_record_1.RecordType.Pipe) { + rec.args.forEach(function(recordIndex) { + return _this.records[recordIndex - 1].argumentToPureFunction = true; + }); + this.records[rec.contextIndex - 1].argumentToPureFunction = true; + } + } + }; + ProtoRecordBuilder.prototype._appendRecords = function(b, variableNames, bindingIndex) { + if (b.isDirectiveLifecycle()) { + this.records.push(new proto_record_1.ProtoRecord(proto_record_1.RecordType.DirectiveLifecycle, b.lifecycleEvent, null, [], [], -1, null, this.records.length + 1, b, false, false, false, false, null)); + } else { + _ConvertAstIntoProtoRecords.append(this.records, b, variableNames, bindingIndex); + } + }; + return ProtoRecordBuilder; + })(); + exports.ProtoRecordBuilder = ProtoRecordBuilder; + var _ConvertAstIntoProtoRecords = (function() { + function _ConvertAstIntoProtoRecords(_records, _bindingRecord, _variableNames, _bindingIndex) { + this._records = _records; + this._bindingRecord = _bindingRecord; + this._variableNames = _variableNames; + this._bindingIndex = _bindingIndex; + } + _ConvertAstIntoProtoRecords.append = function(records, b, variableNames, bindingIndex) { + var c = new _ConvertAstIntoProtoRecords(records, b, variableNames, bindingIndex); + b.ast.visit(c); + }; + _ConvertAstIntoProtoRecords.create = function(b, variableNames) { + var rec = []; + _ConvertAstIntoProtoRecords.append(rec, b, variableNames, null); + rec[rec.length - 1].lastInBinding = true; + return rec; + }; + _ConvertAstIntoProtoRecords.prototype.visitImplicitReceiver = function(ast) { + return this._bindingRecord.implicitReceiver; + }; + _ConvertAstIntoProtoRecords.prototype.visitInterpolation = function(ast) { + var args = this._visitAll(ast.expressions); + return this._addRecord(proto_record_1.RecordType.Interpolate, "interpolate", _interpolationFn(ast.strings), args, ast.strings, 0); + }; + _ConvertAstIntoProtoRecords.prototype.visitLiteralPrimitive = function(ast) { + return this._addRecord(proto_record_1.RecordType.Const, "literal", ast.value, [], null, 0); + }; + _ConvertAstIntoProtoRecords.prototype.visitPropertyRead = function(ast) { + var receiver = ast.receiver.visit(this); + if (lang_1.isPresent(this._variableNames) && collection_1.ListWrapper.contains(this._variableNames, ast.name) && ast.receiver instanceof ast_1.ImplicitReceiver) { + return this._addRecord(proto_record_1.RecordType.Local, ast.name, ast.name, [], null, receiver); + } else { + return this._addRecord(proto_record_1.RecordType.PropertyRead, ast.name, ast.getter, [], null, receiver); + } + }; + _ConvertAstIntoProtoRecords.prototype.visitPropertyWrite = function(ast) { + if (lang_1.isPresent(this._variableNames) && collection_1.ListWrapper.contains(this._variableNames, ast.name) && ast.receiver instanceof ast_1.ImplicitReceiver) { + throw new exceptions_1.BaseException("Cannot reassign a variable binding " + ast.name); + } else { + var receiver = ast.receiver.visit(this); + var value = ast.value.visit(this); + return this._addRecord(proto_record_1.RecordType.PropertyWrite, ast.name, ast.setter, [value], null, receiver); + } + }; + _ConvertAstIntoProtoRecords.prototype.visitKeyedWrite = function(ast) { + var obj = ast.obj.visit(this); + var key = ast.key.visit(this); + var value = ast.value.visit(this); + return this._addRecord(proto_record_1.RecordType.KeyedWrite, null, null, [key, value], null, obj); + }; + _ConvertAstIntoProtoRecords.prototype.visitSafePropertyRead = function(ast) { + var receiver = ast.receiver.visit(this); + return this._addRecord(proto_record_1.RecordType.SafeProperty, ast.name, ast.getter, [], null, receiver); + }; + _ConvertAstIntoProtoRecords.prototype.visitMethodCall = function(ast) { + var receiver = ast.receiver.visit(this); + var args = this._visitAll(ast.args); + if (lang_1.isPresent(this._variableNames) && collection_1.ListWrapper.contains(this._variableNames, ast.name)) { + var target = this._addRecord(proto_record_1.RecordType.Local, ast.name, ast.name, [], null, receiver); + return this._addRecord(proto_record_1.RecordType.InvokeClosure, "closure", null, args, null, target); + } else { + return this._addRecord(proto_record_1.RecordType.InvokeMethod, ast.name, ast.fn, args, null, receiver); + } + }; + _ConvertAstIntoProtoRecords.prototype.visitSafeMethodCall = function(ast) { + var receiver = ast.receiver.visit(this); + var args = this._visitAll(ast.args); + return this._addRecord(proto_record_1.RecordType.SafeMethodInvoke, ast.name, ast.fn, args, null, receiver); + }; + _ConvertAstIntoProtoRecords.prototype.visitFunctionCall = function(ast) { + var target = ast.target.visit(this); + var args = this._visitAll(ast.args); + return this._addRecord(proto_record_1.RecordType.InvokeClosure, "closure", null, args, null, target); + }; + _ConvertAstIntoProtoRecords.prototype.visitLiteralArray = function(ast) { + var primitiveName = "arrayFn" + ast.expressions.length; + return this._addRecord(proto_record_1.RecordType.CollectionLiteral, primitiveName, _arrayFn(ast.expressions.length), this._visitAll(ast.expressions), null, 0); + }; + _ConvertAstIntoProtoRecords.prototype.visitLiteralMap = function(ast) { + return this._addRecord(proto_record_1.RecordType.CollectionLiteral, _mapPrimitiveName(ast.keys), change_detection_util_1.ChangeDetectionUtil.mapFn(ast.keys), this._visitAll(ast.values), null, 0); + }; + _ConvertAstIntoProtoRecords.prototype.visitBinary = function(ast) { + var left = ast.left.visit(this); + switch (ast.operation) { + case '&&': + var branchEnd = [null]; + this._addRecord(proto_record_1.RecordType.SkipRecordsIfNot, "SkipRecordsIfNot", null, [], branchEnd, left); + var right = ast.right.visit(this); + branchEnd[0] = right; + return this._addRecord(proto_record_1.RecordType.PrimitiveOp, "cond", change_detection_util_1.ChangeDetectionUtil.cond, [left, right, left], null, 0); + case '||': + var branchEnd = [null]; + this._addRecord(proto_record_1.RecordType.SkipRecordsIf, "SkipRecordsIf", null, [], branchEnd, left); + var right = ast.right.visit(this); + branchEnd[0] = right; + return this._addRecord(proto_record_1.RecordType.PrimitiveOp, "cond", change_detection_util_1.ChangeDetectionUtil.cond, [left, left, right], null, 0); + default: + var right = ast.right.visit(this); + return this._addRecord(proto_record_1.RecordType.PrimitiveOp, _operationToPrimitiveName(ast.operation), _operationToFunction(ast.operation), [left, right], null, 0); + } + }; + _ConvertAstIntoProtoRecords.prototype.visitPrefixNot = function(ast) { + var exp = ast.expression.visit(this); + return this._addRecord(proto_record_1.RecordType.PrimitiveOp, "operation_negate", change_detection_util_1.ChangeDetectionUtil.operation_negate, [exp], null, 0); + }; + _ConvertAstIntoProtoRecords.prototype.visitConditional = function(ast) { + var condition = ast.condition.visit(this); + var startOfFalseBranch = [null]; + var endOfFalseBranch = [null]; + this._addRecord(proto_record_1.RecordType.SkipRecordsIfNot, "SkipRecordsIfNot", null, [], startOfFalseBranch, condition); + var whenTrue = ast.trueExp.visit(this); + var skip = this._addRecord(proto_record_1.RecordType.SkipRecords, "SkipRecords", null, [], endOfFalseBranch, 0); + var whenFalse = ast.falseExp.visit(this); + startOfFalseBranch[0] = skip; + endOfFalseBranch[0] = whenFalse; + return this._addRecord(proto_record_1.RecordType.PrimitiveOp, "cond", change_detection_util_1.ChangeDetectionUtil.cond, [condition, whenTrue, whenFalse], null, 0); + }; + _ConvertAstIntoProtoRecords.prototype.visitPipe = function(ast) { + var value = ast.exp.visit(this); + var args = this._visitAll(ast.args); + return this._addRecord(proto_record_1.RecordType.Pipe, ast.name, ast.name, args, null, value); + }; + _ConvertAstIntoProtoRecords.prototype.visitKeyedRead = function(ast) { + var obj = ast.obj.visit(this); + var key = ast.key.visit(this); + return this._addRecord(proto_record_1.RecordType.KeyedRead, "keyedAccess", change_detection_util_1.ChangeDetectionUtil.keyedAccess, [key], null, obj); + }; + _ConvertAstIntoProtoRecords.prototype.visitChain = function(ast) { + var _this = this; + var args = ast.expressions.map(function(e) { + return e.visit(_this); + }); + return this._addRecord(proto_record_1.RecordType.Chain, "chain", null, args, null, 0); + }; + _ConvertAstIntoProtoRecords.prototype.visitQuote = function(ast) { + throw new exceptions_1.BaseException(("Caught uninterpreted expression at " + ast.location + ": " + ast.uninterpretedExpression + ". ") + ("Expression prefix " + ast.prefix + " did not match a template transformer to interpret the expression.")); + }; + _ConvertAstIntoProtoRecords.prototype._visitAll = function(asts) { + var res = collection_1.ListWrapper.createFixedSize(asts.length); + for (var i = 0; i < asts.length; ++i) { + res[i] = asts[i].visit(this); + } + return res; + }; + _ConvertAstIntoProtoRecords.prototype._addRecord = function(type, name, funcOrValue, args, fixedArgs, context) { + var selfIndex = this._records.length + 1; + if (context instanceof directive_record_1.DirectiveIndex) { + this._records.push(new proto_record_1.ProtoRecord(type, name, funcOrValue, args, fixedArgs, -1, context, selfIndex, this._bindingRecord, false, false, false, false, this._bindingIndex)); + } else { + this._records.push(new proto_record_1.ProtoRecord(type, name, funcOrValue, args, fixedArgs, context, null, selfIndex, this._bindingRecord, false, false, false, false, this._bindingIndex)); + } + return selfIndex; + }; + return _ConvertAstIntoProtoRecords; + })(); + function _arrayFn(length) { + switch (length) { + case 0: + return change_detection_util_1.ChangeDetectionUtil.arrayFn0; + case 1: + return change_detection_util_1.ChangeDetectionUtil.arrayFn1; + case 2: + return change_detection_util_1.ChangeDetectionUtil.arrayFn2; + case 3: + return change_detection_util_1.ChangeDetectionUtil.arrayFn3; + case 4: + return change_detection_util_1.ChangeDetectionUtil.arrayFn4; + case 5: + return change_detection_util_1.ChangeDetectionUtil.arrayFn5; + case 6: + return change_detection_util_1.ChangeDetectionUtil.arrayFn6; + case 7: + return change_detection_util_1.ChangeDetectionUtil.arrayFn7; + case 8: + return change_detection_util_1.ChangeDetectionUtil.arrayFn8; + case 9: + return change_detection_util_1.ChangeDetectionUtil.arrayFn9; + default: + throw new exceptions_1.BaseException("Does not support literal maps with more than 9 elements"); + } + } + function _mapPrimitiveName(keys) { + var stringifiedKeys = keys.map(function(k) { + return lang_1.isString(k) ? "\"" + k + "\"" : "" + k; + }).join(', '); + return "mapFn([" + stringifiedKeys + "])"; + } + function _operationToPrimitiveName(operation) { + switch (operation) { + case '+': + return "operation_add"; + case '-': + return "operation_subtract"; + case '*': + return "operation_multiply"; + case '/': + return "operation_divide"; + case '%': + return "operation_remainder"; + case '==': + return "operation_equals"; + case '!=': + return "operation_not_equals"; + case '===': + return "operation_identical"; + case '!==': + return "operation_not_identical"; + case '<': + return "operation_less_then"; + case '>': + return "operation_greater_then"; + case '<=': + return "operation_less_or_equals_then"; + case '>=': + return "operation_greater_or_equals_then"; + default: + throw new exceptions_1.BaseException("Unsupported operation " + operation); + } + } + function _operationToFunction(operation) { + switch (operation) { + case '+': + return change_detection_util_1.ChangeDetectionUtil.operation_add; + case '-': + return change_detection_util_1.ChangeDetectionUtil.operation_subtract; + case '*': + return change_detection_util_1.ChangeDetectionUtil.operation_multiply; + case '/': + return change_detection_util_1.ChangeDetectionUtil.operation_divide; + case '%': + return change_detection_util_1.ChangeDetectionUtil.operation_remainder; + case '==': + return change_detection_util_1.ChangeDetectionUtil.operation_equals; + case '!=': + return change_detection_util_1.ChangeDetectionUtil.operation_not_equals; + case '===': + return change_detection_util_1.ChangeDetectionUtil.operation_identical; + case '!==': + return change_detection_util_1.ChangeDetectionUtil.operation_not_identical; + case '<': + return change_detection_util_1.ChangeDetectionUtil.operation_less_then; + case '>': + return change_detection_util_1.ChangeDetectionUtil.operation_greater_then; + case '<=': + return change_detection_util_1.ChangeDetectionUtil.operation_less_or_equals_then; + case '>=': + return change_detection_util_1.ChangeDetectionUtil.operation_greater_or_equals_then; + default: + throw new exceptions_1.BaseException("Unsupported operation " + operation); + } + } + function s(v) { + return lang_1.isPresent(v) ? "" + v : ''; + } + function _interpolationFn(strings) { + var length = strings.length; + var c0 = length > 0 ? strings[0] : null; + var c1 = length > 1 ? strings[1] : null; + var c2 = length > 2 ? strings[2] : null; + var c3 = length > 3 ? strings[3] : null; + var c4 = length > 4 ? strings[4] : null; + var c5 = length > 5 ? strings[5] : null; + var c6 = length > 6 ? strings[6] : null; + var c7 = length > 7 ? strings[7] : null; + var c8 = length > 8 ? strings[8] : null; + var c9 = length > 9 ? strings[9] : null; + switch (length - 1) { + case 1: + return function(a1) { + return c0 + s(a1) + c1; + }; + case 2: + return function(a1, a2) { + return c0 + s(a1) + c1 + s(a2) + c2; + }; + case 3: + return function(a1, a2, a3) { + return c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3; + }; + case 4: + return function(a1, a2, a3, a4) { + return c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) + c4; + }; + case 5: + return function(a1, a2, a3, a4, a5) { + return c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) + c4 + s(a5) + c5; + }; + case 6: + return function(a1, a2, a3, a4, a5, a6) { + return c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) + c4 + s(a5) + c5 + s(a6) + c6; + }; + case 7: + return function(a1, a2, a3, a4, a5, a6, a7) { + return c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) + c4 + s(a5) + c5 + s(a6) + c6 + s(a7) + c7; + }; + case 8: + return function(a1, a2, a3, a4, a5, a6, a7, a8) { + return c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) + c4 + s(a5) + c5 + s(a6) + c6 + s(a7) + c7 + s(a8) + c8; + }; + case 9: + return function(a1, a2, a3, a4, a5, a6, a7, a8, a9) { + return c0 + s(a1) + c1 + s(a2) + c2 + s(a3) + c3 + s(a4) + c4 + s(a5) + c5 + s(a6) + c6 + s(a7) + c7 + s(a8) + c8 + s(a9) + c9; + }; + default: + throw new exceptions_1.BaseException("Does not support more than 9 expressions"); + } + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/jit_proto_change_detector", ["angular2/src/core/change_detection/change_detection_jit_generator"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var change_detection_jit_generator_1 = require("angular2/src/core/change_detection/change_detection_jit_generator"); + var JitProtoChangeDetector = (function() { + function JitProtoChangeDetector(definition) { + this.definition = definition; + this._factory = this._createFactory(definition); + } + JitProtoChangeDetector.isSupported = function() { + return true; + }; + JitProtoChangeDetector.prototype.instantiate = function(dispatcher) { + return this._factory(dispatcher); + }; + JitProtoChangeDetector.prototype._createFactory = function(definition) { + return new change_detection_jit_generator_1.ChangeDetectorJITGenerator(definition, 'util', 'AbstractChangeDetector', 'ChangeDetectorStatus').generate(); + }; + return JitProtoChangeDetector; + })(); + exports.JitProtoChangeDetector = JitProtoChangeDetector; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/element_injector", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/async", "angular2/src/facade/collection", "angular2/src/core/di", "angular2/src/core/di/injector", "angular2/src/core/di/provider", "angular2/src/core/metadata/di", "angular2/src/core/linker/view_manager", "angular2/src/core/linker/view_container_ref", "angular2/src/core/linker/element_ref", "angular2/src/core/linker/template_ref", "angular2/src/core/metadata/directives", "angular2/src/core/linker/directive_lifecycle_reflector", "angular2/src/core/change_detection/change_detection", "angular2/src/core/linker/query_list", "angular2/src/core/reflection/reflection", "angular2/src/core/linker/event_config", "angular2/src/core/pipes/pipe_provider", "angular2/src/core/linker/interfaces", "angular2/src/core/linker/view_container_ref"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var async_1 = require("angular2/src/facade/async"); + var collection_1 = require("angular2/src/facade/collection"); + var di_1 = require("angular2/src/core/di"); + var injector_1 = require("angular2/src/core/di/injector"); + var provider_1 = require("angular2/src/core/di/provider"); + var di_2 = require("angular2/src/core/metadata/di"); + var avmModule = require("angular2/src/core/linker/view_manager"); + var view_container_ref_1 = require("angular2/src/core/linker/view_container_ref"); + var element_ref_1 = require("angular2/src/core/linker/element_ref"); + var template_ref_1 = require("angular2/src/core/linker/template_ref"); + var directives_1 = require("angular2/src/core/metadata/directives"); + var directive_lifecycle_reflector_1 = require("angular2/src/core/linker/directive_lifecycle_reflector"); + var change_detection_1 = require("angular2/src/core/change_detection/change_detection"); + var query_list_1 = require("angular2/src/core/linker/query_list"); + var reflection_1 = require("angular2/src/core/reflection/reflection"); + var event_config_1 = require("angular2/src/core/linker/event_config"); + var pipe_provider_1 = require("angular2/src/core/pipes/pipe_provider"); + var interfaces_1 = require("angular2/src/core/linker/interfaces"); + var view_container_ref_2 = require("angular2/src/core/linker/view_container_ref"); + var _staticKeys; + var StaticKeys = (function() { + function StaticKeys() { + this.viewManagerId = di_1.Key.get(avmModule.AppViewManager).id; + this.templateRefId = di_1.Key.get(template_ref_1.TemplateRef).id; + this.viewContainerId = di_1.Key.get(view_container_ref_1.ViewContainerRef).id; + this.changeDetectorRefId = di_1.Key.get(change_detection_1.ChangeDetectorRef).id; + this.elementRefId = di_1.Key.get(element_ref_1.ElementRef).id; + } + StaticKeys.instance = function() { + if (lang_1.isBlank(_staticKeys)) + _staticKeys = new StaticKeys(); + return _staticKeys; + }; + return StaticKeys; + })(); + exports.StaticKeys = StaticKeys; + var TreeNode = (function() { + function TreeNode(parent) { + if (lang_1.isPresent(parent)) { + parent.addChild(this); + } else { + this._parent = null; + } + } + TreeNode.prototype.addChild = function(child) { + child._parent = this; + }; + TreeNode.prototype.remove = function() { + this._parent = null; + }; + Object.defineProperty(TreeNode.prototype, "parent", { + get: function() { + return this._parent; + }, + enumerable: true, + configurable: true + }); + return TreeNode; + })(); + exports.TreeNode = TreeNode; + var DirectiveDependency = (function(_super) { + __extends(DirectiveDependency, _super); + function DirectiveDependency(key, optional, lowerBoundVisibility, upperBoundVisibility, properties, attributeName, queryDecorator) { + _super.call(this, key, optional, lowerBoundVisibility, upperBoundVisibility, properties); + this.attributeName = attributeName; + this.queryDecorator = queryDecorator; + this._verify(); + } + DirectiveDependency.prototype._verify = function() { + var count = 0; + if (lang_1.isPresent(this.queryDecorator)) + count++; + if (lang_1.isPresent(this.attributeName)) + count++; + if (count > 1) + throw new exceptions_1.BaseException('A directive injectable can contain only one of the following @Attribute or @Query.'); + }; + DirectiveDependency.createFrom = function(d) { + return new DirectiveDependency(d.key, d.optional, d.lowerBoundVisibility, d.upperBoundVisibility, d.properties, DirectiveDependency._attributeName(d.properties), DirectiveDependency._query(d.properties)); + }; + DirectiveDependency._attributeName = function(properties) { + var p = properties.find(function(p) { + return p instanceof di_2.AttributeMetadata; + }); + return lang_1.isPresent(p) ? p.attributeName : null; + }; + DirectiveDependency._query = function(properties) { + return properties.find(function(p) { + return p instanceof di_2.QueryMetadata; + }); + }; + return DirectiveDependency; + })(di_1.Dependency); + exports.DirectiveDependency = DirectiveDependency; + var DirectiveProvider = (function(_super) { + __extends(DirectiveProvider, _super); + function DirectiveProvider(key, factory, deps, metadata, providers, viewProviders) { + _super.call(this, key, [new provider_1.ResolvedFactory(factory, deps)], false); + this.metadata = metadata; + this.providers = providers; + this.viewProviders = viewProviders; + this.callOnDestroy = directive_lifecycle_reflector_1.hasLifecycleHook(interfaces_1.LifecycleHooks.OnDestroy, key.token); + } + Object.defineProperty(DirectiveProvider.prototype, "displayName", { + get: function() { + return this.key.displayName; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectiveProvider.prototype, "queries", { + get: function() { + if (lang_1.isBlank(this.metadata.queries)) + return []; + var res = []; + collection_1.StringMapWrapper.forEach(this.metadata.queries, function(meta, fieldName) { + var setter = reflection_1.reflector.setter(fieldName); + res.push(new QueryMetadataWithSetter(setter, meta)); + }); + return res; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectiveProvider.prototype, "eventEmitters", { + get: function() { + return lang_1.isPresent(this.metadata) && lang_1.isPresent(this.metadata.outputs) ? this.metadata.outputs : []; + }, + enumerable: true, + configurable: true + }); + DirectiveProvider.createFromProvider = function(provider, meta) { + if (lang_1.isBlank(meta)) { + meta = new directives_1.DirectiveMetadata(); + } + var rb = provider_1.resolveProvider(provider); + var rf = rb.resolvedFactories[0]; + var deps = rf.dependencies.map(DirectiveDependency.createFrom); + var providers = lang_1.isPresent(meta.providers) ? meta.providers : []; + var viewBindigs = meta instanceof directives_1.ComponentMetadata && lang_1.isPresent(meta.viewProviders) ? meta.viewProviders : []; + return new DirectiveProvider(rb.key, rf.factory, deps, meta, providers, viewBindigs); + }; + DirectiveProvider.createFromType = function(type, annotation) { + var provider = new di_1.Provider(type, {useClass: type}); + return DirectiveProvider.createFromProvider(provider, annotation); + }; + return DirectiveProvider; + })(provider_1.ResolvedProvider_); + exports.DirectiveProvider = DirectiveProvider; + var PreBuiltObjects = (function() { + function PreBuiltObjects(viewManager, view, elementRef, templateRef) { + this.viewManager = viewManager; + this.view = view; + this.elementRef = elementRef; + this.templateRef = templateRef; + this.nestedView = null; + } + return PreBuiltObjects; + })(); + exports.PreBuiltObjects = PreBuiltObjects; + var QueryMetadataWithSetter = (function() { + function QueryMetadataWithSetter(setter, metadata) { + this.setter = setter; + this.metadata = metadata; + } + return QueryMetadataWithSetter; + })(); + exports.QueryMetadataWithSetter = QueryMetadataWithSetter; + var EventEmitterAccessor = (function() { + function EventEmitterAccessor(eventName, getter) { + this.eventName = eventName; + this.getter = getter; + } + EventEmitterAccessor.prototype.subscribe = function(view, boundElementIndex, directive) { + var _this = this; + var eventEmitter = this.getter(directive); + return async_1.ObservableWrapper.subscribe(eventEmitter, function(eventObj) { + return view.triggerEventHandlers(_this.eventName, eventObj, boundElementIndex); + }); + }; + return EventEmitterAccessor; + })(); + exports.EventEmitterAccessor = EventEmitterAccessor; + function _createEventEmitterAccessors(bwv) { + var provider = bwv.provider; + if (!(provider instanceof DirectiveProvider)) + return []; + var db = provider; + return db.eventEmitters.map(function(eventConfig) { + var parsedEvent = event_config_1.EventConfig.parse(eventConfig); + return new EventEmitterAccessor(parsedEvent.eventName, reflection_1.reflector.getter(parsedEvent.fieldName)); + }); + } + function _createProtoQueryRefs(providers) { + var res = []; + collection_1.ListWrapper.forEachWithIndex(providers, function(b, i) { + if (b.provider instanceof DirectiveProvider) { + var directiveProvider = b.provider; + var queries = directiveProvider.queries; + queries.forEach(function(q) { + return res.push(new ProtoQueryRef(i, q.setter, q.metadata)); + }); + var deps = directiveProvider.resolvedFactory.dependencies; + deps.forEach(function(d) { + if (lang_1.isPresent(d.queryDecorator)) + res.push(new ProtoQueryRef(i, null, d.queryDecorator)); + }); + } + }); + return res; + } + var ProtoElementInjector = (function() { + function ProtoElementInjector(parent, index, bwv, distanceToParent, _firstProviderIsComponent, directiveVariableBindings) { + this.parent = parent; + this.index = index; + this.distanceToParent = distanceToParent; + this.directiveVariableBindings = directiveVariableBindings; + this._firstProviderIsComponent = _firstProviderIsComponent; + var length = bwv.length; + this.protoInjector = new injector_1.ProtoInjector(bwv); + this.eventEmitterAccessors = collection_1.ListWrapper.createFixedSize(length); + for (var i = 0; i < length; ++i) { + this.eventEmitterAccessors[i] = _createEventEmitterAccessors(bwv[i]); + } + this.protoQueryRefs = _createProtoQueryRefs(bwv); + } + ProtoElementInjector.create = function(parent, index, providers, firstProviderIsComponent, distanceToParent, directiveVariableBindings) { + var bd = []; + ProtoElementInjector._createDirectiveProviderWithVisibility(providers, bd, firstProviderIsComponent); + if (firstProviderIsComponent) { + ProtoElementInjector._createViewProvidersWithVisibility(providers, bd); + } + ProtoElementInjector._createProvidersWithVisibility(providers, bd); + return new ProtoElementInjector(parent, index, bd, distanceToParent, firstProviderIsComponent, directiveVariableBindings); + }; + ProtoElementInjector._createDirectiveProviderWithVisibility = function(dirProviders, bd, firstProviderIsComponent) { + dirProviders.forEach(function(dirProvider) { + bd.push(ProtoElementInjector._createProviderWithVisibility(firstProviderIsComponent, dirProvider, dirProviders, dirProvider)); + }); + }; + ProtoElementInjector._createProvidersWithVisibility = function(dirProviders, bd) { + var providersFromAllDirectives = []; + dirProviders.forEach(function(dirProvider) { + providersFromAllDirectives = collection_1.ListWrapper.concat(providersFromAllDirectives, dirProvider.providers); + }); + var resolved = di_1.Injector.resolve(providersFromAllDirectives); + resolved.forEach(function(b) { + return bd.push(new injector_1.ProviderWithVisibility(b, injector_1.Visibility.Public)); + }); + }; + ProtoElementInjector._createProviderWithVisibility = function(firstProviderIsComponent, dirProvider, dirProviders, provider) { + var isComponent = firstProviderIsComponent && dirProviders[0] === dirProvider; + return new injector_1.ProviderWithVisibility(provider, isComponent ? injector_1.Visibility.PublicAndPrivate : injector_1.Visibility.Public); + }; + ProtoElementInjector._createViewProvidersWithVisibility = function(dirProviders, bd) { + var resolvedViewProviders = di_1.Injector.resolve(dirProviders[0].viewProviders); + resolvedViewProviders.forEach(function(b) { + return bd.push(new injector_1.ProviderWithVisibility(b, injector_1.Visibility.Private)); + }); + }; + ProtoElementInjector.prototype.instantiate = function(parent) { + return new ElementInjector(this, parent); + }; + ProtoElementInjector.prototype.directParent = function() { + return this.distanceToParent < 2 ? this.parent : null; + }; + Object.defineProperty(ProtoElementInjector.prototype, "hasBindings", { + get: function() { + return this.eventEmitterAccessors.length > 0; + }, + enumerable: true, + configurable: true + }); + ProtoElementInjector.prototype.getProviderAtIndex = function(index) { + return this.protoInjector.getProviderAtIndex(index); + }; + return ProtoElementInjector; + })(); + exports.ProtoElementInjector = ProtoElementInjector; + var _Context = (function() { + function _Context(element, componentElement, injector) { + this.element = element; + this.componentElement = componentElement; + this.injector = injector; + } + return _Context; + })(); + var ElementInjector = (function(_super) { + __extends(ElementInjector, _super); + function ElementInjector(_proto, parent) { + var _this = this; + _super.call(this, parent); + this._preBuiltObjects = null; + this._proto = _proto; + this._injector = new di_1.Injector(this._proto.protoInjector, null, this, function() { + return _this._debugContext(); + }); + var injectorStrategy = this._injector.internalStrategy; + this._strategy = injectorStrategy instanceof injector_1.InjectorInlineStrategy ? new ElementInjectorInlineStrategy(injectorStrategy, this) : new ElementInjectorDynamicStrategy(injectorStrategy, this); + this.hydrated = false; + this._queryStrategy = this._buildQueryStrategy(); + } + ElementInjector.prototype.dehydrate = function() { + this.hydrated = false; + this._host = null; + this._preBuiltObjects = null; + this._strategy.callOnDestroy(); + this._strategy.dehydrate(); + this._queryStrategy.dehydrate(); + }; + ElementInjector.prototype.hydrate = function(imperativelyCreatedInjector, host, preBuiltObjects) { + this._host = host; + this._preBuiltObjects = preBuiltObjects; + this._reattachInjectors(imperativelyCreatedInjector); + this._queryStrategy.hydrate(); + this._strategy.hydrate(); + this.hydrated = true; + }; + ElementInjector.prototype._debugContext = function() { + var p = this._preBuiltObjects; + var index = p.elementRef.boundElementIndex - p.view.elementOffset; + var c = this._preBuiltObjects.view.getDebugContext(index, null); + return lang_1.isPresent(c) ? new _Context(c.element, c.componentElement, c.injector) : null; + }; + ElementInjector.prototype._reattachInjectors = function(imperativelyCreatedInjector) { + if (lang_1.isPresent(this._parent)) { + if (lang_1.isPresent(imperativelyCreatedInjector)) { + this._reattachInjector(this._injector, imperativelyCreatedInjector, false); + this._reattachInjector(imperativelyCreatedInjector, this._parent._injector, false); + } else { + this._reattachInjector(this._injector, this._parent._injector, false); + } + } else if (lang_1.isPresent(this._host)) { + if (lang_1.isPresent(imperativelyCreatedInjector)) { + this._reattachInjector(this._injector, imperativelyCreatedInjector, false); + this._reattachInjector(imperativelyCreatedInjector, this._host._injector, true); + } else { + this._reattachInjector(this._injector, this._host._injector, true); + } + } else { + if (lang_1.isPresent(imperativelyCreatedInjector)) { + this._reattachInjector(this._injector, imperativelyCreatedInjector, true); + } + } + }; + ElementInjector.prototype._reattachInjector = function(injector, parentInjector, isBoundary) { + injector.internalStrategy.attach(parentInjector, isBoundary); + }; + ElementInjector.prototype.hasVariableBinding = function(name) { + var vb = this._proto.directiveVariableBindings; + return lang_1.isPresent(vb) && vb.has(name); + }; + ElementInjector.prototype.getVariableBinding = function(name) { + var index = this._proto.directiveVariableBindings.get(name); + return lang_1.isPresent(index) ? this.getDirectiveAtIndex(index) : this.getElementRef(); + }; + ElementInjector.prototype.get = function(token) { + return this._injector.get(token); + }; + ElementInjector.prototype.hasDirective = function(type) { + return lang_1.isPresent(this._injector.getOptional(type)); + }; + ElementInjector.prototype.getEventEmitterAccessors = function() { + return this._proto.eventEmitterAccessors; + }; + ElementInjector.prototype.getDirectiveVariableBindings = function() { + return this._proto.directiveVariableBindings; + }; + ElementInjector.prototype.getComponent = function() { + return this._strategy.getComponent(); + }; + ElementInjector.prototype.getInjector = function() { + return this._injector; + }; + ElementInjector.prototype.getElementRef = function() { + return this._preBuiltObjects.elementRef; + }; + ElementInjector.prototype.getViewContainerRef = function() { + return new view_container_ref_2.ViewContainerRef_(this._preBuiltObjects.viewManager, this.getElementRef()); + }; + ElementInjector.prototype.getNestedView = function() { + return this._preBuiltObjects.nestedView; + }; + ElementInjector.prototype.getView = function() { + return this._preBuiltObjects.view; + }; + ElementInjector.prototype.directParent = function() { + return this._proto.distanceToParent < 2 ? this.parent : null; + }; + ElementInjector.prototype.isComponentKey = function(key) { + return this._strategy.isComponentKey(key); + }; + ElementInjector.prototype.getDependency = function(injector, provider, dep) { + var key = dep.key; + if (provider instanceof DirectiveProvider) { + var dirDep = dep; + var dirProvider = provider; + var staticKeys = StaticKeys.instance(); + if (key.id === staticKeys.viewManagerId) + return this._preBuiltObjects.viewManager; + if (lang_1.isPresent(dirDep.attributeName)) + return this._buildAttribute(dirDep); + if (lang_1.isPresent(dirDep.queryDecorator)) + return this._queryStrategy.findQuery(dirDep.queryDecorator).list; + if (dirDep.key.id === StaticKeys.instance().changeDetectorRefId) { + if (dirProvider.metadata instanceof directives_1.ComponentMetadata) { + var componentView = this._preBuiltObjects.view.getNestedView(this._preBuiltObjects.elementRef.boundElementIndex); + return componentView.changeDetector.ref; + } else { + return this._preBuiltObjects.view.changeDetector.ref; + } + } + if (dirDep.key.id === StaticKeys.instance().elementRefId) { + return this.getElementRef(); + } + if (dirDep.key.id === StaticKeys.instance().viewContainerId) { + return this.getViewContainerRef(); + } + if (dirDep.key.id === StaticKeys.instance().templateRefId) { + if (lang_1.isBlank(this._preBuiltObjects.templateRef)) { + if (dirDep.optional) { + return null; + } + throw new di_1.NoProviderError(null, dirDep.key); + } + return this._preBuiltObjects.templateRef; + } + } else if (provider instanceof pipe_provider_1.PipeProvider) { + if (dep.key.id === StaticKeys.instance().changeDetectorRefId) { + var componentView = this._preBuiltObjects.view.getNestedView(this._preBuiltObjects.elementRef.boundElementIndex); + return componentView.changeDetector.ref; + } + } + return injector_1.UNDEFINED; + }; + ElementInjector.prototype._buildAttribute = function(dep) { + var attributes = this._proto.attributes; + if (lang_1.isPresent(attributes) && attributes.has(dep.attributeName)) { + return attributes.get(dep.attributeName); + } else { + return null; + } + }; + ElementInjector.prototype.addDirectivesMatchingQuery = function(query, list) { + var templateRef = lang_1.isBlank(this._preBuiltObjects) ? null : this._preBuiltObjects.templateRef; + if (query.selector === template_ref_1.TemplateRef && lang_1.isPresent(templateRef)) { + list.push(templateRef); + } + this._strategy.addDirectivesMatchingQuery(query, list); + }; + ElementInjector.prototype._buildQueryStrategy = function() { + if (this._proto.protoQueryRefs.length === 0) { + return _emptyQueryStrategy; + } else if (this._proto.protoQueryRefs.length <= InlineQueryStrategy.NUMBER_OF_SUPPORTED_QUERIES) { + return new InlineQueryStrategy(this); + } else { + return new DynamicQueryStrategy(this); + } + }; + ElementInjector.prototype.link = function(parent) { + parent.addChild(this); + }; + ElementInjector.prototype.unlink = function() { + this.remove(); + }; + ElementInjector.prototype.getDirectiveAtIndex = function(index) { + return this._injector.getAt(index); + }; + ElementInjector.prototype.hasInstances = function() { + return this._proto.hasBindings && this.hydrated; + }; + ElementInjector.prototype.getHost = function() { + return this._host; + }; + ElementInjector.prototype.getBoundElementIndex = function() { + return this._proto.index; + }; + ElementInjector.prototype.getRootViewInjectors = function() { + if (!this.hydrated) + return []; + var view = this._preBuiltObjects.view; + var nestedView = view.getNestedView(view.elementOffset + this.getBoundElementIndex()); + return lang_1.isPresent(nestedView) ? nestedView.rootElementInjectors : []; + }; + ElementInjector.prototype.ngAfterViewChecked = function() { + this._queryStrategy.updateViewQueries(); + }; + ElementInjector.prototype.ngAfterContentChecked = function() { + this._queryStrategy.updateContentQueries(); + }; + ElementInjector.prototype.traverseAndSetQueriesAsDirty = function() { + var inj = this; + while (lang_1.isPresent(inj)) { + inj._setQueriesAsDirty(); + inj = inj.parent; + } + }; + ElementInjector.prototype._setQueriesAsDirty = function() { + this._queryStrategy.setContentQueriesAsDirty(); + if (lang_1.isPresent(this._host)) + this._host._queryStrategy.setViewQueriesAsDirty(); + }; + return ElementInjector; + })(TreeNode); + exports.ElementInjector = ElementInjector; + var _EmptyQueryStrategy = (function() { + function _EmptyQueryStrategy() {} + _EmptyQueryStrategy.prototype.setContentQueriesAsDirty = function() {}; + _EmptyQueryStrategy.prototype.setViewQueriesAsDirty = function() {}; + _EmptyQueryStrategy.prototype.hydrate = function() {}; + _EmptyQueryStrategy.prototype.dehydrate = function() {}; + _EmptyQueryStrategy.prototype.updateContentQueries = function() {}; + _EmptyQueryStrategy.prototype.updateViewQueries = function() {}; + _EmptyQueryStrategy.prototype.findQuery = function(query) { + throw new exceptions_1.BaseException("Cannot find query for directive " + query + "."); + }; + return _EmptyQueryStrategy; + })(); + var _emptyQueryStrategy = new _EmptyQueryStrategy(); + var InlineQueryStrategy = (function() { + function InlineQueryStrategy(ei) { + var protoRefs = ei._proto.protoQueryRefs; + if (protoRefs.length > 0) + this.query0 = new QueryRef(protoRefs[0], ei); + if (protoRefs.length > 1) + this.query1 = new QueryRef(protoRefs[1], ei); + if (protoRefs.length > 2) + this.query2 = new QueryRef(protoRefs[2], ei); + } + InlineQueryStrategy.prototype.setContentQueriesAsDirty = function() { + if (lang_1.isPresent(this.query0) && !this.query0.isViewQuery) + this.query0.dirty = true; + if (lang_1.isPresent(this.query1) && !this.query1.isViewQuery) + this.query1.dirty = true; + if (lang_1.isPresent(this.query2) && !this.query2.isViewQuery) + this.query2.dirty = true; + }; + InlineQueryStrategy.prototype.setViewQueriesAsDirty = function() { + if (lang_1.isPresent(this.query0) && this.query0.isViewQuery) + this.query0.dirty = true; + if (lang_1.isPresent(this.query1) && this.query1.isViewQuery) + this.query1.dirty = true; + if (lang_1.isPresent(this.query2) && this.query2.isViewQuery) + this.query2.dirty = true; + }; + InlineQueryStrategy.prototype.hydrate = function() { + if (lang_1.isPresent(this.query0)) + this.query0.hydrate(); + if (lang_1.isPresent(this.query1)) + this.query1.hydrate(); + if (lang_1.isPresent(this.query2)) + this.query2.hydrate(); + }; + InlineQueryStrategy.prototype.dehydrate = function() { + if (lang_1.isPresent(this.query0)) + this.query0.dehydrate(); + if (lang_1.isPresent(this.query1)) + this.query1.dehydrate(); + if (lang_1.isPresent(this.query2)) + this.query2.dehydrate(); + }; + InlineQueryStrategy.prototype.updateContentQueries = function() { + if (lang_1.isPresent(this.query0) && !this.query0.isViewQuery) { + this.query0.update(); + } + if (lang_1.isPresent(this.query1) && !this.query1.isViewQuery) { + this.query1.update(); + } + if (lang_1.isPresent(this.query2) && !this.query2.isViewQuery) { + this.query2.update(); + } + }; + InlineQueryStrategy.prototype.updateViewQueries = function() { + if (lang_1.isPresent(this.query0) && this.query0.isViewQuery) { + this.query0.update(); + } + if (lang_1.isPresent(this.query1) && this.query1.isViewQuery) { + this.query1.update(); + } + if (lang_1.isPresent(this.query2) && this.query2.isViewQuery) { + this.query2.update(); + } + }; + InlineQueryStrategy.prototype.findQuery = function(query) { + if (lang_1.isPresent(this.query0) && this.query0.protoQueryRef.query === query) { + return this.query0; + } + if (lang_1.isPresent(this.query1) && this.query1.protoQueryRef.query === query) { + return this.query1; + } + if (lang_1.isPresent(this.query2) && this.query2.protoQueryRef.query === query) { + return this.query2; + } + throw new exceptions_1.BaseException("Cannot find query for directive " + query + "."); + }; + InlineQueryStrategy.NUMBER_OF_SUPPORTED_QUERIES = 3; + return InlineQueryStrategy; + })(); + var DynamicQueryStrategy = (function() { + function DynamicQueryStrategy(ei) { + this.queries = ei._proto.protoQueryRefs.map(function(p) { + return new QueryRef(p, ei); + }); + } + DynamicQueryStrategy.prototype.setContentQueriesAsDirty = function() { + for (var i = 0; i < this.queries.length; ++i) { + var q = this.queries[i]; + if (!q.isViewQuery) + q.dirty = true; + } + }; + DynamicQueryStrategy.prototype.setViewQueriesAsDirty = function() { + for (var i = 0; i < this.queries.length; ++i) { + var q = this.queries[i]; + if (q.isViewQuery) + q.dirty = true; + } + }; + DynamicQueryStrategy.prototype.hydrate = function() { + for (var i = 0; i < this.queries.length; ++i) { + var q = this.queries[i]; + q.hydrate(); + } + }; + DynamicQueryStrategy.prototype.dehydrate = function() { + for (var i = 0; i < this.queries.length; ++i) { + var q = this.queries[i]; + q.dehydrate(); + } + }; + DynamicQueryStrategy.prototype.updateContentQueries = function() { + for (var i = 0; i < this.queries.length; ++i) { + var q = this.queries[i]; + if (!q.isViewQuery) { + q.update(); + } + } + }; + DynamicQueryStrategy.prototype.updateViewQueries = function() { + for (var i = 0; i < this.queries.length; ++i) { + var q = this.queries[i]; + if (q.isViewQuery) { + q.update(); + } + } + }; + DynamicQueryStrategy.prototype.findQuery = function(query) { + for (var i = 0; i < this.queries.length; ++i) { + var q = this.queries[i]; + if (q.protoQueryRef.query === query) { + return q; + } + } + throw new exceptions_1.BaseException("Cannot find query for directive " + query + "."); + }; + return DynamicQueryStrategy; + })(); + var ElementInjectorInlineStrategy = (function() { + function ElementInjectorInlineStrategy(injectorStrategy, _ei) { + this.injectorStrategy = injectorStrategy; + this._ei = _ei; + } + ElementInjectorInlineStrategy.prototype.hydrate = function() { + var i = this.injectorStrategy; + var p = i.protoStrategy; + i.resetConstructionCounter(); + if (p.provider0 instanceof DirectiveProvider && lang_1.isPresent(p.keyId0) && i.obj0 === injector_1.UNDEFINED) + i.obj0 = i.instantiateProvider(p.provider0, p.visibility0); + if (p.provider1 instanceof DirectiveProvider && lang_1.isPresent(p.keyId1) && i.obj1 === injector_1.UNDEFINED) + i.obj1 = i.instantiateProvider(p.provider1, p.visibility1); + if (p.provider2 instanceof DirectiveProvider && lang_1.isPresent(p.keyId2) && i.obj2 === injector_1.UNDEFINED) + i.obj2 = i.instantiateProvider(p.provider2, p.visibility2); + if (p.provider3 instanceof DirectiveProvider && lang_1.isPresent(p.keyId3) && i.obj3 === injector_1.UNDEFINED) + i.obj3 = i.instantiateProvider(p.provider3, p.visibility3); + if (p.provider4 instanceof DirectiveProvider && lang_1.isPresent(p.keyId4) && i.obj4 === injector_1.UNDEFINED) + i.obj4 = i.instantiateProvider(p.provider4, p.visibility4); + if (p.provider5 instanceof DirectiveProvider && lang_1.isPresent(p.keyId5) && i.obj5 === injector_1.UNDEFINED) + i.obj5 = i.instantiateProvider(p.provider5, p.visibility5); + if (p.provider6 instanceof DirectiveProvider && lang_1.isPresent(p.keyId6) && i.obj6 === injector_1.UNDEFINED) + i.obj6 = i.instantiateProvider(p.provider6, p.visibility6); + if (p.provider7 instanceof DirectiveProvider && lang_1.isPresent(p.keyId7) && i.obj7 === injector_1.UNDEFINED) + i.obj7 = i.instantiateProvider(p.provider7, p.visibility7); + if (p.provider8 instanceof DirectiveProvider && lang_1.isPresent(p.keyId8) && i.obj8 === injector_1.UNDEFINED) + i.obj8 = i.instantiateProvider(p.provider8, p.visibility8); + if (p.provider9 instanceof DirectiveProvider && lang_1.isPresent(p.keyId9) && i.obj9 === injector_1.UNDEFINED) + i.obj9 = i.instantiateProvider(p.provider9, p.visibility9); + }; + ElementInjectorInlineStrategy.prototype.dehydrate = function() { + var i = this.injectorStrategy; + i.obj0 = injector_1.UNDEFINED; + i.obj1 = injector_1.UNDEFINED; + i.obj2 = injector_1.UNDEFINED; + i.obj3 = injector_1.UNDEFINED; + i.obj4 = injector_1.UNDEFINED; + i.obj5 = injector_1.UNDEFINED; + i.obj6 = injector_1.UNDEFINED; + i.obj7 = injector_1.UNDEFINED; + i.obj8 = injector_1.UNDEFINED; + i.obj9 = injector_1.UNDEFINED; + }; + ElementInjectorInlineStrategy.prototype.callOnDestroy = function() { + var i = this.injectorStrategy; + var p = i.protoStrategy; + if (p.provider0 instanceof DirectiveProvider && p.provider0.callOnDestroy) { + i.obj0.ngOnDestroy(); + } + if (p.provider1 instanceof DirectiveProvider && p.provider1.callOnDestroy) { + i.obj1.ngOnDestroy(); + } + if (p.provider2 instanceof DirectiveProvider && p.provider2.callOnDestroy) { + i.obj2.ngOnDestroy(); + } + if (p.provider3 instanceof DirectiveProvider && p.provider3.callOnDestroy) { + i.obj3.ngOnDestroy(); + } + if (p.provider4 instanceof DirectiveProvider && p.provider4.callOnDestroy) { + i.obj4.ngOnDestroy(); + } + if (p.provider5 instanceof DirectiveProvider && p.provider5.callOnDestroy) { + i.obj5.ngOnDestroy(); + } + if (p.provider6 instanceof DirectiveProvider && p.provider6.callOnDestroy) { + i.obj6.ngOnDestroy(); + } + if (p.provider7 instanceof DirectiveProvider && p.provider7.callOnDestroy) { + i.obj7.ngOnDestroy(); + } + if (p.provider8 instanceof DirectiveProvider && p.provider8.callOnDestroy) { + i.obj8.ngOnDestroy(); + } + if (p.provider9 instanceof DirectiveProvider && p.provider9.callOnDestroy) { + i.obj9.ngOnDestroy(); + } + }; + ElementInjectorInlineStrategy.prototype.getComponent = function() { + return this.injectorStrategy.obj0; + }; + ElementInjectorInlineStrategy.prototype.isComponentKey = function(key) { + return this._ei._proto._firstProviderIsComponent && lang_1.isPresent(key) && key.id === this.injectorStrategy.protoStrategy.keyId0; + }; + ElementInjectorInlineStrategy.prototype.addDirectivesMatchingQuery = function(query, list) { + var i = this.injectorStrategy; + var p = i.protoStrategy; + if (lang_1.isPresent(p.provider0) && p.provider0.key.token === query.selector) { + if (i.obj0 === injector_1.UNDEFINED) + i.obj0 = i.instantiateProvider(p.provider0, p.visibility0); + list.push(i.obj0); + } + if (lang_1.isPresent(p.provider1) && p.provider1.key.token === query.selector) { + if (i.obj1 === injector_1.UNDEFINED) + i.obj1 = i.instantiateProvider(p.provider1, p.visibility1); + list.push(i.obj1); + } + if (lang_1.isPresent(p.provider2) && p.provider2.key.token === query.selector) { + if (i.obj2 === injector_1.UNDEFINED) + i.obj2 = i.instantiateProvider(p.provider2, p.visibility2); + list.push(i.obj2); + } + if (lang_1.isPresent(p.provider3) && p.provider3.key.token === query.selector) { + if (i.obj3 === injector_1.UNDEFINED) + i.obj3 = i.instantiateProvider(p.provider3, p.visibility3); + list.push(i.obj3); + } + if (lang_1.isPresent(p.provider4) && p.provider4.key.token === query.selector) { + if (i.obj4 === injector_1.UNDEFINED) + i.obj4 = i.instantiateProvider(p.provider4, p.visibility4); + list.push(i.obj4); + } + if (lang_1.isPresent(p.provider5) && p.provider5.key.token === query.selector) { + if (i.obj5 === injector_1.UNDEFINED) + i.obj5 = i.instantiateProvider(p.provider5, p.visibility5); + list.push(i.obj5); + } + if (lang_1.isPresent(p.provider6) && p.provider6.key.token === query.selector) { + if (i.obj6 === injector_1.UNDEFINED) + i.obj6 = i.instantiateProvider(p.provider6, p.visibility6); + list.push(i.obj6); + } + if (lang_1.isPresent(p.provider7) && p.provider7.key.token === query.selector) { + if (i.obj7 === injector_1.UNDEFINED) + i.obj7 = i.instantiateProvider(p.provider7, p.visibility7); + list.push(i.obj7); + } + if (lang_1.isPresent(p.provider8) && p.provider8.key.token === query.selector) { + if (i.obj8 === injector_1.UNDEFINED) + i.obj8 = i.instantiateProvider(p.provider8, p.visibility8); + list.push(i.obj8); + } + if (lang_1.isPresent(p.provider9) && p.provider9.key.token === query.selector) { + if (i.obj9 === injector_1.UNDEFINED) + i.obj9 = i.instantiateProvider(p.provider9, p.visibility9); + list.push(i.obj9); + } + }; + return ElementInjectorInlineStrategy; + })(); + var ElementInjectorDynamicStrategy = (function() { + function ElementInjectorDynamicStrategy(injectorStrategy, _ei) { + this.injectorStrategy = injectorStrategy; + this._ei = _ei; + } + ElementInjectorDynamicStrategy.prototype.hydrate = function() { + var inj = this.injectorStrategy; + var p = inj.protoStrategy; + inj.resetConstructionCounter(); + for (var i = 0; i < p.keyIds.length; i++) { + if (p.providers[i] instanceof DirectiveProvider && lang_1.isPresent(p.keyIds[i]) && inj.objs[i] === injector_1.UNDEFINED) { + inj.objs[i] = inj.instantiateProvider(p.providers[i], p.visibilities[i]); + } + } + }; + ElementInjectorDynamicStrategy.prototype.dehydrate = function() { + var inj = this.injectorStrategy; + collection_1.ListWrapper.fill(inj.objs, injector_1.UNDEFINED); + }; + ElementInjectorDynamicStrategy.prototype.callOnDestroy = function() { + var ist = this.injectorStrategy; + var p = ist.protoStrategy; + for (var i = 0; i < p.providers.length; i++) { + if (p.providers[i] instanceof DirectiveProvider && p.providers[i].callOnDestroy) { + ist.objs[i].ngOnDestroy(); + } + } + }; + ElementInjectorDynamicStrategy.prototype.getComponent = function() { + return this.injectorStrategy.objs[0]; + }; + ElementInjectorDynamicStrategy.prototype.isComponentKey = function(key) { + var p = this.injectorStrategy.protoStrategy; + return this._ei._proto._firstProviderIsComponent && lang_1.isPresent(key) && key.id === p.keyIds[0]; + }; + ElementInjectorDynamicStrategy.prototype.addDirectivesMatchingQuery = function(query, list) { + var ist = this.injectorStrategy; + var p = ist.protoStrategy; + for (var i = 0; i < p.providers.length; i++) { + if (p.providers[i].key.token === query.selector) { + if (ist.objs[i] === injector_1.UNDEFINED) { + ist.objs[i] = ist.instantiateProvider(p.providers[i], p.visibilities[i]); + } + list.push(ist.objs[i]); + } + } + }; + return ElementInjectorDynamicStrategy; + })(); + var ProtoQueryRef = (function() { + function ProtoQueryRef(dirIndex, setter, query) { + this.dirIndex = dirIndex; + this.setter = setter; + this.query = query; + } + Object.defineProperty(ProtoQueryRef.prototype, "usesPropertySyntax", { + get: function() { + return lang_1.isPresent(this.setter); + }, + enumerable: true, + configurable: true + }); + return ProtoQueryRef; + })(); + exports.ProtoQueryRef = ProtoQueryRef; + var QueryRef = (function() { + function QueryRef(protoQueryRef, originator) { + this.protoQueryRef = protoQueryRef; + this.originator = originator; + } + Object.defineProperty(QueryRef.prototype, "isViewQuery", { + get: function() { + return this.protoQueryRef.query.isViewQuery; + }, + enumerable: true, + configurable: true + }); + QueryRef.prototype.update = function() { + if (!this.dirty) + return ; + this._update(); + this.dirty = false; + if (this.protoQueryRef.usesPropertySyntax) { + var dir = this.originator.getDirectiveAtIndex(this.protoQueryRef.dirIndex); + if (this.protoQueryRef.query.first) { + this.protoQueryRef.setter(dir, this.list.length > 0 ? this.list.first : null); + } else { + this.protoQueryRef.setter(dir, this.list); + } + } + this.list.notifyOnChanges(); + }; + QueryRef.prototype._update = function() { + var aggregator = []; + if (this.protoQueryRef.query.isViewQuery) { + var view = this.originator.getView(); + var nestedView = view.getNestedView(view.elementOffset + this.originator.getBoundElementIndex()); + if (lang_1.isPresent(nestedView)) + this._visitView(nestedView, aggregator); + } else { + this._visit(this.originator, aggregator); + } + this.list.reset(aggregator); + }; + ; + QueryRef.prototype._visit = function(inj, aggregator) { + var view = inj.getView(); + var startIdx = view.elementOffset + inj._proto.index; + for (var i = startIdx; i < view.elementOffset + view.ownBindersCount; i++) { + var curInj = view.elementInjectors[i]; + if (lang_1.isBlank(curInj)) + continue; + if (i > startIdx && (lang_1.isBlank(curInj) || lang_1.isBlank(curInj.parent) || view.elementOffset + curInj.parent._proto.index < startIdx)) { + break; + } + if (!this.protoQueryRef.query.descendants && !(curInj.parent == this.originator || curInj == this.originator)) + continue; + this._visitInjector(curInj, aggregator); + var vc = view.viewContainers[i]; + if (lang_1.isPresent(vc)) + this._visitViewContainer(vc, aggregator); + } + }; + QueryRef.prototype._visitInjector = function(inj, aggregator) { + if (this.protoQueryRef.query.isVarBindingQuery) { + this._aggregateVariableBinding(inj, aggregator); + } else { + this._aggregateDirective(inj, aggregator); + } + }; + QueryRef.prototype._visitViewContainer = function(vc, aggregator) { + for (var j = 0; j < vc.views.length; j++) { + this._visitView(vc.views[j], aggregator); + } + }; + QueryRef.prototype._visitView = function(view, aggregator) { + for (var i = view.elementOffset; i < view.elementOffset + view.ownBindersCount; i++) { + var inj = view.elementInjectors[i]; + if (lang_1.isBlank(inj)) + continue; + this._visitInjector(inj, aggregator); + var vc = view.viewContainers[i]; + if (lang_1.isPresent(vc)) + this._visitViewContainer(vc, aggregator); + } + }; + QueryRef.prototype._aggregateVariableBinding = function(inj, aggregator) { + var vb = this.protoQueryRef.query.varBindings; + for (var i = 0; i < vb.length; ++i) { + if (inj.hasVariableBinding(vb[i])) { + aggregator.push(inj.getVariableBinding(vb[i])); + } + } + }; + QueryRef.prototype._aggregateDirective = function(inj, aggregator) { + inj.addDirectivesMatchingQuery(this.protoQueryRef.query, aggregator); + }; + QueryRef.prototype.dehydrate = function() { + this.list = null; + }; + QueryRef.prototype.hydrate = function() { + this.list = new query_list_1.QueryList(); + this.dirty = true; + }; + return QueryRef; + })(); + exports.QueryRef = QueryRef; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/di", ["angular2/src/core/di/metadata", "angular2/src/core/di/decorators", "angular2/src/core/di/forward_ref", "angular2/src/core/di/injector", "angular2/src/core/di/provider", "angular2/src/core/di/key", "angular2/src/core/di/exceptions", "angular2/src/core/di/opaque_token"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function __export(m) { + for (var p in m) + if (!exports.hasOwnProperty(p)) + exports[p] = m[p]; + } + var metadata_1 = require("angular2/src/core/di/metadata"); + exports.InjectMetadata = metadata_1.InjectMetadata; + exports.OptionalMetadata = metadata_1.OptionalMetadata; + exports.InjectableMetadata = metadata_1.InjectableMetadata; + exports.SelfMetadata = metadata_1.SelfMetadata; + exports.HostMetadata = metadata_1.HostMetadata; + exports.SkipSelfMetadata = metadata_1.SkipSelfMetadata; + exports.DependencyMetadata = metadata_1.DependencyMetadata; + __export(require("angular2/src/core/di/decorators")); + var forward_ref_1 = require("angular2/src/core/di/forward_ref"); + exports.forwardRef = forward_ref_1.forwardRef; + exports.resolveForwardRef = forward_ref_1.resolveForwardRef; + var injector_1 = require("angular2/src/core/di/injector"); + exports.Injector = injector_1.Injector; + var provider_1 = require("angular2/src/core/di/provider"); + exports.Binding = provider_1.Binding; + exports.ProviderBuilder = provider_1.ProviderBuilder; + exports.ResolvedFactory = provider_1.ResolvedFactory; + exports.Dependency = provider_1.Dependency; + exports.bind = provider_1.bind; + exports.Provider = provider_1.Provider; + exports.provide = provider_1.provide; + var key_1 = require("angular2/src/core/di/key"); + exports.Key = key_1.Key; + exports.TypeLiteral = key_1.TypeLiteral; + var exceptions_1 = require("angular2/src/core/di/exceptions"); + exports.NoProviderError = exceptions_1.NoProviderError; + exports.AbstractProviderError = exceptions_1.AbstractProviderError; + exports.CyclicDependencyError = exceptions_1.CyclicDependencyError; + exports.InstantiationError = exceptions_1.InstantiationError; + exports.InvalidProviderError = exceptions_1.InvalidProviderError; + exports.NoAnnotationError = exceptions_1.NoAnnotationError; + exports.OutOfBoundsError = exceptions_1.OutOfBoundsError; + var opaque_token_1 = require("angular2/src/core/di/opaque_token"); + exports.OpaqueToken = opaque_token_1.OpaqueToken; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection/change_detection", ["angular2/src/core/change_detection/differs/iterable_differs", "angular2/src/core/change_detection/differs/default_iterable_differ", "angular2/src/core/change_detection/differs/keyvalue_differs", "angular2/src/core/change_detection/differs/default_keyvalue_differ", "angular2/src/facade/lang", "angular2/src/core/change_detection/parser/ast", "angular2/src/core/change_detection/parser/lexer", "angular2/src/core/change_detection/parser/parser", "angular2/src/core/change_detection/parser/locals", "angular2/src/core/change_detection/exceptions", "angular2/src/core/change_detection/interfaces", "angular2/src/core/change_detection/constants", "angular2/src/core/change_detection/proto_change_detector", "angular2/src/core/change_detection/jit_proto_change_detector", "angular2/src/core/change_detection/binding_record", "angular2/src/core/change_detection/directive_record", "angular2/src/core/change_detection/dynamic_change_detector", "angular2/src/core/change_detection/change_detector_ref", "angular2/src/core/change_detection/differs/iterable_differs", "angular2/src/core/change_detection/differs/keyvalue_differs", "angular2/src/core/change_detection/change_detection_util"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var iterable_differs_1 = require("angular2/src/core/change_detection/differs/iterable_differs"); + var default_iterable_differ_1 = require("angular2/src/core/change_detection/differs/default_iterable_differ"); + var keyvalue_differs_1 = require("angular2/src/core/change_detection/differs/keyvalue_differs"); + var default_keyvalue_differ_1 = require("angular2/src/core/change_detection/differs/default_keyvalue_differ"); + var lang_1 = require("angular2/src/facade/lang"); + var ast_1 = require("angular2/src/core/change_detection/parser/ast"); + exports.ASTWithSource = ast_1.ASTWithSource; + exports.AST = ast_1.AST; + exports.AstTransformer = ast_1.AstTransformer; + exports.PropertyRead = ast_1.PropertyRead; + exports.LiteralArray = ast_1.LiteralArray; + exports.ImplicitReceiver = ast_1.ImplicitReceiver; + var lexer_1 = require("angular2/src/core/change_detection/parser/lexer"); + exports.Lexer = lexer_1.Lexer; + var parser_1 = require("angular2/src/core/change_detection/parser/parser"); + exports.Parser = parser_1.Parser; + var locals_1 = require("angular2/src/core/change_detection/parser/locals"); + exports.Locals = locals_1.Locals; + var exceptions_1 = require("angular2/src/core/change_detection/exceptions"); + exports.DehydratedException = exceptions_1.DehydratedException; + exports.ExpressionChangedAfterItHasBeenCheckedException = exceptions_1.ExpressionChangedAfterItHasBeenCheckedException; + exports.ChangeDetectionError = exceptions_1.ChangeDetectionError; + var interfaces_1 = require("angular2/src/core/change_detection/interfaces"); + exports.ChangeDetectorDefinition = interfaces_1.ChangeDetectorDefinition; + exports.DebugContext = interfaces_1.DebugContext; + exports.ChangeDetectorGenConfig = interfaces_1.ChangeDetectorGenConfig; + var constants_1 = require("angular2/src/core/change_detection/constants"); + exports.ChangeDetectionStrategy = constants_1.ChangeDetectionStrategy; + exports.CHANGE_DETECTION_STRATEGY_VALUES = constants_1.CHANGE_DETECTION_STRATEGY_VALUES; + var proto_change_detector_1 = require("angular2/src/core/change_detection/proto_change_detector"); + exports.DynamicProtoChangeDetector = proto_change_detector_1.DynamicProtoChangeDetector; + var jit_proto_change_detector_1 = require("angular2/src/core/change_detection/jit_proto_change_detector"); + exports.JitProtoChangeDetector = jit_proto_change_detector_1.JitProtoChangeDetector; + var binding_record_1 = require("angular2/src/core/change_detection/binding_record"); + exports.BindingRecord = binding_record_1.BindingRecord; + exports.BindingTarget = binding_record_1.BindingTarget; + var directive_record_1 = require("angular2/src/core/change_detection/directive_record"); + exports.DirectiveIndex = directive_record_1.DirectiveIndex; + exports.DirectiveRecord = directive_record_1.DirectiveRecord; + var dynamic_change_detector_1 = require("angular2/src/core/change_detection/dynamic_change_detector"); + exports.DynamicChangeDetector = dynamic_change_detector_1.DynamicChangeDetector; + var change_detector_ref_1 = require("angular2/src/core/change_detection/change_detector_ref"); + exports.ChangeDetectorRef = change_detector_ref_1.ChangeDetectorRef; + var iterable_differs_2 = require("angular2/src/core/change_detection/differs/iterable_differs"); + exports.IterableDiffers = iterable_differs_2.IterableDiffers; + var keyvalue_differs_2 = require("angular2/src/core/change_detection/differs/keyvalue_differs"); + exports.KeyValueDiffers = keyvalue_differs_2.KeyValueDiffers; + var change_detection_util_1 = require("angular2/src/core/change_detection/change_detection_util"); + exports.WrappedValue = change_detection_util_1.WrappedValue; + exports.SimpleChange = change_detection_util_1.SimpleChange; + exports.keyValDiff = lang_1.CONST_EXPR([lang_1.CONST_EXPR(new default_keyvalue_differ_1.DefaultKeyValueDifferFactory())]); + exports.iterableDiff = lang_1.CONST_EXPR([lang_1.CONST_EXPR(new default_iterable_differ_1.DefaultIterableDifferFactory())]); + exports.defaultIterableDiffers = lang_1.CONST_EXPR(new iterable_differs_1.IterableDiffers(exports.iterableDiff)); + exports.defaultKeyValueDiffers = lang_1.CONST_EXPR(new keyvalue_differs_1.KeyValueDiffers(exports.keyValDiff)); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/proto_view_factory", ["angular2/src/facade/lang", "angular2/src/core/render/api", "angular2/src/core/di", "angular2/src/core/pipes/pipe_provider", "angular2/src/core/pipes/pipes", "angular2/src/core/linker/view", "angular2/src/core/linker/element_binder", "angular2/src/core/linker/element_injector", "angular2/src/core/linker/directive_resolver", "angular2/src/core/linker/view_resolver", "angular2/src/core/linker/pipe_resolver", "angular2/src/core/metadata/view", "angular2/src/core/platform_directives_and_pipes", "angular2/src/core/linker/template_commands", "angular2/src/core/render/api", "angular2/src/core/application_tokens"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var lang_1 = require("angular2/src/facade/lang"); + var api_1 = require("angular2/src/core/render/api"); + var di_1 = require("angular2/src/core/di"); + var pipe_provider_1 = require("angular2/src/core/pipes/pipe_provider"); + var pipes_1 = require("angular2/src/core/pipes/pipes"); + var view_1 = require("angular2/src/core/linker/view"); + var element_binder_1 = require("angular2/src/core/linker/element_binder"); + var element_injector_1 = require("angular2/src/core/linker/element_injector"); + var directive_resolver_1 = require("angular2/src/core/linker/directive_resolver"); + var view_resolver_1 = require("angular2/src/core/linker/view_resolver"); + var pipe_resolver_1 = require("angular2/src/core/linker/pipe_resolver"); + var view_2 = require("angular2/src/core/metadata/view"); + var platform_directives_and_pipes_1 = require("angular2/src/core/platform_directives_and_pipes"); + var template_commands_1 = require("angular2/src/core/linker/template_commands"); + var api_2 = require("angular2/src/core/render/api"); + var application_tokens_1 = require("angular2/src/core/application_tokens"); + var ProtoViewFactory = (function() { + function ProtoViewFactory(_renderer, _platformPipes, _directiveResolver, _viewResolver, _pipeResolver, _appId) { + this._renderer = _renderer; + this._platformPipes = _platformPipes; + this._directiveResolver = _directiveResolver; + this._viewResolver = _viewResolver; + this._pipeResolver = _pipeResolver; + this._appId = _appId; + this._cache = new Map(); + this._nextTemplateId = 0; + } + ProtoViewFactory.prototype.clearCache = function() { + this._cache.clear(); + }; + ProtoViewFactory.prototype.createHost = function(compiledHostTemplate) { + var compiledTemplate = compiledHostTemplate.template; + var result = this._cache.get(compiledTemplate.id); + if (lang_1.isBlank(result)) { + var emptyMap = {}; + var shortId = this._appId + "-" + this._nextTemplateId++; + this._renderer.registerComponentTemplate(new api_1.RenderComponentTemplate(compiledTemplate.id, shortId, view_2.ViewEncapsulation.None, compiledTemplate.commands, [])); + result = new view_1.AppProtoView(compiledTemplate.id, compiledTemplate.commands, view_1.ViewType.HOST, true, compiledTemplate.changeDetectorFactory, null, new pipes_1.ProtoPipes(emptyMap)); + this._cache.set(compiledTemplate.id, result); + } + return result; + }; + ProtoViewFactory.prototype._createComponent = function(cmd) { + var _this = this; + var nestedProtoView = this._cache.get(cmd.templateId); + if (lang_1.isBlank(nestedProtoView)) { + var component = cmd.directives[0]; + var view = this._viewResolver.resolve(component); + var compiledTemplate = cmd.templateGetter(); + var styles = _flattenStyleArr(compiledTemplate.styles, []); + var shortId = this._appId + "-" + this._nextTemplateId++; + this._renderer.registerComponentTemplate(new api_1.RenderComponentTemplate(compiledTemplate.id, shortId, cmd.encapsulation, compiledTemplate.commands, styles)); + var boundPipes = this._flattenPipes(view).map(function(pipe) { + return _this._bindPipe(pipe); + }); + nestedProtoView = new view_1.AppProtoView(compiledTemplate.id, compiledTemplate.commands, view_1.ViewType.COMPONENT, true, compiledTemplate.changeDetectorFactory, null, pipes_1.ProtoPipes.fromProviders(boundPipes)); + this._cache.set(compiledTemplate.id, nestedProtoView); + this._initializeProtoView(nestedProtoView, null); + } + return nestedProtoView; + }; + ProtoViewFactory.prototype._createEmbeddedTemplate = function(cmd, parent) { + var nestedProtoView = new view_1.AppProtoView(parent.templateId, cmd.children, view_1.ViewType.EMBEDDED, cmd.isMerged, cmd.changeDetectorFactory, arrayToMap(cmd.variableNameAndValues, true), new pipes_1.ProtoPipes(parent.pipes.config)); + if (cmd.isMerged) { + this.initializeProtoViewIfNeeded(nestedProtoView); + } + return nestedProtoView; + }; + ProtoViewFactory.prototype.initializeProtoViewIfNeeded = function(protoView) { + if (!protoView.isInitialized()) { + var render = this._renderer.createProtoView(protoView.templateId, protoView.templateCmds); + this._initializeProtoView(protoView, render); + } + }; + ProtoViewFactory.prototype._initializeProtoView = function(protoView, render) { + var initializer = new _ProtoViewInitializer(protoView, this._directiveResolver, this); + template_commands_1.visitAllCommands(initializer, protoView.templateCmds); + var mergeInfo = new view_1.AppProtoViewMergeInfo(initializer.mergeEmbeddedViewCount, initializer.mergeElementCount, initializer.mergeViewCount); + protoView.init(render, initializer.elementBinders, initializer.boundTextCount, mergeInfo, initializer.variableLocations); + }; + ProtoViewFactory.prototype._bindPipe = function(typeOrProvider) { + var meta = this._pipeResolver.resolve(typeOrProvider); + return pipe_provider_1.PipeProvider.createFromType(typeOrProvider, meta); + }; + ProtoViewFactory.prototype._flattenPipes = function(view) { + var pipes = []; + if (lang_1.isPresent(this._platformPipes)) { + _flattenArray(this._platformPipes, pipes); + } + if (lang_1.isPresent(view.pipes)) { + _flattenArray(view.pipes, pipes); + } + return pipes; + }; + ProtoViewFactory = __decorate([di_1.Injectable(), __param(1, di_1.Optional()), __param(1, di_1.Inject(platform_directives_and_pipes_1.PLATFORM_PIPES)), __param(5, di_1.Inject(application_tokens_1.APP_ID)), __metadata('design:paramtypes', [api_2.Renderer, Array, directive_resolver_1.DirectiveResolver, view_resolver_1.ViewResolver, pipe_resolver_1.PipeResolver, String])], ProtoViewFactory); + return ProtoViewFactory; + })(); + exports.ProtoViewFactory = ProtoViewFactory; + function createComponent(protoViewFactory, cmd) { + return protoViewFactory._createComponent(cmd); + } + function createEmbeddedTemplate(protoViewFactory, cmd, parent) { + return protoViewFactory._createEmbeddedTemplate(cmd, parent); + } + var _ProtoViewInitializer = (function() { + function _ProtoViewInitializer(_protoView, _directiveResolver, _protoViewFactory) { + this._protoView = _protoView; + this._directiveResolver = _directiveResolver; + this._protoViewFactory = _protoViewFactory; + this.variableLocations = new Map(); + this.boundTextCount = 0; + this.boundElementIndex = 0; + this.elementBinderStack = []; + this.distanceToParentElementBinder = 0; + this.distanceToParentProtoElementInjector = 0; + this.elementBinders = []; + this.mergeEmbeddedViewCount = 0; + this.mergeElementCount = 0; + this.mergeViewCount = 1; + } + _ProtoViewInitializer.prototype.visitText = function(cmd, context) { + if (cmd.isBound) { + this.boundTextCount++; + } + return null; + }; + _ProtoViewInitializer.prototype.visitNgContent = function(cmd, context) { + return null; + }; + _ProtoViewInitializer.prototype.visitBeginElement = function(cmd, context) { + if (cmd.isBound) { + this._visitBeginBoundElement(cmd, null); + } else { + this._visitBeginElement(cmd, null, null); + } + return null; + }; + _ProtoViewInitializer.prototype.visitEndElement = function(context) { + return this._visitEndElement(); + }; + _ProtoViewInitializer.prototype.visitBeginComponent = function(cmd, context) { + var nestedProtoView = createComponent(this._protoViewFactory, cmd); + return this._visitBeginBoundElement(cmd, nestedProtoView); + }; + _ProtoViewInitializer.prototype.visitEndComponent = function(context) { + return this._visitEndElement(); + }; + _ProtoViewInitializer.prototype.visitEmbeddedTemplate = function(cmd, context) { + var nestedProtoView = createEmbeddedTemplate(this._protoViewFactory, cmd, this._protoView); + if (cmd.isMerged) { + this.mergeEmbeddedViewCount++; + } + this._visitBeginBoundElement(cmd, nestedProtoView); + return this._visitEndElement(); + }; + _ProtoViewInitializer.prototype._visitBeginBoundElement = function(cmd, nestedProtoView) { + if (lang_1.isPresent(nestedProtoView) && nestedProtoView.isMergable) { + this.mergeElementCount += nestedProtoView.mergeInfo.elementCount; + this.mergeViewCount += nestedProtoView.mergeInfo.viewCount; + this.mergeEmbeddedViewCount += nestedProtoView.mergeInfo.embeddedViewCount; + } + var elementBinder = _createElementBinder(this._directiveResolver, nestedProtoView, this.elementBinderStack, this.boundElementIndex, this.distanceToParentElementBinder, this.distanceToParentProtoElementInjector, cmd); + this.elementBinders.push(elementBinder); + var protoElementInjector = elementBinder.protoElementInjector; + for (var i = 0; i < cmd.variableNameAndValues.length; i += 2) { + this.variableLocations.set(cmd.variableNameAndValues[i], this.boundElementIndex); + } + this.boundElementIndex++; + this.mergeElementCount++; + return this._visitBeginElement(cmd, elementBinder, protoElementInjector); + }; + _ProtoViewInitializer.prototype._visitBeginElement = function(cmd, elementBinder, protoElementInjector) { + this.distanceToParentElementBinder = lang_1.isPresent(elementBinder) ? 1 : this.distanceToParentElementBinder + 1; + this.distanceToParentProtoElementInjector = lang_1.isPresent(protoElementInjector) ? 1 : this.distanceToParentProtoElementInjector + 1; + this.elementBinderStack.push(elementBinder); + return null; + }; + _ProtoViewInitializer.prototype._visitEndElement = function() { + var parentElementBinder = this.elementBinderStack.pop(); + var parentProtoElementInjector = lang_1.isPresent(parentElementBinder) ? parentElementBinder.protoElementInjector : null; + this.distanceToParentElementBinder = lang_1.isPresent(parentElementBinder) ? parentElementBinder.distanceToParent : this.distanceToParentElementBinder - 1; + this.distanceToParentProtoElementInjector = lang_1.isPresent(parentProtoElementInjector) ? parentProtoElementInjector.distanceToParent : this.distanceToParentProtoElementInjector - 1; + return null; + }; + return _ProtoViewInitializer; + })(); + function _createElementBinder(directiveResolver, nestedProtoView, elementBinderStack, boundElementIndex, distanceToParentBinder, distanceToParentPei, beginElementCmd) { + var parentElementBinder = null; + var parentProtoElementInjector = null; + if (distanceToParentBinder > 0) { + parentElementBinder = elementBinderStack[elementBinderStack.length - distanceToParentBinder]; + } + if (lang_1.isBlank(parentElementBinder)) { + distanceToParentBinder = -1; + } + if (distanceToParentPei > 0) { + var peiBinder = elementBinderStack[elementBinderStack.length - distanceToParentPei]; + if (lang_1.isPresent(peiBinder)) { + parentProtoElementInjector = peiBinder.protoElementInjector; + } + } + if (lang_1.isBlank(parentProtoElementInjector)) { + distanceToParentPei = -1; + } + var componentDirectiveProvider = null; + var isEmbeddedTemplate = false; + var directiveProviders = beginElementCmd.directives.map(function(type) { + return provideDirective(directiveResolver, type); + }); + if (beginElementCmd instanceof template_commands_1.BeginComponentCmd) { + componentDirectiveProvider = directiveProviders[0]; + } else if (beginElementCmd instanceof template_commands_1.EmbeddedTemplateCmd) { + isEmbeddedTemplate = true; + } + var protoElementInjector = null; + var hasVariables = beginElementCmd.variableNameAndValues.length > 0; + if (directiveProviders.length > 0 || hasVariables || isEmbeddedTemplate) { + var directiveVariableBindings = new Map(); + if (!isEmbeddedTemplate) { + directiveVariableBindings = createDirectiveVariableBindings(beginElementCmd.variableNameAndValues, directiveProviders); + } + protoElementInjector = element_injector_1.ProtoElementInjector.create(parentProtoElementInjector, boundElementIndex, directiveProviders, lang_1.isPresent(componentDirectiveProvider), distanceToParentPei, directiveVariableBindings); + protoElementInjector.attributes = arrayToMap(beginElementCmd.attrNameAndValues, false); + } + return new element_binder_1.ElementBinder(boundElementIndex, parentElementBinder, distanceToParentBinder, protoElementInjector, componentDirectiveProvider, nestedProtoView); + } + function provideDirective(directiveResolver, type) { + var annotation = directiveResolver.resolve(type); + return element_injector_1.DirectiveProvider.createFromType(type, annotation); + } + function createDirectiveVariableBindings(variableNameAndValues, directiveProviders) { + var directiveVariableBindings = new Map(); + for (var i = 0; i < variableNameAndValues.length; i += 2) { + var templateName = variableNameAndValues[i]; + var dirIndex = variableNameAndValues[i + 1]; + if (lang_1.isNumber(dirIndex)) { + directiveVariableBindings.set(templateName, dirIndex); + } else { + directiveVariableBindings.set(templateName, null); + } + } + return directiveVariableBindings; + } + exports.createDirectiveVariableBindings = createDirectiveVariableBindings; + function arrayToMap(arr, inverse) { + var result = new Map(); + for (var i = 0; i < arr.length; i += 2) { + if (inverse) { + result.set(arr[i + 1], arr[i]); + } else { + result.set(arr[i], arr[i + 1]); + } + } + return result; + } + function _flattenArray(tree, out) { + for (var i = 0; i < tree.length; i++) { + var item = di_1.resolveForwardRef(tree[i]); + if (lang_1.isArray(item)) { + _flattenArray(item, out); + } else { + out.push(item); + } + } + } + function _flattenStyleArr(arr, out) { + for (var i = 0; i < arr.length; i++) { + var entry = arr[i]; + if (lang_1.isArray(entry)) { + _flattenStyleArr(entry, out); + } else { + out.push(entry); + } + } + return out; + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/change_detection", ["angular2/src/core/change_detection/change_detection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var change_detection_1 = require("angular2/src/core/change_detection/change_detection"); + exports.ChangeDetectionStrategy = change_detection_1.ChangeDetectionStrategy; + exports.ExpressionChangedAfterItHasBeenCheckedException = change_detection_1.ExpressionChangedAfterItHasBeenCheckedException; + exports.ChangeDetectionError = change_detection_1.ChangeDetectionError; + exports.ChangeDetectorRef = change_detection_1.ChangeDetectorRef; + exports.WrappedValue = change_detection_1.WrappedValue; + exports.SimpleChange = change_detection_1.SimpleChange; + exports.IterableDiffers = change_detection_1.IterableDiffers; + exports.KeyValueDiffers = change_detection_1.KeyValueDiffers; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/compiler", ["angular2/src/core/linker/proto_view_factory", "angular2/src/core/di", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/async", "angular2/src/core/reflection/reflection", "angular2/src/core/linker/template_commands"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var proto_view_factory_1 = require("angular2/src/core/linker/proto_view_factory"); + var di_1 = require("angular2/src/core/di"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var async_1 = require("angular2/src/facade/async"); + var reflection_1 = require("angular2/src/core/reflection/reflection"); + var template_commands_1 = require("angular2/src/core/linker/template_commands"); + var Compiler = (function() { + function Compiler() {} + return Compiler; + })(); + exports.Compiler = Compiler; + function _isCompiledHostTemplate(type) { + return type instanceof template_commands_1.CompiledHostTemplate; + } + var Compiler_ = (function(_super) { + __extends(Compiler_, _super); + function Compiler_(_protoViewFactory) { + _super.call(this); + this._protoViewFactory = _protoViewFactory; + } + Compiler_.prototype.compileInHost = function(componentType) { + var metadatas = reflection_1.reflector.annotations(componentType); + var compiledHostTemplate = metadatas.find(_isCompiledHostTemplate); + if (lang_1.isBlank(compiledHostTemplate)) { + throw new exceptions_1.BaseException("No precompiled template for component " + lang_1.stringify(componentType) + " found"); + } + return async_1.PromiseWrapper.resolve(this._createProtoView(compiledHostTemplate)); + }; + Compiler_.prototype._createProtoView = function(compiledHostTemplate) { + return this._protoViewFactory.createHost(compiledHostTemplate).ref; + }; + Compiler_.prototype.clearCache = function() { + this._protoViewFactory.clearCache(); + }; + Compiler_ = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [proto_view_factory_1.ProtoViewFactory])], Compiler_); + return Compiler_; + })(Compiler); + exports.Compiler_ = Compiler_; + function internalCreateProtoView(compiler, compiledHostTemplate) { + return compiler._createProtoView(compiledHostTemplate); + } + exports.internalCreateProtoView = internalCreateProtoView; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/metadata/directives", ["angular2/src/facade/lang", "angular2/src/core/di/metadata", "angular2/src/core/change_detection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var metadata_1 = require("angular2/src/core/di/metadata"); + var change_detection_1 = require("angular2/src/core/change_detection"); + var DirectiveMetadata = (function(_super) { + __extends(DirectiveMetadata, _super); + function DirectiveMetadata(_a) { + var _b = _a === void 0 ? {} : _a, + selector = _b.selector, + inputs = _b.inputs, + outputs = _b.outputs, + properties = _b.properties, + events = _b.events, + host = _b.host, + bindings = _b.bindings, + providers = _b.providers, + exportAs = _b.exportAs, + queries = _b.queries; + _super.call(this); + this.selector = selector; + this._inputs = inputs; + this._properties = properties; + this._outputs = outputs; + this._events = events; + this.host = host; + this.exportAs = exportAs; + this.queries = queries; + this._providers = providers; + this._bindings = bindings; + } + Object.defineProperty(DirectiveMetadata.prototype, "inputs", { + get: function() { + return lang_1.isPresent(this._properties) && this._properties.length > 0 ? this._properties : this._inputs; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectiveMetadata.prototype, "properties", { + get: function() { + return this.inputs; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectiveMetadata.prototype, "outputs", { + get: function() { + return lang_1.isPresent(this._events) && this._events.length > 0 ? this._events : this._outputs; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectiveMetadata.prototype, "events", { + get: function() { + return this.outputs; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectiveMetadata.prototype, "providers", { + get: function() { + return lang_1.isPresent(this._bindings) && this._bindings.length > 0 ? this._bindings : this._providers; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectiveMetadata.prototype, "bindings", { + get: function() { + return this.providers; + }, + enumerable: true, + configurable: true + }); + DirectiveMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object])], DirectiveMetadata); + return DirectiveMetadata; + })(metadata_1.InjectableMetadata); + exports.DirectiveMetadata = DirectiveMetadata; + var ComponentMetadata = (function(_super) { + __extends(ComponentMetadata, _super); + function ComponentMetadata(_a) { + var _b = _a === void 0 ? {} : _a, + selector = _b.selector, + inputs = _b.inputs, + outputs = _b.outputs, + properties = _b.properties, + events = _b.events, + host = _b.host, + exportAs = _b.exportAs, + moduleId = _b.moduleId, + bindings = _b.bindings, + providers = _b.providers, + viewBindings = _b.viewBindings, + viewProviders = _b.viewProviders, + _c = _b.changeDetection, + changeDetection = _c === void 0 ? change_detection_1.ChangeDetectionStrategy.Default : _c, + queries = _b.queries, + templateUrl = _b.templateUrl, + template = _b.template, + styleUrls = _b.styleUrls, + styles = _b.styles, + directives = _b.directives, + pipes = _b.pipes, + encapsulation = _b.encapsulation; + _super.call(this, { + selector: selector, + inputs: inputs, + outputs: outputs, + properties: properties, + events: events, + host: host, + exportAs: exportAs, + bindings: bindings, + providers: providers, + queries: queries + }); + this.changeDetection = changeDetection; + this._viewProviders = viewProviders; + this._viewBindings = viewBindings; + this.templateUrl = templateUrl; + this.template = template; + this.styleUrls = styleUrls; + this.styles = styles; + this.directives = directives; + this.pipes = pipes; + this.encapsulation = encapsulation; + this.moduleId = moduleId; + } + Object.defineProperty(ComponentMetadata.prototype, "viewProviders", { + get: function() { + return lang_1.isPresent(this._viewBindings) && this._viewBindings.length > 0 ? this._viewBindings : this._viewProviders; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ComponentMetadata.prototype, "viewBindings", { + get: function() { + return this.viewProviders; + }, + enumerable: true, + configurable: true + }); + ComponentMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object])], ComponentMetadata); + return ComponentMetadata; + })(DirectiveMetadata); + exports.ComponentMetadata = ComponentMetadata; + var PipeMetadata = (function(_super) { + __extends(PipeMetadata, _super); + function PipeMetadata(_a) { + var name = _a.name, + pure = _a.pure; + _super.call(this); + this.name = name; + this._pure = pure; + } + Object.defineProperty(PipeMetadata.prototype, "pure", { + get: function() { + return lang_1.isPresent(this._pure) ? this._pure : true; + }, + enumerable: true, + configurable: true + }); + PipeMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object])], PipeMetadata); + return PipeMetadata; + })(metadata_1.InjectableMetadata); + exports.PipeMetadata = PipeMetadata; + var InputMetadata = (function() { + function InputMetadata(bindingPropertyName) { + this.bindingPropertyName = bindingPropertyName; + } + InputMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [String])], InputMetadata); + return InputMetadata; + })(); + exports.InputMetadata = InputMetadata; + var OutputMetadata = (function() { + function OutputMetadata(bindingPropertyName) { + this.bindingPropertyName = bindingPropertyName; + } + OutputMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [String])], OutputMetadata); + return OutputMetadata; + })(); + exports.OutputMetadata = OutputMetadata; + var HostBindingMetadata = (function() { + function HostBindingMetadata(hostPropertyName) { + this.hostPropertyName = hostPropertyName; + } + HostBindingMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [String])], HostBindingMetadata); + return HostBindingMetadata; + })(); + exports.HostBindingMetadata = HostBindingMetadata; + var HostListenerMetadata = (function() { + function HostListenerMetadata(eventName, args) { + this.eventName = eventName; + this.args = args; + } + HostListenerMetadata = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [String, Array])], HostListenerMetadata); + return HostListenerMetadata; + })(); + exports.HostListenerMetadata = HostListenerMetadata; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/facade/async", ["angular2/src/facade/lang", "angular2/src/facade/promise", "rxjs/Subject", "rxjs/observable/fromPromise", "rxjs/operator/toPromise", "rxjs/Observable", "rxjs/Subject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var lang_1 = require("angular2/src/facade/lang"); + var promise_1 = require("angular2/src/facade/promise"); + exports.PromiseWrapper = promise_1.PromiseWrapper; + exports.Promise = promise_1.Promise; + var Subject_1 = require("rxjs/Subject"); + var fromPromise_1 = require("rxjs/observable/fromPromise"); + var toPromise_1 = require("rxjs/operator/toPromise"); + var Observable_1 = require("rxjs/Observable"); + exports.Observable = Observable_1.Observable; + var Subject_2 = require("rxjs/Subject"); + exports.Subject = Subject_2.Subject; + var TimerWrapper = (function() { + function TimerWrapper() {} + TimerWrapper.setTimeout = function(fn, millis) { + return lang_1.global.setTimeout(fn, millis); + }; + TimerWrapper.clearTimeout = function(id) { + lang_1.global.clearTimeout(id); + }; + TimerWrapper.setInterval = function(fn, millis) { + return lang_1.global.setInterval(fn, millis); + }; + TimerWrapper.clearInterval = function(id) { + lang_1.global.clearInterval(id); + }; + return TimerWrapper; + })(); + exports.TimerWrapper = TimerWrapper; + var ObservableWrapper = (function() { + function ObservableWrapper() {} + ObservableWrapper.subscribe = function(emitter, onNext, onError, onComplete) { + if (onComplete === void 0) { + onComplete = function() {}; + } + onError = (typeof onError === "function") && onError || lang_1.noop; + onComplete = (typeof onComplete === "function") && onComplete || lang_1.noop; + return emitter.subscribe({ + next: onNext, + error: onError, + complete: onComplete + }); + }; + ObservableWrapper.isObservable = function(obs) { + return !!obs.subscribe; + }; + ObservableWrapper.hasSubscribers = function(obs) { + return obs.observers.length > 0; + }; + ObservableWrapper.dispose = function(subscription) { + subscription.unsubscribe(); + }; + ObservableWrapper.callNext = function(emitter, value) { + emitter.next(value); + }; + ObservableWrapper.callEmit = function(emitter, value) { + emitter.emit(value); + }; + ObservableWrapper.callError = function(emitter, error) { + emitter.error(error); + }; + ObservableWrapper.callComplete = function(emitter) { + emitter.complete(); + }; + ObservableWrapper.fromPromise = function(promise) { + return fromPromise_1.PromiseObservable.create(promise); + }; + ObservableWrapper.toPromise = function(obj) { + return toPromise_1.toPromise.call(obj); + }; + return ObservableWrapper; + })(); + exports.ObservableWrapper = ObservableWrapper; + var EventEmitter = (function(_super) { + __extends(EventEmitter, _super); + function EventEmitter(isAsync) { + if (isAsync === void 0) { + isAsync = true; + } + _super.call(this); + this._isAsync = isAsync; + } + EventEmitter.prototype.emit = function(value) { + _super.prototype.next.call(this, value); + }; + EventEmitter.prototype.next = function(value) { + _super.prototype.next.call(this, value); + }; + EventEmitter.prototype.subscribe = function(generatorOrNext, error, complete) { + var schedulerFn; + var errorFn = function(err) { + return null; + }; + var completeFn = function() { + return null; + }; + if (generatorOrNext && typeof generatorOrNext === 'object') { + schedulerFn = this._isAsync ? function(value) { + setTimeout(function() { + return generatorOrNext.next(value); + }); + } : function(value) { + generatorOrNext.next(value); + }; + if (generatorOrNext.error) { + errorFn = this._isAsync ? function(err) { + setTimeout(function() { + return generatorOrNext.error(err); + }); + } : function(err) { + generatorOrNext.error(err); + }; + } + if (generatorOrNext.complete) { + completeFn = this._isAsync ? function() { + setTimeout(function() { + return generatorOrNext.complete(); + }); + } : function() { + generatorOrNext.complete(); + }; + } + } else { + schedulerFn = this._isAsync ? function(value) { + setTimeout(function() { + return generatorOrNext(value); + }); + } : function(value) { + generatorOrNext(value); + }; + if (error) { + errorFn = this._isAsync ? function(err) { + setTimeout(function() { + return error(err); + }); + } : function(err) { + error(err); + }; + } + if (complete) { + completeFn = this._isAsync ? function() { + setTimeout(function() { + return complete(); + }); + } : function() { + complete(); + }; + } + } + return _super.prototype.subscribe.call(this, schedulerFn, errorFn, completeFn); + }; + return EventEmitter; + })(Subject_1.Subject); + exports.EventEmitter = EventEmitter; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/dynamic_component_loader", ["angular2/src/core/di", "angular2/src/core/linker/compiler", "angular2/src/facade/lang", "angular2/src/core/linker/view_manager"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var di_1 = require("angular2/src/core/di"); + var compiler_1 = require("angular2/src/core/linker/compiler"); + var lang_1 = require("angular2/src/facade/lang"); + var view_manager_1 = require("angular2/src/core/linker/view_manager"); + var ComponentRef = (function() { + function ComponentRef() {} + Object.defineProperty(ComponentRef.prototype, "hostView", { + get: function() { + return this.location.parentView; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ComponentRef.prototype, "hostComponent", { + get: function() { + return this.instance; + }, + enumerable: true, + configurable: true + }); + return ComponentRef; + })(); + exports.ComponentRef = ComponentRef; + var ComponentRef_ = (function(_super) { + __extends(ComponentRef_, _super); + function ComponentRef_(location, instance, componentType, injector, _dispose) { + _super.call(this); + this._dispose = _dispose; + this.location = location; + this.instance = instance; + this.componentType = componentType; + this.injector = injector; + } + Object.defineProperty(ComponentRef_.prototype, "hostComponentType", { + get: function() { + return this.componentType; + }, + enumerable: true, + configurable: true + }); + ComponentRef_.prototype.dispose = function() { + this._dispose(); + }; + return ComponentRef_; + })(ComponentRef); + exports.ComponentRef_ = ComponentRef_; + var DynamicComponentLoader = (function() { + function DynamicComponentLoader() {} + return DynamicComponentLoader; + })(); + exports.DynamicComponentLoader = DynamicComponentLoader; + var DynamicComponentLoader_ = (function(_super) { + __extends(DynamicComponentLoader_, _super); + function DynamicComponentLoader_(_compiler, _viewManager) { + _super.call(this); + this._compiler = _compiler; + this._viewManager = _viewManager; + } + DynamicComponentLoader_.prototype.loadAsRoot = function(type, overrideSelector, injector, onDispose) { + var _this = this; + return this._compiler.compileInHost(type).then(function(hostProtoViewRef) { + var hostViewRef = _this._viewManager.createRootHostView(hostProtoViewRef, overrideSelector, injector); + var newLocation = _this._viewManager.getHostElement(hostViewRef); + var component = _this._viewManager.getComponent(newLocation); + var dispose = function() { + if (lang_1.isPresent(onDispose)) { + onDispose(); + } + _this._viewManager.destroyRootHostView(hostViewRef); + }; + return new ComponentRef_(newLocation, component, type, injector, dispose); + }); + }; + DynamicComponentLoader_.prototype.loadIntoLocation = function(type, hostLocation, anchorName, providers) { + if (providers === void 0) { + providers = null; + } + return this.loadNextToLocation(type, this._viewManager.getNamedElementInComponentView(hostLocation, anchorName), providers); + }; + DynamicComponentLoader_.prototype.loadNextToLocation = function(type, location, providers) { + var _this = this; + if (providers === void 0) { + providers = null; + } + return this._compiler.compileInHost(type).then(function(hostProtoViewRef) { + var viewContainer = _this._viewManager.getViewContainer(location); + var hostViewRef = viewContainer.createHostView(hostProtoViewRef, viewContainer.length, providers); + var newLocation = _this._viewManager.getHostElement(hostViewRef); + var component = _this._viewManager.getComponent(newLocation); + var dispose = function() { + var index = viewContainer.indexOf(hostViewRef); + if (index !== -1) { + viewContainer.remove(index); + } + }; + return new ComponentRef_(newLocation, component, type, null, dispose); + }); + }; + DynamicComponentLoader_ = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [compiler_1.Compiler, view_manager_1.AppViewManager])], DynamicComponentLoader_); + return DynamicComponentLoader_; + })(DynamicComponentLoader); + exports.DynamicComponentLoader_ = DynamicComponentLoader_; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/metadata", ["angular2/src/core/metadata/di", "angular2/src/core/metadata/directives", "angular2/src/core/metadata/view", "angular2/src/core/metadata/di", "angular2/src/core/metadata/directives", "angular2/src/core/metadata/view", "angular2/src/core/util/decorators"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var di_1 = require("angular2/src/core/metadata/di"); + exports.QueryMetadata = di_1.QueryMetadata; + exports.ContentChildrenMetadata = di_1.ContentChildrenMetadata; + exports.ContentChildMetadata = di_1.ContentChildMetadata; + exports.ViewChildrenMetadata = di_1.ViewChildrenMetadata; + exports.ViewQueryMetadata = di_1.ViewQueryMetadata; + exports.ViewChildMetadata = di_1.ViewChildMetadata; + exports.AttributeMetadata = di_1.AttributeMetadata; + var directives_1 = require("angular2/src/core/metadata/directives"); + exports.ComponentMetadata = directives_1.ComponentMetadata; + exports.DirectiveMetadata = directives_1.DirectiveMetadata; + exports.PipeMetadata = directives_1.PipeMetadata; + exports.InputMetadata = directives_1.InputMetadata; + exports.OutputMetadata = directives_1.OutputMetadata; + exports.HostBindingMetadata = directives_1.HostBindingMetadata; + exports.HostListenerMetadata = directives_1.HostListenerMetadata; + var view_1 = require("angular2/src/core/metadata/view"); + exports.ViewMetadata = view_1.ViewMetadata; + exports.ViewEncapsulation = view_1.ViewEncapsulation; + var di_2 = require("angular2/src/core/metadata/di"); + var directives_2 = require("angular2/src/core/metadata/directives"); + var view_2 = require("angular2/src/core/metadata/view"); + var decorators_1 = require("angular2/src/core/util/decorators"); + exports.Component = decorators_1.makeDecorator(directives_2.ComponentMetadata, function(fn) { + return fn.View = exports.View; + }); + exports.Directive = decorators_1.makeDecorator(directives_2.DirectiveMetadata); + exports.View = decorators_1.makeDecorator(view_2.ViewMetadata, function(fn) { + return fn.View = exports.View; + }); + exports.Attribute = decorators_1.makeParamDecorator(di_2.AttributeMetadata); + exports.Query = decorators_1.makeParamDecorator(di_2.QueryMetadata); + exports.ContentChildren = decorators_1.makePropDecorator(di_2.ContentChildrenMetadata); + exports.ContentChild = decorators_1.makePropDecorator(di_2.ContentChildMetadata); + exports.ViewChildren = decorators_1.makePropDecorator(di_2.ViewChildrenMetadata); + exports.ViewChild = decorators_1.makePropDecorator(di_2.ViewChildMetadata); + exports.ViewQuery = decorators_1.makeParamDecorator(di_2.ViewQueryMetadata); + exports.Pipe = decorators_1.makeDecorator(directives_2.PipeMetadata); + exports.Input = decorators_1.makePropDecorator(directives_2.InputMetadata); + exports.Output = decorators_1.makePropDecorator(directives_2.OutputMetadata); + exports.HostBinding = decorators_1.makePropDecorator(directives_2.HostBindingMetadata); + exports.HostListener = decorators_1.makePropDecorator(directives_2.HostListenerMetadata); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/facade/facade", ["angular2/src/facade/lang", "angular2/src/facade/async", "angular2/src/facade/exceptions", "angular2/src/facade/exception_handler"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + exports.Type = lang_1.Type; + var async_1 = require("angular2/src/facade/async"); + exports.EventEmitter = async_1.EventEmitter; + var exceptions_1 = require("angular2/src/facade/exceptions"); + exports.WrappedException = exceptions_1.WrappedException; + var exception_handler_1 = require("angular2/src/facade/exception_handler"); + exports.ExceptionHandler = exception_handler_1.ExceptionHandler; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/application_ref", ["angular2/src/core/zone/ng_zone", "angular2/src/facade/lang", "angular2/src/core/di", "angular2/src/core/application_tokens", "angular2/src/facade/async", "angular2/src/facade/collection", "angular2/src/core/testability/testability", "angular2/src/core/linker/dynamic_component_loader", "angular2/src/facade/exceptions", "angular2/src/core/linker/view_ref", "angular2/src/core/console", "angular2/src/core/profile/profile", "angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var ng_zone_1 = require("angular2/src/core/zone/ng_zone"); + var lang_1 = require("angular2/src/facade/lang"); + var di_1 = require("angular2/src/core/di"); + var application_tokens_1 = require("angular2/src/core/application_tokens"); + var async_1 = require("angular2/src/facade/async"); + var collection_1 = require("angular2/src/facade/collection"); + var testability_1 = require("angular2/src/core/testability/testability"); + var dynamic_component_loader_1 = require("angular2/src/core/linker/dynamic_component_loader"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var view_ref_1 = require("angular2/src/core/linker/view_ref"); + var console_1 = require("angular2/src/core/console"); + var profile_1 = require("angular2/src/core/profile/profile"); + var lang_2 = require("angular2/src/facade/lang"); + function _componentProviders(appComponentType) { + return [di_1.provide(application_tokens_1.APP_COMPONENT, {useValue: appComponentType}), di_1.provide(application_tokens_1.APP_COMPONENT_REF_PROMISE, { + useFactory: function(dynamicComponentLoader, appRef, injector) { + var ref; + return dynamicComponentLoader.loadAsRoot(appComponentType, null, injector, function() { + appRef._unloadComponent(ref); + }).then(function(componentRef) { + ref = componentRef; + if (lang_1.isPresent(componentRef.location.nativeElement)) { + injector.get(testability_1.TestabilityRegistry).registerApplication(componentRef.location.nativeElement, injector.get(testability_1.Testability)); + } + return componentRef; + }); + }, + deps: [dynamic_component_loader_1.DynamicComponentLoader, ApplicationRef, di_1.Injector] + }), di_1.provide(appComponentType, { + useFactory: function(p) { + return p.then(function(ref) { + return ref.instance; + }); + }, + deps: [application_tokens_1.APP_COMPONENT_REF_PROMISE] + })]; + } + function createNgZone() { + return new ng_zone_1.NgZone({enableLongStackTrace: lang_1.assertionsEnabled()}); + } + exports.createNgZone = createNgZone; + var _platform; + var _platformProviders; + function platform(providers) { + lang_2.lockMode(); + if (lang_1.isPresent(_platform)) { + if (collection_1.ListWrapper.equals(_platformProviders, providers)) { + return _platform; + } else { + throw new exceptions_1.BaseException("platform cannot be initialized with different sets of providers."); + } + } else { + return _createPlatform(providers); + } + } + exports.platform = platform; + function disposePlatform() { + if (lang_1.isPresent(_platform)) { + _platform.dispose(); + _platform = null; + } + } + exports.disposePlatform = disposePlatform; + function _createPlatform(providers) { + _platformProviders = providers; + var injector = di_1.Injector.resolveAndCreate(providers); + _platform = new PlatformRef_(injector, function() { + _platform = null; + _platformProviders = null; + }); + _runPlatformInitializers(injector); + return _platform; + } + function _runPlatformInitializers(injector) { + var inits = injector.getOptional(application_tokens_1.PLATFORM_INITIALIZER); + if (lang_1.isPresent(inits)) + inits.forEach(function(init) { + return init(); + }); + } + var PlatformRef = (function() { + function PlatformRef() {} + Object.defineProperty(PlatformRef.prototype, "injector", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + return PlatformRef; + })(); + exports.PlatformRef = PlatformRef; + var PlatformRef_ = (function(_super) { + __extends(PlatformRef_, _super); + function PlatformRef_(_injector, _dispose) { + _super.call(this); + this._injector = _injector; + this._dispose = _dispose; + this._applications = []; + this._disposeListeners = []; + } + PlatformRef_.prototype.registerDisposeListener = function(dispose) { + this._disposeListeners.push(dispose); + }; + Object.defineProperty(PlatformRef_.prototype, "injector", { + get: function() { + return this._injector; + }, + enumerable: true, + configurable: true + }); + PlatformRef_.prototype.application = function(providers) { + var app = this._initApp(createNgZone(), providers); + return app; + }; + PlatformRef_.prototype.asyncApplication = function(bindingFn, additionalProviders) { + var _this = this; + var zone = createNgZone(); + var completer = async_1.PromiseWrapper.completer(); + zone.run(function() { + async_1.PromiseWrapper.then(bindingFn(zone), function(providers) { + if (lang_1.isPresent(additionalProviders)) { + providers = collection_1.ListWrapper.concat(providers, additionalProviders); + } + completer.resolve(_this._initApp(zone, providers)); + }); + }); + return completer.promise; + }; + PlatformRef_.prototype._initApp = function(zone, providers) { + var _this = this; + var injector; + var app; + zone.run(function() { + providers = collection_1.ListWrapper.concat(providers, [di_1.provide(ng_zone_1.NgZone, {useValue: zone}), di_1.provide(ApplicationRef, { + useFactory: function() { + return app; + }, + deps: [] + })]); + var exceptionHandler; + try { + injector = _this.injector.resolveAndCreateChild(providers); + exceptionHandler = injector.get(exceptions_1.ExceptionHandler); + zone.overrideOnErrorHandler(function(e, s) { + return exceptionHandler.call(e, s); + }); + } catch (e) { + if (lang_1.isPresent(exceptionHandler)) { + exceptionHandler.call(e, e.stack); + } else { + lang_1.print(e.toString()); + } + } + }); + app = new ApplicationRef_(this, zone, injector); + this._applications.push(app); + _runAppInitializers(injector); + return app; + }; + PlatformRef_.prototype.dispose = function() { + collection_1.ListWrapper.clone(this._applications).forEach(function(app) { + return app.dispose(); + }); + this._disposeListeners.forEach(function(dispose) { + return dispose(); + }); + this._dispose(); + }; + PlatformRef_.prototype._applicationDisposed = function(app) { + collection_1.ListWrapper.remove(this._applications, app); + }; + return PlatformRef_; + })(PlatformRef); + exports.PlatformRef_ = PlatformRef_; + function _runAppInitializers(injector) { + var inits = injector.getOptional(application_tokens_1.APP_INITIALIZER); + if (lang_1.isPresent(inits)) + inits.forEach(function(init) { + return init(); + }); + } + var ApplicationRef = (function() { + function ApplicationRef() {} + Object.defineProperty(ApplicationRef.prototype, "injector", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + Object.defineProperty(ApplicationRef.prototype, "zone", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + Object.defineProperty(ApplicationRef.prototype, "componentTypes", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + return ApplicationRef; + })(); + exports.ApplicationRef = ApplicationRef; + var ApplicationRef_ = (function(_super) { + __extends(ApplicationRef_, _super); + function ApplicationRef_(_platform, _zone, _injector) { + var _this = this; + _super.call(this); + this._platform = _platform; + this._zone = _zone; + this._injector = _injector; + this._bootstrapListeners = []; + this._disposeListeners = []; + this._rootComponents = []; + this._rootComponentTypes = []; + this._changeDetectorRefs = []; + this._runningTick = false; + this._enforceNoNewChanges = false; + if (lang_1.isPresent(this._zone)) { + async_1.ObservableWrapper.subscribe(this._zone.onTurnDone, function(_) { + _this._zone.run(function() { + _this.tick(); + }); + }); + } + this._enforceNoNewChanges = lang_1.assertionsEnabled(); + } + ApplicationRef_.prototype.registerBootstrapListener = function(listener) { + this._bootstrapListeners.push(listener); + }; + ApplicationRef_.prototype.registerDisposeListener = function(dispose) { + this._disposeListeners.push(dispose); + }; + ApplicationRef_.prototype.registerChangeDetector = function(changeDetector) { + this._changeDetectorRefs.push(changeDetector); + }; + ApplicationRef_.prototype.unregisterChangeDetector = function(changeDetector) { + collection_1.ListWrapper.remove(this._changeDetectorRefs, changeDetector); + }; + ApplicationRef_.prototype.bootstrap = function(componentType, providers) { + var _this = this; + var completer = async_1.PromiseWrapper.completer(); + this._zone.run(function() { + var componentProviders = _componentProviders(componentType); + if (lang_1.isPresent(providers)) { + componentProviders.push(providers); + } + var exceptionHandler = _this._injector.get(exceptions_1.ExceptionHandler); + _this._rootComponentTypes.push(componentType); + try { + var injector = _this._injector.resolveAndCreateChild(componentProviders); + var compRefToken = injector.get(application_tokens_1.APP_COMPONENT_REF_PROMISE); + var tick = function(componentRef) { + _this._loadComponent(componentRef); + completer.resolve(componentRef); + }; + var tickResult = async_1.PromiseWrapper.then(compRefToken, tick); + if (lang_1.IS_DART) { + async_1.PromiseWrapper.then(tickResult, function(_) {}); + } + async_1.PromiseWrapper.then(tickResult, null, function(err, stackTrace) { + return completer.reject(err, stackTrace); + }); + } catch (e) { + exceptionHandler.call(e, e.stack); + completer.reject(e, e.stack); + } + }); + return completer.promise.then(function(_) { + var c = _this._injector.get(console_1.Console); + var modeDescription = lang_1.assertionsEnabled() ? "in the development mode. Call enableProdMode() to enable the production mode." : "in the production mode. Call enableDevMode() to enable the development mode."; + c.log("Angular 2 is running " + modeDescription); + return _; + }); + }; + ApplicationRef_.prototype._loadComponent = function(ref) { + var appChangeDetector = view_ref_1.internalView(ref.hostView).changeDetector; + this._changeDetectorRefs.push(appChangeDetector.ref); + this.tick(); + this._rootComponents.push(ref); + this._bootstrapListeners.forEach(function(listener) { + return listener(ref); + }); + }; + ApplicationRef_.prototype._unloadComponent = function(ref) { + if (!collection_1.ListWrapper.contains(this._rootComponents, ref)) { + return ; + } + this.unregisterChangeDetector(view_ref_1.internalView(ref.hostView).changeDetector.ref); + collection_1.ListWrapper.remove(this._rootComponents, ref); + }; + Object.defineProperty(ApplicationRef_.prototype, "injector", { + get: function() { + return this._injector; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ApplicationRef_.prototype, "zone", { + get: function() { + return this._zone; + }, + enumerable: true, + configurable: true + }); + ApplicationRef_.prototype.tick = function() { + if (this._runningTick) { + throw new exceptions_1.BaseException("ApplicationRef.tick is called recursively"); + } + var s = ApplicationRef_._tickScope(); + try { + this._runningTick = true; + this._changeDetectorRefs.forEach(function(detector) { + return detector.detectChanges(); + }); + if (this._enforceNoNewChanges) { + this._changeDetectorRefs.forEach(function(detector) { + return detector.checkNoChanges(); + }); + } + } finally { + this._runningTick = false; + profile_1.wtfLeave(s); + } + }; + ApplicationRef_.prototype.dispose = function() { + collection_1.ListWrapper.clone(this._rootComponents).forEach(function(ref) { + return ref.dispose(); + }); + this._disposeListeners.forEach(function(dispose) { + return dispose(); + }); + this._platform._applicationDisposed(this); + }; + Object.defineProperty(ApplicationRef_.prototype, "componentTypes", { + get: function() { + return this._rootComponentTypes; + }, + enumerable: true, + configurable: true + }); + ApplicationRef_._tickScope = profile_1.wtfCreateScope('ApplicationRef#tick()'); + return ApplicationRef_; + })(ApplicationRef); + exports.ApplicationRef_ = ApplicationRef_; + global.define = __define; + return module.exports; +}); + +System.register("angular2/core", ["angular2/src/core/metadata", "angular2/src/core/util", "angular2/src/core/prod_mode", "angular2/src/core/di", "angular2/src/facade/facade", "angular2/src/facade/lang", "angular2/src/core/application_ref", "angular2/src/core/application_tokens", "angular2/src/core/zone", "angular2/src/core/render", "angular2/src/core/linker", "angular2/src/core/debug/debug_element", "angular2/src/core/testability/testability", "angular2/src/core/change_detection", "angular2/src/core/platform_directives_and_pipes", "angular2/src/core/platform_common_providers", "angular2/src/core/application_common_providers", "angular2/src/core/reflection/reflection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function __export(m) { + for (var p in m) + if (!exports.hasOwnProperty(p)) + exports[p] = m[p]; + } + __export(require("angular2/src/core/metadata")); + __export(require("angular2/src/core/util")); + __export(require("angular2/src/core/prod_mode")); + __export(require("angular2/src/core/di")); + __export(require("angular2/src/facade/facade")); + var lang_1 = require("angular2/src/facade/lang"); + exports.enableProdMode = lang_1.enableProdMode; + var application_ref_1 = require("angular2/src/core/application_ref"); + exports.platform = application_ref_1.platform; + exports.createNgZone = application_ref_1.createNgZone; + exports.PlatformRef = application_ref_1.PlatformRef; + exports.ApplicationRef = application_ref_1.ApplicationRef; + var application_tokens_1 = require("angular2/src/core/application_tokens"); + exports.APP_ID = application_tokens_1.APP_ID; + exports.APP_COMPONENT = application_tokens_1.APP_COMPONENT; + exports.APP_INITIALIZER = application_tokens_1.APP_INITIALIZER; + exports.PACKAGE_ROOT_URL = application_tokens_1.PACKAGE_ROOT_URL; + exports.PLATFORM_INITIALIZER = application_tokens_1.PLATFORM_INITIALIZER; + __export(require("angular2/src/core/zone")); + __export(require("angular2/src/core/render")); + __export(require("angular2/src/core/linker")); + var debug_element_1 = require("angular2/src/core/debug/debug_element"); + exports.DebugElement = debug_element_1.DebugElement; + exports.Scope = debug_element_1.Scope; + exports.inspectElement = debug_element_1.inspectElement; + exports.asNativeElements = debug_element_1.asNativeElements; + __export(require("angular2/src/core/testability/testability")); + __export(require("angular2/src/core/change_detection")); + __export(require("angular2/src/core/platform_directives_and_pipes")); + __export(require("angular2/src/core/platform_common_providers")); + __export(require("angular2/src/core/application_common_providers")); + __export(require("angular2/src/core/reflection/reflection")); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/dom/dom_renderer", ["angular2/src/core/di", "angular2/src/animate/animation_builder", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/platform/dom/shared_styles_host", "angular2/src/core/profile/profile", "angular2/core", "angular2/src/platform/dom/events/event_manager", "angular2/src/platform/dom/dom_tokens", "angular2/src/core/render/view_factory", "angular2/src/core/render/view", "angular2/src/core/metadata", "angular2/src/platform/dom/dom_adapter", "angular2/src/platform/dom/util"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var di_1 = require("angular2/src/core/di"); + var animation_builder_1 = require("angular2/src/animate/animation_builder"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var shared_styles_host_1 = require("angular2/src/platform/dom/shared_styles_host"); + var profile_1 = require("angular2/src/core/profile/profile"); + var core_1 = require("angular2/core"); + var event_manager_1 = require("angular2/src/platform/dom/events/event_manager"); + var dom_tokens_1 = require("angular2/src/platform/dom/dom_tokens"); + var view_factory_1 = require("angular2/src/core/render/view_factory"); + var view_1 = require("angular2/src/core/render/view"); + var metadata_1 = require("angular2/src/core/metadata"); + var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); + var util_1 = require("angular2/src/platform/dom/util"); + var NAMESPACE_URIS = lang_1.CONST_EXPR({ + 'xlink': 'http://www.w3.org/1999/xlink', + 'svg': 'http://www.w3.org/2000/svg' + }); + var TEMPLATE_COMMENT_TEXT = 'template bindings={}'; + var TEMPLATE_BINDINGS_EXP = /^template bindings=(.*)$/g; + var DomRenderer = (function(_super) { + __extends(DomRenderer, _super); + function DomRenderer() { + _super.apply(this, arguments); + } + DomRenderer.prototype.getNativeElementSync = function(location) { + return resolveInternalDomView(location.renderView).boundElements[location.boundElementIndex]; + }; + DomRenderer.prototype.getRootNodes = function(fragment) { + return resolveInternalDomFragment(fragment); + }; + DomRenderer.prototype.attachFragmentAfterFragment = function(previousFragmentRef, fragmentRef) { + var previousFragmentNodes = resolveInternalDomFragment(previousFragmentRef); + if (previousFragmentNodes.length > 0) { + var sibling = previousFragmentNodes[previousFragmentNodes.length - 1]; + var nodes = resolveInternalDomFragment(fragmentRef); + moveNodesAfterSibling(sibling, nodes); + this.animateNodesEnter(nodes); + } + }; + DomRenderer.prototype.animateNodesEnter = function(nodes) { + for (var i = 0; i < nodes.length; i++) + this.animateNodeEnter(nodes[i]); + }; + DomRenderer.prototype.attachFragmentAfterElement = function(elementRef, fragmentRef) { + var parentView = resolveInternalDomView(elementRef.renderView); + var element = parentView.boundElements[elementRef.boundElementIndex]; + var nodes = resolveInternalDomFragment(fragmentRef); + moveNodesAfterSibling(element, nodes); + this.animateNodesEnter(nodes); + }; + DomRenderer.prototype.hydrateView = function(viewRef) { + resolveInternalDomView(viewRef).hydrate(); + }; + DomRenderer.prototype.dehydrateView = function(viewRef) { + resolveInternalDomView(viewRef).dehydrate(); + }; + DomRenderer.prototype.createTemplateAnchor = function(attrNameAndValues) { + return dom_adapter_1.DOM.createComment(TEMPLATE_COMMENT_TEXT); + }; + DomRenderer.prototype.createText = function(value) { + return dom_adapter_1.DOM.createTextNode(lang_1.isPresent(value) ? value : ''); + }; + DomRenderer.prototype.appendChild = function(parent, child) { + dom_adapter_1.DOM.appendChild(parent, child); + }; + DomRenderer.prototype.setElementProperty = function(location, propertyName, propertyValue) { + var view = resolveInternalDomView(location.renderView); + dom_adapter_1.DOM.setProperty(view.boundElements[location.boundElementIndex], propertyName, propertyValue); + }; + DomRenderer.prototype.setElementAttribute = function(location, attributeName, attributeValue) { + var view = resolveInternalDomView(location.renderView); + var element = view.boundElements[location.boundElementIndex]; + if (lang_1.isPresent(attributeValue)) { + dom_adapter_1.DOM.setAttribute(element, attributeName, lang_1.stringify(attributeValue)); + } else { + dom_adapter_1.DOM.removeAttribute(element, attributeName); + } + }; + DomRenderer.prototype.setBindingDebugInfo = function(location, propertyName, propertyValue) { + var view = resolveInternalDomView(location.renderView); + var element = view.boundElements[location.boundElementIndex]; + var dashCasedPropertyName = util_1.camelCaseToDashCase(propertyName); + if (dom_adapter_1.DOM.isCommentNode(element)) { + var existingBindings = lang_1.RegExpWrapper.firstMatch(TEMPLATE_BINDINGS_EXP, lang_1.StringWrapper.replaceAll(dom_adapter_1.DOM.getText(element), /\n/g, '')); + var parsedBindings = lang_1.Json.parse(existingBindings[1]); + parsedBindings[dashCasedPropertyName] = propertyValue; + dom_adapter_1.DOM.setText(element, lang_1.StringWrapper.replace(TEMPLATE_COMMENT_TEXT, '{}', lang_1.Json.stringify(parsedBindings))); + } else { + this.setElementAttribute(location, propertyName, propertyValue); + } + }; + DomRenderer.prototype.setElementClass = function(location, className, isAdd) { + var view = resolveInternalDomView(location.renderView); + var element = view.boundElements[location.boundElementIndex]; + if (isAdd) { + dom_adapter_1.DOM.addClass(element, className); + } else { + dom_adapter_1.DOM.removeClass(element, className); + } + }; + DomRenderer.prototype.setElementStyle = function(location, styleName, styleValue) { + var view = resolveInternalDomView(location.renderView); + var element = view.boundElements[location.boundElementIndex]; + if (lang_1.isPresent(styleValue)) { + dom_adapter_1.DOM.setStyle(element, styleName, lang_1.stringify(styleValue)); + } else { + dom_adapter_1.DOM.removeStyle(element, styleName); + } + }; + DomRenderer.prototype.invokeElementMethod = function(location, methodName, args) { + var view = resolveInternalDomView(location.renderView); + var element = view.boundElements[location.boundElementIndex]; + dom_adapter_1.DOM.invoke(element, methodName, args); + }; + DomRenderer.prototype.setText = function(viewRef, textNodeIndex, text) { + var view = resolveInternalDomView(viewRef); + dom_adapter_1.DOM.setText(view.boundTextNodes[textNodeIndex], text); + }; + DomRenderer.prototype.setEventDispatcher = function(viewRef, dispatcher) { + resolveInternalDomView(viewRef).setEventDispatcher(dispatcher); + }; + return DomRenderer; + })(core_1.Renderer); + exports.DomRenderer = DomRenderer; + var DomRenderer_ = (function(_super) { + __extends(DomRenderer_, _super); + function DomRenderer_(_eventManager, _domSharedStylesHost, _animate, document) { + _super.call(this); + this._eventManager = _eventManager; + this._domSharedStylesHost = _domSharedStylesHost; + this._animate = _animate; + this._componentTpls = new Map(); + this._createRootHostViewScope = profile_1.wtfCreateScope('DomRenderer#createRootHostView()'); + this._createViewScope = profile_1.wtfCreateScope('DomRenderer#createView()'); + this._detachFragmentScope = profile_1.wtfCreateScope('DomRenderer#detachFragment()'); + this._document = document; + } + DomRenderer_.prototype.registerComponentTemplate = function(template) { + this._componentTpls.set(template.id, template); + if (template.encapsulation !== metadata_1.ViewEncapsulation.Native) { + var encapsulatedStyles = view_factory_1.encapsulateStyles(template); + this._domSharedStylesHost.addStyles(encapsulatedStyles); + } + }; + DomRenderer_.prototype.createProtoView = function(componentTemplateId, cmds) { + return new view_1.DefaultProtoViewRef(this._componentTpls.get(componentTemplateId), cmds); + }; + DomRenderer_.prototype.resolveComponentTemplate = function(templateId) { + return this._componentTpls.get(templateId); + }; + DomRenderer_.prototype.createRootHostView = function(hostProtoViewRef, fragmentCount, hostElementSelector) { + var s = this._createRootHostViewScope(); + var element = dom_adapter_1.DOM.querySelector(this._document, hostElementSelector); + if (lang_1.isBlank(element)) { + profile_1.wtfLeave(s); + throw new exceptions_1.BaseException("The selector \"" + hostElementSelector + "\" did not match any elements"); + } + return profile_1.wtfLeave(s, this._createView(hostProtoViewRef, element)); + }; + DomRenderer_.prototype.createView = function(protoViewRef, fragmentCount) { + var s = this._createViewScope(); + return profile_1.wtfLeave(s, this._createView(protoViewRef, null)); + }; + DomRenderer_.prototype._createView = function(protoViewRef, inplaceElement) { + var dpvr = protoViewRef; + var view = view_factory_1.createRenderView(dpvr.template, dpvr.cmds, inplaceElement, this); + var sdRoots = view.nativeShadowRoots; + for (var i = 0; i < sdRoots.length; i++) { + this._domSharedStylesHost.addHost(sdRoots[i]); + } + return new core_1.RenderViewWithFragments(view, view.fragments); + }; + DomRenderer_.prototype.destroyView = function(viewRef) { + var view = viewRef; + var sdRoots = view.nativeShadowRoots; + for (var i = 0; i < sdRoots.length; i++) { + this._domSharedStylesHost.removeHost(sdRoots[i]); + } + }; + DomRenderer_.prototype.animateNodeEnter = function(node) { + if (dom_adapter_1.DOM.isElementNode(node) && dom_adapter_1.DOM.hasClass(node, 'ng-animate')) { + dom_adapter_1.DOM.addClass(node, 'ng-enter'); + this._animate.css().addAnimationClass('ng-enter-active').start(node).onComplete(function() { + dom_adapter_1.DOM.removeClass(node, 'ng-enter'); + }); + } + }; + DomRenderer_.prototype.animateNodeLeave = function(node) { + if (dom_adapter_1.DOM.isElementNode(node) && dom_adapter_1.DOM.hasClass(node, 'ng-animate')) { + dom_adapter_1.DOM.addClass(node, 'ng-leave'); + this._animate.css().addAnimationClass('ng-leave-active').start(node).onComplete(function() { + dom_adapter_1.DOM.removeClass(node, 'ng-leave'); + dom_adapter_1.DOM.remove(node); + }); + } else { + dom_adapter_1.DOM.remove(node); + } + }; + DomRenderer_.prototype.detachFragment = function(fragmentRef) { + var s = this._detachFragmentScope(); + var fragmentNodes = resolveInternalDomFragment(fragmentRef); + for (var i = 0; i < fragmentNodes.length; i++) { + this.animateNodeLeave(fragmentNodes[i]); + } + profile_1.wtfLeave(s); + }; + DomRenderer_.prototype.createElement = function(name, attrNameAndValues) { + var nsAndName = splitNamespace(name); + var el = lang_1.isPresent(nsAndName[0]) ? dom_adapter_1.DOM.createElementNS(NAMESPACE_URIS[nsAndName[0]], nsAndName[1]) : dom_adapter_1.DOM.createElement(nsAndName[1]); + this._setAttributes(el, attrNameAndValues); + return el; + }; + DomRenderer_.prototype.mergeElement = function(existing, attrNameAndValues) { + dom_adapter_1.DOM.clearNodes(existing); + this._setAttributes(existing, attrNameAndValues); + }; + DomRenderer_.prototype._setAttributes = function(node, attrNameAndValues) { + for (var attrIdx = 0; attrIdx < attrNameAndValues.length; attrIdx += 2) { + var attrNs; + var attrName = attrNameAndValues[attrIdx]; + var nsAndName = splitNamespace(attrName); + if (lang_1.isPresent(nsAndName[0])) { + attrName = nsAndName[0] + ':' + nsAndName[1]; + attrNs = NAMESPACE_URIS[nsAndName[0]]; + } + var attrValue = attrNameAndValues[attrIdx + 1]; + if (lang_1.isPresent(attrNs)) { + dom_adapter_1.DOM.setAttributeNS(node, attrNs, attrName, attrValue); + } else { + dom_adapter_1.DOM.setAttribute(node, nsAndName[1], attrValue); + } + } + }; + DomRenderer_.prototype.createRootContentInsertionPoint = function() { + return dom_adapter_1.DOM.createComment('root-content-insertion-point'); + }; + DomRenderer_.prototype.createShadowRoot = function(host, templateId) { + var sr = dom_adapter_1.DOM.createShadowRoot(host); + var tpl = this._componentTpls.get(templateId); + for (var i = 0; i < tpl.styles.length; i++) { + dom_adapter_1.DOM.appendChild(sr, dom_adapter_1.DOM.createStyleElement(tpl.styles[i])); + } + return sr; + }; + DomRenderer_.prototype.on = function(element, eventName, callback) { + this._eventManager.addEventListener(element, eventName, decoratePreventDefault(callback)); + }; + DomRenderer_.prototype.globalOn = function(target, eventName, callback) { + return this._eventManager.addGlobalEventListener(target, eventName, decoratePreventDefault(callback)); + }; + DomRenderer_ = __decorate([di_1.Injectable(), __param(3, di_1.Inject(dom_tokens_1.DOCUMENT)), __metadata('design:paramtypes', [event_manager_1.EventManager, shared_styles_host_1.DomSharedStylesHost, animation_builder_1.AnimationBuilder, Object])], DomRenderer_); + return DomRenderer_; + })(DomRenderer); + exports.DomRenderer_ = DomRenderer_; + function resolveInternalDomView(viewRef) { + return viewRef; + } + function resolveInternalDomFragment(fragmentRef) { + return fragmentRef.nodes; + } + function moveNodesAfterSibling(sibling, nodes) { + var parent = dom_adapter_1.DOM.parentElement(sibling); + if (nodes.length > 0 && lang_1.isPresent(parent)) { + var nextSibling = dom_adapter_1.DOM.nextSibling(sibling); + if (lang_1.isPresent(nextSibling)) { + for (var i = 0; i < nodes.length; i++) { + dom_adapter_1.DOM.insertBefore(nextSibling, nodes[i]); + } + } else { + for (var i = 0; i < nodes.length; i++) { + dom_adapter_1.DOM.appendChild(parent, nodes[i]); + } + } + } + } + function decoratePreventDefault(eventHandler) { + return function(event) { + var allowDefaultBehavior = eventHandler(event); + if (!allowDefaultBehavior) { + dom_adapter_1.DOM.preventDefault(event); + } + }; + } + var NS_PREFIX_RE = /^@([^:]+):(.+)/g; + function splitNamespace(name) { + if (name[0] != '@') { + return [null, name]; + } + var match = lang_1.RegExpWrapper.firstMatch(NS_PREFIX_RE, name); + return [match[1], match[2]]; + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/platform/common_dom", ["angular2/src/platform/dom/dom_adapter", "angular2/src/platform/dom/dom_renderer", "angular2/src/platform/dom/dom_tokens", "angular2/src/platform/dom/shared_styles_host", "angular2/src/platform/dom/events/dom_events", "angular2/src/platform/dom/events/event_manager", "angular2/src/platform/dom/debug/by", "angular2/src/platform/dom/debug/debug_element_view_listener"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function __export(m) { + for (var p in m) + if (!exports.hasOwnProperty(p)) + exports[p] = m[p]; + } + var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); + exports.DOM = dom_adapter_1.DOM; + exports.setRootDomAdapter = dom_adapter_1.setRootDomAdapter; + exports.DomAdapter = dom_adapter_1.DomAdapter; + var dom_renderer_1 = require("angular2/src/platform/dom/dom_renderer"); + exports.DomRenderer = dom_renderer_1.DomRenderer; + var dom_tokens_1 = require("angular2/src/platform/dom/dom_tokens"); + exports.DOCUMENT = dom_tokens_1.DOCUMENT; + var shared_styles_host_1 = require("angular2/src/platform/dom/shared_styles_host"); + exports.SharedStylesHost = shared_styles_host_1.SharedStylesHost; + exports.DomSharedStylesHost = shared_styles_host_1.DomSharedStylesHost; + var dom_events_1 = require("angular2/src/platform/dom/events/dom_events"); + exports.DomEventsPlugin = dom_events_1.DomEventsPlugin; + var event_manager_1 = require("angular2/src/platform/dom/events/event_manager"); + exports.EVENT_MANAGER_PLUGINS = event_manager_1.EVENT_MANAGER_PLUGINS; + exports.EventManager = event_manager_1.EventManager; + exports.EventManagerPlugin = event_manager_1.EventManagerPlugin; + __export(require("angular2/src/platform/dom/debug/by")); + __export(require("angular2/src/platform/dom/debug/debug_element_view_listener")); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/pipes/invalid_pipe_argument_exception", ["angular2/src/facade/lang", "angular2/src/facade/exceptions"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var InvalidPipeArgumentException = (function(_super) { + __extends(InvalidPipeArgumentException, _super); + function InvalidPipeArgumentException(type, value) { + _super.call(this, "Invalid argument '" + value + "' for pipe '" + lang_1.stringify(type) + "'"); + } + return InvalidPipeArgumentException; + })(exceptions_1.BaseException); + exports.InvalidPipeArgumentException = InvalidPipeArgumentException; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/pipes/uppercase_pipe", ["angular2/src/facade/lang", "angular2/core", "angular2/src/common/pipes/invalid_pipe_argument_exception"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var core_1 = require("angular2/core"); + var invalid_pipe_argument_exception_1 = require("angular2/src/common/pipes/invalid_pipe_argument_exception"); + var UpperCasePipe = (function() { + function UpperCasePipe() {} + UpperCasePipe.prototype.transform = function(value, args) { + if (args === void 0) { + args = null; + } + if (lang_1.isBlank(value)) + return value; + if (!lang_1.isString(value)) { + throw new invalid_pipe_argument_exception_1.InvalidPipeArgumentException(UpperCasePipe, value); + } + return value.toUpperCase(); + }; + UpperCasePipe = __decorate([lang_1.CONST(), core_1.Pipe({name: 'uppercase'}), core_1.Injectable(), __metadata('design:paramtypes', [])], UpperCasePipe); + return UpperCasePipe; + })(); + exports.UpperCasePipe = UpperCasePipe; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/pipes/lowercase_pipe", ["angular2/src/facade/lang", "angular2/core", "angular2/src/common/pipes/invalid_pipe_argument_exception"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var core_1 = require("angular2/core"); + var invalid_pipe_argument_exception_1 = require("angular2/src/common/pipes/invalid_pipe_argument_exception"); + var LowerCasePipe = (function() { + function LowerCasePipe() {} + LowerCasePipe.prototype.transform = function(value, args) { + if (args === void 0) { + args = null; + } + if (lang_1.isBlank(value)) + return value; + if (!lang_1.isString(value)) { + throw new invalid_pipe_argument_exception_1.InvalidPipeArgumentException(LowerCasePipe, value); + } + return value.toLowerCase(); + }; + LowerCasePipe = __decorate([lang_1.CONST(), core_1.Pipe({name: 'lowercase'}), core_1.Injectable(), __metadata('design:paramtypes', [])], LowerCasePipe); + return LowerCasePipe; + })(); + exports.LowerCasePipe = LowerCasePipe; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/pipes/json_pipe", ["angular2/src/facade/lang", "angular2/core"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var core_1 = require("angular2/core"); + var JsonPipe = (function() { + function JsonPipe() {} + JsonPipe.prototype.transform = function(value, args) { + if (args === void 0) { + args = null; + } + return lang_1.Json.stringify(value); + }; + JsonPipe = __decorate([lang_1.CONST(), core_1.Pipe({ + name: 'json', + pure: false + }), core_1.Injectable(), __metadata('design:paramtypes', [])], JsonPipe); + return JsonPipe; + })(); + exports.JsonPipe = JsonPipe; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/pipes/slice_pipe", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/core", "angular2/src/common/pipes/invalid_pipe_argument_exception"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var core_1 = require("angular2/core"); + var invalid_pipe_argument_exception_1 = require("angular2/src/common/pipes/invalid_pipe_argument_exception"); + var SlicePipe = (function() { + function SlicePipe() {} + SlicePipe.prototype.transform = function(value, args) { + if (args === void 0) { + args = null; + } + if (lang_1.isBlank(args) || args.length == 0) { + throw new exceptions_1.BaseException('Slice pipe requires one argument'); + } + if (!this.supports(value)) { + throw new invalid_pipe_argument_exception_1.InvalidPipeArgumentException(SlicePipe, value); + } + if (lang_1.isBlank(value)) + return value; + var start = args[0]; + var end = args.length > 1 ? args[1] : null; + if (lang_1.isString(value)) { + return lang_1.StringWrapper.slice(value, start, end); + } + return collection_1.ListWrapper.slice(value, start, end); + }; + SlicePipe.prototype.supports = function(obj) { + return lang_1.isString(obj) || lang_1.isArray(obj); + }; + SlicePipe = __decorate([core_1.Pipe({ + name: 'slice', + pure: false + }), core_1.Injectable(), __metadata('design:paramtypes', [])], SlicePipe); + return SlicePipe; + })(); + exports.SlicePipe = SlicePipe; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/facade/intl", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + (function(NumberFormatStyle) { + NumberFormatStyle[NumberFormatStyle["Decimal"] = 0] = "Decimal"; + NumberFormatStyle[NumberFormatStyle["Percent"] = 1] = "Percent"; + NumberFormatStyle[NumberFormatStyle["Currency"] = 2] = "Currency"; + })(exports.NumberFormatStyle || (exports.NumberFormatStyle = {})); + var NumberFormatStyle = exports.NumberFormatStyle; + var NumberFormatter = (function() { + function NumberFormatter() {} + NumberFormatter.format = function(num, locale, style, _a) { + var _b = _a === void 0 ? {} : _a, + _c = _b.minimumIntegerDigits, + minimumIntegerDigits = _c === void 0 ? 1 : _c, + _d = _b.minimumFractionDigits, + minimumFractionDigits = _d === void 0 ? 0 : _d, + _e = _b.maximumFractionDigits, + maximumFractionDigits = _e === void 0 ? 3 : _e, + currency = _b.currency, + _f = _b.currencyAsSymbol, + currencyAsSymbol = _f === void 0 ? false : _f; + var intlOptions = { + minimumIntegerDigits: minimumIntegerDigits, + minimumFractionDigits: minimumFractionDigits, + maximumFractionDigits: maximumFractionDigits + }; + intlOptions.style = NumberFormatStyle[style].toLowerCase(); + if (style == NumberFormatStyle.Currency) { + intlOptions.currency = currency; + intlOptions.currencyDisplay = currencyAsSymbol ? 'symbol' : 'code'; + } + return new Intl.NumberFormat(locale, intlOptions).format(num); + }; + return NumberFormatter; + })(); + exports.NumberFormatter = NumberFormatter; + function digitCondition(len) { + return len == 2 ? '2-digit' : 'numeric'; + } + function nameCondition(len) { + return len < 4 ? 'short' : 'long'; + } + function extractComponents(pattern) { + var ret = {}; + var i = 0, + j; + while (i < pattern.length) { + j = i; + while (j < pattern.length && pattern[j] == pattern[i]) + j++; + var len = j - i; + switch (pattern[i]) { + case 'G': + ret.era = nameCondition(len); + break; + case 'y': + ret.year = digitCondition(len); + break; + case 'M': + if (len >= 3) + ret.month = nameCondition(len); + else + ret.month = digitCondition(len); + break; + case 'd': + ret.day = digitCondition(len); + break; + case 'E': + ret.weekday = nameCondition(len); + break; + case 'j': + ret.hour = digitCondition(len); + break; + case 'h': + ret.hour = digitCondition(len); + ret.hour12 = true; + break; + case 'H': + ret.hour = digitCondition(len); + ret.hour12 = false; + break; + case 'm': + ret.minute = digitCondition(len); + break; + case 's': + ret.second = digitCondition(len); + break; + case 'z': + ret.timeZoneName = 'long'; + break; + case 'Z': + ret.timeZoneName = 'short'; + break; + } + i = j; + } + return ret; + } + var dateFormatterCache = new Map(); + var DateFormatter = (function() { + function DateFormatter() {} + DateFormatter.format = function(date, locale, pattern) { + var key = locale + pattern; + if (dateFormatterCache.has(key)) { + return dateFormatterCache.get(key).format(date); + } + var formatter = new Intl.DateTimeFormat(locale, extractComponents(pattern)); + dateFormatterCache.set(key, formatter); + return formatter.format(date); + }; + return DateFormatter; + })(); + exports.DateFormatter = DateFormatter; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/pipes/number_pipe", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/intl", "angular2/core", "angular2/src/facade/collection", "angular2/src/common/pipes/invalid_pipe_argument_exception"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var intl_1 = require("angular2/src/facade/intl"); + var core_1 = require("angular2/core"); + var collection_1 = require("angular2/src/facade/collection"); + var invalid_pipe_argument_exception_1 = require("angular2/src/common/pipes/invalid_pipe_argument_exception"); + var defaultLocale = 'en-US'; + var _re = lang_1.RegExpWrapper.create('^(\\d+)?\\.((\\d+)(\\-(\\d+))?)?$'); + var NumberPipe = (function() { + function NumberPipe() {} + NumberPipe._format = function(value, style, digits, currency, currencyAsSymbol) { + if (currency === void 0) { + currency = null; + } + if (currencyAsSymbol === void 0) { + currencyAsSymbol = false; + } + if (lang_1.isBlank(value)) + return null; + if (!lang_1.isNumber(value)) { + throw new invalid_pipe_argument_exception_1.InvalidPipeArgumentException(NumberPipe, value); + } + var minInt = 1, + minFraction = 0, + maxFraction = 3; + if (lang_1.isPresent(digits)) { + var parts = lang_1.RegExpWrapper.firstMatch(_re, digits); + if (lang_1.isBlank(parts)) { + throw new exceptions_1.BaseException(digits + " is not a valid digit info for number pipes"); + } + if (lang_1.isPresent(parts[1])) { + minInt = lang_1.NumberWrapper.parseIntAutoRadix(parts[1]); + } + if (lang_1.isPresent(parts[3])) { + minFraction = lang_1.NumberWrapper.parseIntAutoRadix(parts[3]); + } + if (lang_1.isPresent(parts[5])) { + maxFraction = lang_1.NumberWrapper.parseIntAutoRadix(parts[5]); + } + } + return intl_1.NumberFormatter.format(value, defaultLocale, style, { + minimumIntegerDigits: minInt, + minimumFractionDigits: minFraction, + maximumFractionDigits: maxFraction, + currency: currency, + currencyAsSymbol: currencyAsSymbol + }); + }; + NumberPipe = __decorate([lang_1.CONST(), core_1.Injectable(), __metadata('design:paramtypes', [])], NumberPipe); + return NumberPipe; + })(); + exports.NumberPipe = NumberPipe; + var DecimalPipe = (function(_super) { + __extends(DecimalPipe, _super); + function DecimalPipe() { + _super.apply(this, arguments); + } + DecimalPipe.prototype.transform = function(value, args) { + var digits = collection_1.ListWrapper.first(args); + return NumberPipe._format(value, intl_1.NumberFormatStyle.Decimal, digits); + }; + DecimalPipe = __decorate([lang_1.CONST(), core_1.Pipe({name: 'number'}), core_1.Injectable(), __metadata('design:paramtypes', [])], DecimalPipe); + return DecimalPipe; + })(NumberPipe); + exports.DecimalPipe = DecimalPipe; + var PercentPipe = (function(_super) { + __extends(PercentPipe, _super); + function PercentPipe() { + _super.apply(this, arguments); + } + PercentPipe.prototype.transform = function(value, args) { + var digits = collection_1.ListWrapper.first(args); + return NumberPipe._format(value, intl_1.NumberFormatStyle.Percent, digits); + }; + PercentPipe = __decorate([lang_1.CONST(), core_1.Pipe({name: 'percent'}), core_1.Injectable(), __metadata('design:paramtypes', [])], PercentPipe); + return PercentPipe; + })(NumberPipe); + exports.PercentPipe = PercentPipe; + var CurrencyPipe = (function(_super) { + __extends(CurrencyPipe, _super); + function CurrencyPipe() { + _super.apply(this, arguments); + } + CurrencyPipe.prototype.transform = function(value, args) { + var currencyCode = lang_1.isPresent(args) && args.length > 0 ? args[0] : 'USD'; + var symbolDisplay = lang_1.isPresent(args) && args.length > 1 ? args[1] : false; + var digits = lang_1.isPresent(args) && args.length > 2 ? args[2] : null; + return NumberPipe._format(value, intl_1.NumberFormatStyle.Currency, digits, currencyCode, symbolDisplay); + }; + CurrencyPipe = __decorate([lang_1.CONST(), core_1.Pipe({name: 'currency'}), core_1.Injectable(), __metadata('design:paramtypes', [])], CurrencyPipe); + return CurrencyPipe; + })(NumberPipe); + exports.CurrencyPipe = CurrencyPipe; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/directives/ng_class", ["angular2/src/facade/lang", "angular2/core", "angular2/src/facade/collection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var core_1 = require("angular2/core"); + var collection_1 = require("angular2/src/facade/collection"); + var NgClass = (function() { + function NgClass(_iterableDiffers, _keyValueDiffers, _ngEl, _renderer) { + this._iterableDiffers = _iterableDiffers; + this._keyValueDiffers = _keyValueDiffers; + this._ngEl = _ngEl; + this._renderer = _renderer; + this._initialClasses = []; + } + Object.defineProperty(NgClass.prototype, "initialClasses", { + set: function(v) { + this._applyInitialClasses(true); + this._initialClasses = lang_1.isPresent(v) && lang_1.isString(v) ? v.split(' ') : []; + this._applyInitialClasses(false); + this._applyClasses(this._rawClass, false); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgClass.prototype, "rawClass", { + set: function(v) { + this._cleanupClasses(this._rawClass); + if (lang_1.isString(v)) { + v = v.split(' '); + } + this._rawClass = v; + if (lang_1.isPresent(v)) { + if (collection_1.isListLikeIterable(v)) { + this._differ = this._iterableDiffers.find(v).create(null); + this._mode = 'iterable'; + } else { + this._differ = this._keyValueDiffers.find(v).create(null); + this._mode = 'keyValue'; + } + } else { + this._differ = null; + } + }, + enumerable: true, + configurable: true + }); + NgClass.prototype.ngDoCheck = function() { + if (lang_1.isPresent(this._differ)) { + var changes = this._differ.diff(this._rawClass); + if (lang_1.isPresent(changes)) { + if (this._mode == 'iterable') { + this._applyIterableChanges(changes); + } else { + this._applyKeyValueChanges(changes); + } + } + } + }; + NgClass.prototype.ngOnDestroy = function() { + this._cleanupClasses(this._rawClass); + }; + NgClass.prototype._cleanupClasses = function(rawClassVal) { + this._applyClasses(rawClassVal, true); + this._applyInitialClasses(false); + }; + NgClass.prototype._applyKeyValueChanges = function(changes) { + var _this = this; + changes.forEachAddedItem(function(record) { + _this._toggleClass(record.key, record.currentValue); + }); + changes.forEachChangedItem(function(record) { + _this._toggleClass(record.key, record.currentValue); + }); + changes.forEachRemovedItem(function(record) { + if (record.previousValue) { + _this._toggleClass(record.key, false); + } + }); + }; + NgClass.prototype._applyIterableChanges = function(changes) { + var _this = this; + changes.forEachAddedItem(function(record) { + _this._toggleClass(record.item, true); + }); + changes.forEachRemovedItem(function(record) { + _this._toggleClass(record.item, false); + }); + }; + NgClass.prototype._applyInitialClasses = function(isCleanup) { + var _this = this; + this._initialClasses.forEach(function(className) { + return _this._toggleClass(className, !isCleanup); + }); + }; + NgClass.prototype._applyClasses = function(rawClassVal, isCleanup) { + var _this = this; + if (lang_1.isPresent(rawClassVal)) { + if (lang_1.isArray(rawClassVal)) { + rawClassVal.forEach(function(className) { + return _this._toggleClass(className, !isCleanup); + }); + } else if (rawClassVal instanceof Set) { + rawClassVal.forEach(function(className) { + return _this._toggleClass(className, !isCleanup); + }); + } else { + collection_1.StringMapWrapper.forEach(rawClassVal, function(expVal, className) { + if (expVal) + _this._toggleClass(className, !isCleanup); + }); + } + } + }; + NgClass.prototype._toggleClass = function(className, enabled) { + className = className.trim(); + if (className.length > 0) { + if (className.indexOf(' ') > -1) { + var classes = className.split(/\s+/g); + for (var i = 0, + len = classes.length; i < len; i++) { + this._renderer.setElementClass(this._ngEl, classes[i], enabled); + } + } else { + this._renderer.setElementClass(this._ngEl, className, enabled); + } + } + }; + NgClass = __decorate([core_1.Directive({ + selector: '[ngClass]', + inputs: ['rawClass: ngClass', 'initialClasses: class'] + }), __metadata('design:paramtypes', [core_1.IterableDiffers, core_1.KeyValueDiffers, core_1.ElementRef, core_1.Renderer])], NgClass); + return NgClass; + })(); + exports.NgClass = NgClass; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/directives/ng_for", ["angular2/core", "angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var core_1 = require("angular2/core"); + var lang_1 = require("angular2/src/facade/lang"); + var NgFor = (function() { + function NgFor(_viewContainer, _templateRef, _iterableDiffers, _cdr) { + this._viewContainer = _viewContainer; + this._templateRef = _templateRef; + this._iterableDiffers = _iterableDiffers; + this._cdr = _cdr; + } + Object.defineProperty(NgFor.prototype, "ngForOf", { + set: function(value) { + this._ngForOf = value; + if (lang_1.isBlank(this._differ) && lang_1.isPresent(value)) { + this._differ = this._iterableDiffers.find(value).create(this._cdr); + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgFor.prototype, "ngForTemplate", { + set: function(value) { + if (lang_1.isPresent(value)) { + this._templateRef = value; + } + }, + enumerable: true, + configurable: true + }); + NgFor.prototype.ngDoCheck = function() { + if (lang_1.isPresent(this._differ)) { + var changes = this._differ.diff(this._ngForOf); + if (lang_1.isPresent(changes)) + this._applyChanges(changes); + } + }; + NgFor.prototype._applyChanges = function(changes) { + var recordViewTuples = []; + changes.forEachRemovedItem(function(removedRecord) { + return recordViewTuples.push(new RecordViewTuple(removedRecord, null)); + }); + changes.forEachMovedItem(function(movedRecord) { + return recordViewTuples.push(new RecordViewTuple(movedRecord, null)); + }); + var insertTuples = this._bulkRemove(recordViewTuples); + changes.forEachAddedItem(function(addedRecord) { + return insertTuples.push(new RecordViewTuple(addedRecord, null)); + }); + this._bulkInsert(insertTuples); + for (var i = 0; i < insertTuples.length; i++) { + this._perViewChange(insertTuples[i].view, insertTuples[i].record); + } + for (var i = 0, + ilen = this._viewContainer.length; i < ilen; i++) { + this._viewContainer.get(i).setLocal('last', i === ilen - 1); + } + }; + NgFor.prototype._perViewChange = function(view, record) { + view.setLocal('\$implicit', record.item); + view.setLocal('index', record.currentIndex); + view.setLocal('even', (record.currentIndex % 2 == 0)); + view.setLocal('odd', (record.currentIndex % 2 == 1)); + }; + NgFor.prototype._bulkRemove = function(tuples) { + tuples.sort(function(a, b) { + return a.record.previousIndex - b.record.previousIndex; + }); + var movedTuples = []; + for (var i = tuples.length - 1; i >= 0; i--) { + var tuple = tuples[i]; + if (lang_1.isPresent(tuple.record.currentIndex)) { + tuple.view = this._viewContainer.detach(tuple.record.previousIndex); + movedTuples.push(tuple); + } else { + this._viewContainer.remove(tuple.record.previousIndex); + } + } + return movedTuples; + }; + NgFor.prototype._bulkInsert = function(tuples) { + tuples.sort(function(a, b) { + return a.record.currentIndex - b.record.currentIndex; + }); + for (var i = 0; i < tuples.length; i++) { + var tuple = tuples[i]; + if (lang_1.isPresent(tuple.view)) { + this._viewContainer.insert(tuple.view, tuple.record.currentIndex); + } else { + tuple.view = this._viewContainer.createEmbeddedView(this._templateRef, tuple.record.currentIndex); + } + } + return tuples; + }; + NgFor = __decorate([core_1.Directive({ + selector: '[ngFor][ngForOf]', + inputs: ['ngForOf', 'ngForTemplate'] + }), __metadata('design:paramtypes', [core_1.ViewContainerRef, core_1.TemplateRef, core_1.IterableDiffers, core_1.ChangeDetectorRef])], NgFor); + return NgFor; + })(); + exports.NgFor = NgFor; + var RecordViewTuple = (function() { + function RecordViewTuple(record, view) { + this.record = record; + this.view = view; + } + return RecordViewTuple; + })(); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/directives/ng_if", ["angular2/core", "angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var core_1 = require("angular2/core"); + var lang_1 = require("angular2/src/facade/lang"); + var NgIf = (function() { + function NgIf(_viewContainer, _templateRef) { + this._viewContainer = _viewContainer; + this._templateRef = _templateRef; + this._prevCondition = null; + } + Object.defineProperty(NgIf.prototype, "ngIf", { + set: function(newCondition) { + if (newCondition && (lang_1.isBlank(this._prevCondition) || !this._prevCondition)) { + this._prevCondition = true; + this._viewContainer.createEmbeddedView(this._templateRef); + } else if (!newCondition && (lang_1.isBlank(this._prevCondition) || this._prevCondition)) { + this._prevCondition = false; + this._viewContainer.clear(); + } + }, + enumerable: true, + configurable: true + }); + NgIf = __decorate([core_1.Directive({ + selector: '[ngIf]', + inputs: ['ngIf'] + }), __metadata('design:paramtypes', [core_1.ViewContainerRef, core_1.TemplateRef])], NgIf); + return NgIf; + })(); + exports.NgIf = NgIf; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/directives/ng_style", ["angular2/core", "angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var core_1 = require("angular2/core"); + var lang_1 = require("angular2/src/facade/lang"); + var NgStyle = (function() { + function NgStyle(_differs, _ngEl, _renderer) { + this._differs = _differs; + this._ngEl = _ngEl; + this._renderer = _renderer; + } + Object.defineProperty(NgStyle.prototype, "rawStyle", { + set: function(v) { + this._rawStyle = v; + if (lang_1.isBlank(this._differ) && lang_1.isPresent(v)) { + this._differ = this._differs.find(this._rawStyle).create(null); + } + }, + enumerable: true, + configurable: true + }); + NgStyle.prototype.ngDoCheck = function() { + if (lang_1.isPresent(this._differ)) { + var changes = this._differ.diff(this._rawStyle); + if (lang_1.isPresent(changes)) { + this._applyChanges(changes); + } + } + }; + NgStyle.prototype._applyChanges = function(changes) { + var _this = this; + changes.forEachAddedItem(function(record) { + _this._setStyle(record.key, record.currentValue); + }); + changes.forEachChangedItem(function(record) { + _this._setStyle(record.key, record.currentValue); + }); + changes.forEachRemovedItem(function(record) { + _this._setStyle(record.key, null); + }); + }; + NgStyle.prototype._setStyle = function(name, val) { + this._renderer.setElementStyle(this._ngEl, name, val); + }; + NgStyle = __decorate([core_1.Directive({ + selector: '[ngStyle]', + inputs: ['rawStyle: ngStyle'] + }), __metadata('design:paramtypes', [core_1.KeyValueDiffers, core_1.ElementRef, core_1.Renderer])], NgStyle); + return NgStyle; + })(); + exports.NgStyle = NgStyle; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/directives/ng_switch", ["angular2/core", "angular2/src/facade/lang", "angular2/src/facade/collection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var core_1 = require("angular2/core"); + var lang_1 = require("angular2/src/facade/lang"); + var collection_1 = require("angular2/src/facade/collection"); + var _WHEN_DEFAULT = lang_1.CONST_EXPR(new Object()); + var SwitchView = (function() { + function SwitchView(_viewContainerRef, _templateRef) { + this._viewContainerRef = _viewContainerRef; + this._templateRef = _templateRef; + } + SwitchView.prototype.create = function() { + this._viewContainerRef.createEmbeddedView(this._templateRef); + }; + SwitchView.prototype.destroy = function() { + this._viewContainerRef.clear(); + }; + return SwitchView; + })(); + var NgSwitch = (function() { + function NgSwitch() { + this._useDefault = false; + this._valueViews = new collection_1.Map(); + this._activeViews = []; + } + Object.defineProperty(NgSwitch.prototype, "ngSwitch", { + set: function(value) { + this._emptyAllActiveViews(); + this._useDefault = false; + var views = this._valueViews.get(value); + if (lang_1.isBlank(views)) { + this._useDefault = true; + views = lang_1.normalizeBlank(this._valueViews.get(_WHEN_DEFAULT)); + } + this._activateViews(views); + this._switchValue = value; + }, + enumerable: true, + configurable: true + }); + NgSwitch.prototype._onWhenValueChanged = function(oldWhen, newWhen, view) { + this._deregisterView(oldWhen, view); + this._registerView(newWhen, view); + if (oldWhen === this._switchValue) { + view.destroy(); + collection_1.ListWrapper.remove(this._activeViews, view); + } else if (newWhen === this._switchValue) { + if (this._useDefault) { + this._useDefault = false; + this._emptyAllActiveViews(); + } + view.create(); + this._activeViews.push(view); + } + if (this._activeViews.length === 0 && !this._useDefault) { + this._useDefault = true; + this._activateViews(this._valueViews.get(_WHEN_DEFAULT)); + } + }; + NgSwitch.prototype._emptyAllActiveViews = function() { + var activeContainers = this._activeViews; + for (var i = 0; i < activeContainers.length; i++) { + activeContainers[i].destroy(); + } + this._activeViews = []; + }; + NgSwitch.prototype._activateViews = function(views) { + if (lang_1.isPresent(views)) { + for (var i = 0; i < views.length; i++) { + views[i].create(); + } + this._activeViews = views; + } + }; + NgSwitch.prototype._registerView = function(value, view) { + var views = this._valueViews.get(value); + if (lang_1.isBlank(views)) { + views = []; + this._valueViews.set(value, views); + } + views.push(view); + }; + NgSwitch.prototype._deregisterView = function(value, view) { + if (value === _WHEN_DEFAULT) + return ; + var views = this._valueViews.get(value); + if (views.length == 1) { + this._valueViews.delete(value); + } else { + collection_1.ListWrapper.remove(views, view); + } + }; + NgSwitch = __decorate([core_1.Directive({ + selector: '[ngSwitch]', + inputs: ['ngSwitch'] + }), __metadata('design:paramtypes', [])], NgSwitch); + return NgSwitch; + })(); + exports.NgSwitch = NgSwitch; + var NgSwitchWhen = (function() { + function NgSwitchWhen(viewContainer, templateRef, ngSwitch) { + this._value = _WHEN_DEFAULT; + this._switch = ngSwitch; + this._view = new SwitchView(viewContainer, templateRef); + } + Object.defineProperty(NgSwitchWhen.prototype, "ngSwitchWhen", { + set: function(value) { + this._switch._onWhenValueChanged(this._value, value, this._view); + this._value = value; + }, + enumerable: true, + configurable: true + }); + NgSwitchWhen = __decorate([core_1.Directive({ + selector: '[ngSwitchWhen]', + inputs: ['ngSwitchWhen'] + }), __param(2, core_1.Host()), __metadata('design:paramtypes', [core_1.ViewContainerRef, core_1.TemplateRef, NgSwitch])], NgSwitchWhen); + return NgSwitchWhen; + })(); + exports.NgSwitchWhen = NgSwitchWhen; + var NgSwitchDefault = (function() { + function NgSwitchDefault(viewContainer, templateRef, sswitch) { + sswitch._registerView(_WHEN_DEFAULT, new SwitchView(viewContainer, templateRef)); + } + NgSwitchDefault = __decorate([core_1.Directive({selector: '[ngSwitchDefault]'}), __param(2, core_1.Host()), __metadata('design:paramtypes', [core_1.ViewContainerRef, core_1.TemplateRef, NgSwitch])], NgSwitchDefault); + return NgSwitchDefault; + })(); + exports.NgSwitchDefault = NgSwitchDefault; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/directives/observable_list_diff", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/directives/core_directives", ["angular2/src/facade/lang", "angular2/src/common/directives/ng_class", "angular2/src/common/directives/ng_for", "angular2/src/common/directives/ng_if", "angular2/src/common/directives/ng_style", "angular2/src/common/directives/ng_switch"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var ng_class_1 = require("angular2/src/common/directives/ng_class"); + var ng_for_1 = require("angular2/src/common/directives/ng_for"); + var ng_if_1 = require("angular2/src/common/directives/ng_if"); + var ng_style_1 = require("angular2/src/common/directives/ng_style"); + var ng_switch_1 = require("angular2/src/common/directives/ng_switch"); + exports.CORE_DIRECTIVES = lang_1.CONST_EXPR([ng_class_1.NgClass, ng_for_1.NgFor, ng_if_1.NgIf, ng_style_1.NgStyle, ng_switch_1.NgSwitch, ng_switch_1.NgSwitchWhen, ng_switch_1.NgSwitchDefault]); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/model", ["angular2/src/facade/lang", "angular2/src/facade/async", "angular2/src/facade/promise", "angular2/src/facade/collection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var lang_1 = require("angular2/src/facade/lang"); + var async_1 = require("angular2/src/facade/async"); + var promise_1 = require("angular2/src/facade/promise"); + var collection_1 = require("angular2/src/facade/collection"); + exports.VALID = "VALID"; + exports.INVALID = "INVALID"; + exports.PENDING = "PENDING"; + function isControl(control) { + return control instanceof AbstractControl; + } + exports.isControl = isControl; + function _find(control, path) { + if (lang_1.isBlank(path)) + return null; + if (!(path instanceof Array)) { + path = path.split("/"); + } + if (path instanceof Array && collection_1.ListWrapper.isEmpty(path)) + return null; + return path.reduce(function(v, name) { + if (v instanceof ControlGroup) { + return lang_1.isPresent(v.controls[name]) ? v.controls[name] : null; + } else if (v instanceof ControlArray) { + var index = name; + return lang_1.isPresent(v.at(index)) ? v.at(index) : null; + } else { + return null; + } + }, control); + } + function toObservable(r) { + return promise_1.PromiseWrapper.isPromise(r) ? async_1.ObservableWrapper.fromPromise(r) : r; + } + var AbstractControl = (function() { + function AbstractControl(validator, asyncValidator) { + this.validator = validator; + this.asyncValidator = asyncValidator; + this._pristine = true; + this._touched = false; + } + Object.defineProperty(AbstractControl.prototype, "value", { + get: function() { + return this._value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbstractControl.prototype, "status", { + get: function() { + return this._status; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbstractControl.prototype, "valid", { + get: function() { + return this._status === exports.VALID; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbstractControl.prototype, "errors", { + get: function() { + return this._errors; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbstractControl.prototype, "pristine", { + get: function() { + return this._pristine; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbstractControl.prototype, "dirty", { + get: function() { + return !this.pristine; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbstractControl.prototype, "touched", { + get: function() { + return this._touched; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbstractControl.prototype, "untouched", { + get: function() { + return !this._touched; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbstractControl.prototype, "valueChanges", { + get: function() { + return this._valueChanges; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbstractControl.prototype, "statusChanges", { + get: function() { + return this._statusChanges; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbstractControl.prototype, "pending", { + get: function() { + return this._status == exports.PENDING; + }, + enumerable: true, + configurable: true + }); + AbstractControl.prototype.markAsTouched = function() { + this._touched = true; + }; + AbstractControl.prototype.markAsDirty = function(_a) { + var onlySelf = (_a === void 0 ? {} : _a).onlySelf; + onlySelf = lang_1.normalizeBool(onlySelf); + this._pristine = false; + if (lang_1.isPresent(this._parent) && !onlySelf) { + this._parent.markAsDirty({onlySelf: onlySelf}); + } + }; + AbstractControl.prototype.markAsPending = function(_a) { + var onlySelf = (_a === void 0 ? {} : _a).onlySelf; + onlySelf = lang_1.normalizeBool(onlySelf); + this._status = exports.PENDING; + if (lang_1.isPresent(this._parent) && !onlySelf) { + this._parent.markAsPending({onlySelf: onlySelf}); + } + }; + AbstractControl.prototype.setParent = function(parent) { + this._parent = parent; + }; + AbstractControl.prototype.updateValueAndValidity = function(_a) { + var _b = _a === void 0 ? {} : _a, + onlySelf = _b.onlySelf, + emitEvent = _b.emitEvent; + onlySelf = lang_1.normalizeBool(onlySelf); + emitEvent = lang_1.isPresent(emitEvent) ? emitEvent : true; + this._updateValue(); + this._errors = this._runValidator(); + this._status = this._calculateStatus(); + if (this._status == exports.VALID || this._status == exports.PENDING) { + this._runAsyncValidator(emitEvent); + } + if (emitEvent) { + async_1.ObservableWrapper.callEmit(this._valueChanges, this._value); + async_1.ObservableWrapper.callEmit(this._statusChanges, this._status); + } + if (lang_1.isPresent(this._parent) && !onlySelf) { + this._parent.updateValueAndValidity({ + onlySelf: onlySelf, + emitEvent: emitEvent + }); + } + }; + AbstractControl.prototype._runValidator = function() { + return lang_1.isPresent(this.validator) ? this.validator(this) : null; + }; + AbstractControl.prototype._runAsyncValidator = function(emitEvent) { + var _this = this; + if (lang_1.isPresent(this.asyncValidator)) { + this._status = exports.PENDING; + this._cancelExistingSubscription(); + var obs = toObservable(this.asyncValidator(this)); + this._asyncValidationSubscription = async_1.ObservableWrapper.subscribe(obs, function(res) { + return _this.setErrors(res, {emitEvent: emitEvent}); + }); + } + }; + AbstractControl.prototype._cancelExistingSubscription = function() { + if (lang_1.isPresent(this._asyncValidationSubscription)) { + async_1.ObservableWrapper.dispose(this._asyncValidationSubscription); + } + }; + AbstractControl.prototype.setErrors = function(errors, _a) { + var emitEvent = (_a === void 0 ? {} : _a).emitEvent; + emitEvent = lang_1.isPresent(emitEvent) ? emitEvent : true; + this._errors = errors; + this._status = this._calculateStatus(); + if (emitEvent) { + async_1.ObservableWrapper.callEmit(this._statusChanges, this._status); + } + if (lang_1.isPresent(this._parent)) { + this._parent._updateControlsErrors(); + } + }; + AbstractControl.prototype.find = function(path) { + return _find(this, path); + }; + AbstractControl.prototype.getError = function(errorCode, path) { + if (path === void 0) { + path = null; + } + var control = lang_1.isPresent(path) && !collection_1.ListWrapper.isEmpty(path) ? this.find(path) : this; + if (lang_1.isPresent(control) && lang_1.isPresent(control._errors)) { + return collection_1.StringMapWrapper.get(control._errors, errorCode); + } else { + return null; + } + }; + AbstractControl.prototype.hasError = function(errorCode, path) { + if (path === void 0) { + path = null; + } + return lang_1.isPresent(this.getError(errorCode, path)); + }; + AbstractControl.prototype._updateControlsErrors = function() { + this._status = this._calculateStatus(); + if (lang_1.isPresent(this._parent)) { + this._parent._updateControlsErrors(); + } + }; + AbstractControl.prototype._initObservables = function() { + this._valueChanges = new async_1.EventEmitter(); + this._statusChanges = new async_1.EventEmitter(); + }; + AbstractControl.prototype._calculateStatus = function() { + if (lang_1.isPresent(this._errors)) + return exports.INVALID; + if (this._anyControlsHaveStatus(exports.PENDING)) + return exports.PENDING; + if (this._anyControlsHaveStatus(exports.INVALID)) + return exports.INVALID; + return exports.VALID; + }; + return AbstractControl; + })(); + exports.AbstractControl = AbstractControl; + var Control = (function(_super) { + __extends(Control, _super); + function Control(value, validator, asyncValidator) { + if (value === void 0) { + value = null; + } + if (validator === void 0) { + validator = null; + } + if (asyncValidator === void 0) { + asyncValidator = null; + } + _super.call(this, validator, asyncValidator); + this._value = value; + this.updateValueAndValidity({ + onlySelf: true, + emitEvent: false + }); + this._initObservables(); + } + Control.prototype.updateValue = function(value, _a) { + var _b = _a === void 0 ? {} : _a, + onlySelf = _b.onlySelf, + emitEvent = _b.emitEvent, + emitModelToViewChange = _b.emitModelToViewChange; + emitModelToViewChange = lang_1.isPresent(emitModelToViewChange) ? emitModelToViewChange : true; + this._value = value; + if (lang_1.isPresent(this._onChange) && emitModelToViewChange) + this._onChange(this._value); + this.updateValueAndValidity({ + onlySelf: onlySelf, + emitEvent: emitEvent + }); + }; + Control.prototype._updateValue = function() {}; + Control.prototype._anyControlsHaveStatus = function(status) { + return false; + }; + Control.prototype.registerOnChange = function(fn) { + this._onChange = fn; + }; + return Control; + })(AbstractControl); + exports.Control = Control; + var ControlGroup = (function(_super) { + __extends(ControlGroup, _super); + function ControlGroup(controls, optionals, validator, asyncValidator) { + if (optionals === void 0) { + optionals = null; + } + if (validator === void 0) { + validator = null; + } + if (asyncValidator === void 0) { + asyncValidator = null; + } + _super.call(this, validator, asyncValidator); + this.controls = controls; + this._optionals = lang_1.isPresent(optionals) ? optionals : {}; + this._initObservables(); + this._setParentForControls(); + this.updateValueAndValidity({ + onlySelf: true, + emitEvent: false + }); + } + ControlGroup.prototype.addControl = function(name, control) { + this.controls[name] = control; + control.setParent(this); + }; + ControlGroup.prototype.removeControl = function(name) { + collection_1.StringMapWrapper.delete(this.controls, name); + }; + ControlGroup.prototype.include = function(controlName) { + collection_1.StringMapWrapper.set(this._optionals, controlName, true); + this.updateValueAndValidity(); + }; + ControlGroup.prototype.exclude = function(controlName) { + collection_1.StringMapWrapper.set(this._optionals, controlName, false); + this.updateValueAndValidity(); + }; + ControlGroup.prototype.contains = function(controlName) { + var c = collection_1.StringMapWrapper.contains(this.controls, controlName); + return c && this._included(controlName); + }; + ControlGroup.prototype._setParentForControls = function() { + var _this = this; + collection_1.StringMapWrapper.forEach(this.controls, function(control, name) { + control.setParent(_this); + }); + }; + ControlGroup.prototype._updateValue = function() { + this._value = this._reduceValue(); + }; + ControlGroup.prototype._anyControlsHaveStatus = function(status) { + var _this = this; + var res = false; + collection_1.StringMapWrapper.forEach(this.controls, function(control, name) { + res = res || (_this.contains(name) && control.status == status); + }); + return res; + }; + ControlGroup.prototype._reduceValue = function() { + return this._reduceChildren({}, function(acc, control, name) { + acc[name] = control.value; + return acc; + }); + }; + ControlGroup.prototype._reduceChildren = function(initValue, fn) { + var _this = this; + var res = initValue; + collection_1.StringMapWrapper.forEach(this.controls, function(control, name) { + if (_this._included(name)) { + res = fn(res, control, name); + } + }); + return res; + }; + ControlGroup.prototype._included = function(controlName) { + var isOptional = collection_1.StringMapWrapper.contains(this._optionals, controlName); + return !isOptional || collection_1.StringMapWrapper.get(this._optionals, controlName); + }; + return ControlGroup; + })(AbstractControl); + exports.ControlGroup = ControlGroup; + var ControlArray = (function(_super) { + __extends(ControlArray, _super); + function ControlArray(controls, validator, asyncValidator) { + if (validator === void 0) { + validator = null; + } + if (asyncValidator === void 0) { + asyncValidator = null; + } + _super.call(this, validator, asyncValidator); + this.controls = controls; + this._initObservables(); + this._setParentForControls(); + this.updateValueAndValidity({ + onlySelf: true, + emitEvent: false + }); + } + ControlArray.prototype.at = function(index) { + return this.controls[index]; + }; + ControlArray.prototype.push = function(control) { + this.controls.push(control); + control.setParent(this); + this.updateValueAndValidity(); + }; + ControlArray.prototype.insert = function(index, control) { + collection_1.ListWrapper.insert(this.controls, index, control); + control.setParent(this); + this.updateValueAndValidity(); + }; + ControlArray.prototype.removeAt = function(index) { + collection_1.ListWrapper.removeAt(this.controls, index); + this.updateValueAndValidity(); + }; + Object.defineProperty(ControlArray.prototype, "length", { + get: function() { + return this.controls.length; + }, + enumerable: true, + configurable: true + }); + ControlArray.prototype._updateValue = function() { + this._value = this.controls.map(function(control) { + return control.value; + }); + }; + ControlArray.prototype._anyControlsHaveStatus = function(status) { + return this.controls.some(function(c) { + return c.status == status; + }); + }; + ControlArray.prototype._setParentForControls = function() { + var _this = this; + this.controls.forEach(function(control) { + control.setParent(_this); + }); + }; + return ControlArray; + })(AbstractControl); + exports.ControlArray = ControlArray; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/directives/abstract_control_directive", ["angular2/src/facade/lang", "angular2/src/facade/exceptions"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var AbstractControlDirective = (function() { + function AbstractControlDirective() {} + Object.defineProperty(AbstractControlDirective.prototype, "control", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbstractControlDirective.prototype, "value", { + get: function() { + return lang_1.isPresent(this.control) ? this.control.value : null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbstractControlDirective.prototype, "valid", { + get: function() { + return lang_1.isPresent(this.control) ? this.control.valid : null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbstractControlDirective.prototype, "errors", { + get: function() { + return lang_1.isPresent(this.control) ? this.control.errors : null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbstractControlDirective.prototype, "pristine", { + get: function() { + return lang_1.isPresent(this.control) ? this.control.pristine : null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbstractControlDirective.prototype, "dirty", { + get: function() { + return lang_1.isPresent(this.control) ? this.control.dirty : null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbstractControlDirective.prototype, "touched", { + get: function() { + return lang_1.isPresent(this.control) ? this.control.touched : null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbstractControlDirective.prototype, "untouched", { + get: function() { + return lang_1.isPresent(this.control) ? this.control.untouched : null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbstractControlDirective.prototype, "path", { + get: function() { + return null; + }, + enumerable: true, + configurable: true + }); + return AbstractControlDirective; + })(); + exports.AbstractControlDirective = AbstractControlDirective; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/directives/control_container", ["angular2/src/common/forms/directives/abstract_control_directive"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var abstract_control_directive_1 = require("angular2/src/common/forms/directives/abstract_control_directive"); + var ControlContainer = (function(_super) { + __extends(ControlContainer, _super); + function ControlContainer() { + _super.apply(this, arguments); + } + Object.defineProperty(ControlContainer.prototype, "formDirective", { + get: function() { + return null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ControlContainer.prototype, "path", { + get: function() { + return null; + }, + enumerable: true, + configurable: true + }); + return ControlContainer; + })(abstract_control_directive_1.AbstractControlDirective); + exports.ControlContainer = ControlContainer; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/directives/ng_control", ["angular2/src/common/forms/directives/abstract_control_directive", "angular2/src/facade/exceptions"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var abstract_control_directive_1 = require("angular2/src/common/forms/directives/abstract_control_directive"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var NgControl = (function(_super) { + __extends(NgControl, _super); + function NgControl() { + _super.apply(this, arguments); + this.name = null; + this.valueAccessor = null; + } + Object.defineProperty(NgControl.prototype, "validator", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgControl.prototype, "asyncValidator", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + return NgControl; + })(abstract_control_directive_1.AbstractControlDirective); + exports.NgControl = NgControl; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/directives/control_value_accessor", ["angular2/core", "angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var core_1 = require("angular2/core"); + var lang_1 = require("angular2/src/facade/lang"); + exports.NG_VALUE_ACCESSOR = lang_1.CONST_EXPR(new core_1.OpaqueToken("NgValueAccessor")); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/validators", ["angular2/src/facade/lang", "angular2/src/facade/promise", "angular2/src/facade/async", "angular2/src/facade/collection", "angular2/core"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var promise_1 = require("angular2/src/facade/promise"); + var async_1 = require("angular2/src/facade/async"); + var collection_1 = require("angular2/src/facade/collection"); + var core_1 = require("angular2/core"); + exports.NG_VALIDATORS = lang_1.CONST_EXPR(new core_1.OpaqueToken("NgValidators")); + exports.NG_ASYNC_VALIDATORS = lang_1.CONST_EXPR(new core_1.OpaqueToken("NgAsyncValidators")); + var Validators = (function() { + function Validators() {} + Validators.required = function(control) { + return lang_1.isBlank(control.value) || control.value == "" ? {"required": true} : null; + }; + Validators.minLength = function(minLength) { + return function(control) { + if (lang_1.isPresent(Validators.required(control))) + return null; + var v = control.value; + return v.length < minLength ? {"minlength": { + "requiredLength": minLength, + "actualLength": v.length + }} : null; + }; + }; + Validators.maxLength = function(maxLength) { + return function(control) { + if (lang_1.isPresent(Validators.required(control))) + return null; + var v = control.value; + return v.length > maxLength ? {"maxlength": { + "requiredLength": maxLength, + "actualLength": v.length + }} : null; + }; + }; + Validators.nullValidator = function(c) { + return null; + }; + Validators.compose = function(validators) { + if (lang_1.isBlank(validators)) + return null; + var presentValidators = validators.filter(lang_1.isPresent); + if (presentValidators.length == 0) + return null; + return function(control) { + return _mergeErrors(_executeValidators(control, presentValidators)); + }; + }; + Validators.composeAsync = function(validators) { + if (lang_1.isBlank(validators)) + return null; + var presentValidators = validators.filter(lang_1.isPresent); + if (presentValidators.length == 0) + return null; + return function(control) { + var promises = _executeValidators(control, presentValidators).map(_convertToPromise); + return promise_1.PromiseWrapper.all(promises).then(_mergeErrors); + }; + }; + return Validators; + })(); + exports.Validators = Validators; + function _convertToPromise(obj) { + return promise_1.PromiseWrapper.isPromise(obj) ? obj : async_1.ObservableWrapper.toPromise(obj); + } + function _executeValidators(control, validators) { + return validators.map(function(v) { + return v(control); + }); + } + function _mergeErrors(arrayOfErrors) { + var res = arrayOfErrors.reduce(function(res, errors) { + return lang_1.isPresent(errors) ? collection_1.StringMapWrapper.merge(res, errors) : res; + }, {}); + return collection_1.StringMapWrapper.isEmpty(res) ? null : res; + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/directives/default_value_accessor", ["angular2/core", "angular2/src/common/forms/directives/control_value_accessor", "angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var core_1 = require("angular2/core"); + var control_value_accessor_1 = require("angular2/src/common/forms/directives/control_value_accessor"); + var lang_1 = require("angular2/src/facade/lang"); + var DEFAULT_VALUE_ACCESSOR = lang_1.CONST_EXPR(new core_1.Provider(control_value_accessor_1.NG_VALUE_ACCESSOR, { + useExisting: core_1.forwardRef(function() { + return DefaultValueAccessor; + }), + multi: true + })); + var DefaultValueAccessor = (function() { + function DefaultValueAccessor(_renderer, _elementRef) { + this._renderer = _renderer; + this._elementRef = _elementRef; + this.onChange = function(_) {}; + this.onTouched = function() {}; + } + DefaultValueAccessor.prototype.writeValue = function(value) { + var normalizedValue = lang_1.isBlank(value) ? '' : value; + this._renderer.setElementProperty(this._elementRef, 'value', normalizedValue); + }; + DefaultValueAccessor.prototype.registerOnChange = function(fn) { + this.onChange = fn; + }; + DefaultValueAccessor.prototype.registerOnTouched = function(fn) { + this.onTouched = fn; + }; + DefaultValueAccessor = __decorate([core_1.Directive({ + selector: 'input:not([type=checkbox])[ngControl],textarea[ngControl],input:not([type=checkbox])[ngFormControl],textarea[ngFormControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]', + host: { + '(input)': 'onChange($event.target.value)', + '(blur)': 'onTouched()' + }, + bindings: [DEFAULT_VALUE_ACCESSOR] + }), __metadata('design:paramtypes', [core_1.Renderer, core_1.ElementRef])], DefaultValueAccessor); + return DefaultValueAccessor; + })(); + exports.DefaultValueAccessor = DefaultValueAccessor; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/directives/number_value_accessor", ["angular2/core", "angular2/src/common/forms/directives/control_value_accessor", "angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var core_1 = require("angular2/core"); + var control_value_accessor_1 = require("angular2/src/common/forms/directives/control_value_accessor"); + var lang_1 = require("angular2/src/facade/lang"); + var NUMBER_VALUE_ACCESSOR = lang_1.CONST_EXPR(new core_1.Provider(control_value_accessor_1.NG_VALUE_ACCESSOR, { + useExisting: core_1.forwardRef(function() { + return NumberValueAccessor; + }), + multi: true + })); + var NumberValueAccessor = (function() { + function NumberValueAccessor(_renderer, _elementRef) { + this._renderer = _renderer; + this._elementRef = _elementRef; + this.onChange = function(_) {}; + this.onTouched = function() {}; + } + NumberValueAccessor.prototype.writeValue = function(value) { + this._renderer.setElementProperty(this._elementRef, 'value', value); + }; + NumberValueAccessor.prototype.registerOnChange = function(fn) { + this.onChange = function(value) { + fn(lang_1.NumberWrapper.parseFloat(value)); + }; + }; + NumberValueAccessor.prototype.registerOnTouched = function(fn) { + this.onTouched = fn; + }; + NumberValueAccessor = __decorate([core_1.Directive({ + selector: 'input[type=number][ngControl],input[type=number][ngFormControl],input[type=number][ngModel]', + host: { + '(change)': 'onChange($event.target.value)', + '(input)': 'onChange($event.target.value)', + '(blur)': 'onTouched()' + }, + bindings: [NUMBER_VALUE_ACCESSOR] + }), __metadata('design:paramtypes', [core_1.Renderer, core_1.ElementRef])], NumberValueAccessor); + return NumberValueAccessor; + })(); + exports.NumberValueAccessor = NumberValueAccessor; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/directives/checkbox_value_accessor", ["angular2/core", "angular2/src/common/forms/directives/control_value_accessor", "angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var core_1 = require("angular2/core"); + var control_value_accessor_1 = require("angular2/src/common/forms/directives/control_value_accessor"); + var lang_1 = require("angular2/src/facade/lang"); + var CHECKBOX_VALUE_ACCESSOR = lang_1.CONST_EXPR(new core_1.Provider(control_value_accessor_1.NG_VALUE_ACCESSOR, { + useExisting: core_1.forwardRef(function() { + return CheckboxControlValueAccessor; + }), + multi: true + })); + var CheckboxControlValueAccessor = (function() { + function CheckboxControlValueAccessor(_renderer, _elementRef) { + this._renderer = _renderer; + this._elementRef = _elementRef; + this.onChange = function(_) {}; + this.onTouched = function() {}; + } + CheckboxControlValueAccessor.prototype.writeValue = function(value) { + this._renderer.setElementProperty(this._elementRef, 'checked', value); + }; + CheckboxControlValueAccessor.prototype.registerOnChange = function(fn) { + this.onChange = fn; + }; + CheckboxControlValueAccessor.prototype.registerOnTouched = function(fn) { + this.onTouched = fn; + }; + CheckboxControlValueAccessor = __decorate([core_1.Directive({ + selector: 'input[type=checkbox][ngControl],input[type=checkbox][ngFormControl],input[type=checkbox][ngModel]', + host: { + '(change)': 'onChange($event.target.checked)', + '(blur)': 'onTouched()' + }, + bindings: [CHECKBOX_VALUE_ACCESSOR] + }), __metadata('design:paramtypes', [core_1.Renderer, core_1.ElementRef])], CheckboxControlValueAccessor); + return CheckboxControlValueAccessor; + })(); + exports.CheckboxControlValueAccessor = CheckboxControlValueAccessor; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/directives/select_control_value_accessor", ["angular2/core", "angular2/src/facade/async", "angular2/src/common/forms/directives/control_value_accessor", "angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var core_1 = require("angular2/core"); + var async_1 = require("angular2/src/facade/async"); + var control_value_accessor_1 = require("angular2/src/common/forms/directives/control_value_accessor"); + var lang_1 = require("angular2/src/facade/lang"); + var SELECT_VALUE_ACCESSOR = lang_1.CONST_EXPR(new core_1.Provider(control_value_accessor_1.NG_VALUE_ACCESSOR, { + useExisting: core_1.forwardRef(function() { + return SelectControlValueAccessor; + }), + multi: true + })); + var NgSelectOption = (function() { + function NgSelectOption() {} + NgSelectOption = __decorate([core_1.Directive({selector: 'option'}), __metadata('design:paramtypes', [])], NgSelectOption); + return NgSelectOption; + })(); + exports.NgSelectOption = NgSelectOption; + var SelectControlValueAccessor = (function() { + function SelectControlValueAccessor(_renderer, _elementRef, query) { + this._renderer = _renderer; + this._elementRef = _elementRef; + this.onChange = function(_) {}; + this.onTouched = function() {}; + this._updateValueWhenListOfOptionsChanges(query); + } + SelectControlValueAccessor.prototype.writeValue = function(value) { + this.value = value; + this._renderer.setElementProperty(this._elementRef, 'value', value); + }; + SelectControlValueAccessor.prototype.registerOnChange = function(fn) { + this.onChange = fn; + }; + SelectControlValueAccessor.prototype.registerOnTouched = function(fn) { + this.onTouched = fn; + }; + SelectControlValueAccessor.prototype._updateValueWhenListOfOptionsChanges = function(query) { + var _this = this; + async_1.ObservableWrapper.subscribe(query.changes, function(_) { + return _this.writeValue(_this.value); + }); + }; + SelectControlValueAccessor = __decorate([core_1.Directive({ + selector: 'select[ngControl],select[ngFormControl],select[ngModel]', + host: { + '(change)': 'onChange($event.target.value)', + '(input)': 'onChange($event.target.value)', + '(blur)': 'onTouched()' + }, + bindings: [SELECT_VALUE_ACCESSOR] + }), __param(2, core_1.Query(NgSelectOption, {descendants: true})), __metadata('design:paramtypes', [core_1.Renderer, core_1.ElementRef, core_1.QueryList])], SelectControlValueAccessor); + return SelectControlValueAccessor; + })(); + exports.SelectControlValueAccessor = SelectControlValueAccessor; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/directives/normalize_validator", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function normalizeValidator(validator) { + if (validator.validate !== undefined) { + return function(c) { + return validator.validate(c); + }; + } else { + return validator; + } + } + exports.normalizeValidator = normalizeValidator; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/directives/ng_form_control", ["angular2/src/facade/lang", "angular2/src/facade/collection", "angular2/src/facade/async", "angular2/core", "angular2/src/common/forms/directives/ng_control", "angular2/src/common/forms/validators", "angular2/src/common/forms/directives/control_value_accessor", "angular2/src/common/forms/directives/shared"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var lang_1 = require("angular2/src/facade/lang"); + var collection_1 = require("angular2/src/facade/collection"); + var async_1 = require("angular2/src/facade/async"); + var core_1 = require("angular2/core"); + var ng_control_1 = require("angular2/src/common/forms/directives/ng_control"); + var validators_1 = require("angular2/src/common/forms/validators"); + var control_value_accessor_1 = require("angular2/src/common/forms/directives/control_value_accessor"); + var shared_1 = require("angular2/src/common/forms/directives/shared"); + var formControlBinding = lang_1.CONST_EXPR(new core_1.Provider(ng_control_1.NgControl, {useExisting: core_1.forwardRef(function() { + return NgFormControl; + })})); + var NgFormControl = (function(_super) { + __extends(NgFormControl, _super); + function NgFormControl(_validators, _asyncValidators, valueAccessors) { + _super.call(this); + this._validators = _validators; + this._asyncValidators = _asyncValidators; + this.update = new async_1.EventEmitter(); + this.valueAccessor = shared_1.selectValueAccessor(this, valueAccessors); + } + NgFormControl.prototype.ngOnChanges = function(changes) { + if (this._isControlChanged(changes)) { + shared_1.setUpControl(this.form, this); + this.form.updateValueAndValidity({emitEvent: false}); + } + if (shared_1.isPropertyUpdated(changes, this.viewModel)) { + this.form.updateValue(this.model); + this.viewModel = this.model; + } + }; + Object.defineProperty(NgFormControl.prototype, "path", { + get: function() { + return []; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgFormControl.prototype, "validator", { + get: function() { + return shared_1.composeValidators(this._validators); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgFormControl.prototype, "asyncValidator", { + get: function() { + return shared_1.composeAsyncValidators(this._asyncValidators); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgFormControl.prototype, "control", { + get: function() { + return this.form; + }, + enumerable: true, + configurable: true + }); + NgFormControl.prototype.viewToModelUpdate = function(newValue) { + this.viewModel = newValue; + async_1.ObservableWrapper.callEmit(this.update, newValue); + }; + NgFormControl.prototype._isControlChanged = function(changes) { + return collection_1.StringMapWrapper.contains(changes, "form"); + }; + NgFormControl = __decorate([core_1.Directive({ + selector: '[ngFormControl]', + bindings: [formControlBinding], + inputs: ['form: ngFormControl', 'model: ngModel'], + outputs: ['update: ngModelChange'], + exportAs: 'ngForm' + }), __param(0, core_1.Optional()), __param(0, core_1.Self()), __param(0, core_1.Inject(validators_1.NG_VALIDATORS)), __param(1, core_1.Optional()), __param(1, core_1.Self()), __param(1, core_1.Inject(validators_1.NG_ASYNC_VALIDATORS)), __param(2, core_1.Optional()), __param(2, core_1.Self()), __param(2, core_1.Inject(control_value_accessor_1.NG_VALUE_ACCESSOR)), __metadata('design:paramtypes', [Array, Array, Array])], NgFormControl); + return NgFormControl; + })(ng_control_1.NgControl); + exports.NgFormControl = NgFormControl; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/directives/ng_model", ["angular2/src/facade/lang", "angular2/src/facade/async", "angular2/core", "angular2/src/common/forms/directives/control_value_accessor", "angular2/src/common/forms/directives/ng_control", "angular2/src/common/forms/model", "angular2/src/common/forms/validators", "angular2/src/common/forms/directives/shared"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var lang_1 = require("angular2/src/facade/lang"); + var async_1 = require("angular2/src/facade/async"); + var core_1 = require("angular2/core"); + var control_value_accessor_1 = require("angular2/src/common/forms/directives/control_value_accessor"); + var ng_control_1 = require("angular2/src/common/forms/directives/ng_control"); + var model_1 = require("angular2/src/common/forms/model"); + var validators_1 = require("angular2/src/common/forms/validators"); + var shared_1 = require("angular2/src/common/forms/directives/shared"); + var formControlBinding = lang_1.CONST_EXPR(new core_1.Provider(ng_control_1.NgControl, {useExisting: core_1.forwardRef(function() { + return NgModel; + })})); + var NgModel = (function(_super) { + __extends(NgModel, _super); + function NgModel(_validators, _asyncValidators, valueAccessors) { + _super.call(this); + this._validators = _validators; + this._asyncValidators = _asyncValidators; + this._control = new model_1.Control(); + this._added = false; + this.update = new async_1.EventEmitter(); + this.valueAccessor = shared_1.selectValueAccessor(this, valueAccessors); + } + NgModel.prototype.ngOnChanges = function(changes) { + if (!this._added) { + shared_1.setUpControl(this._control, this); + this._control.updateValueAndValidity({emitEvent: false}); + this._added = true; + } + if (shared_1.isPropertyUpdated(changes, this.viewModel)) { + this._control.updateValue(this.model); + this.viewModel = this.model; + } + }; + Object.defineProperty(NgModel.prototype, "control", { + get: function() { + return this._control; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgModel.prototype, "path", { + get: function() { + return []; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgModel.prototype, "validator", { + get: function() { + return shared_1.composeValidators(this._validators); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgModel.prototype, "asyncValidator", { + get: function() { + return shared_1.composeAsyncValidators(this._asyncValidators); + }, + enumerable: true, + configurable: true + }); + NgModel.prototype.viewToModelUpdate = function(newValue) { + this.viewModel = newValue; + async_1.ObservableWrapper.callEmit(this.update, newValue); + }; + NgModel = __decorate([core_1.Directive({ + selector: '[ngModel]:not([ngControl]):not([ngFormControl])', + bindings: [formControlBinding], + inputs: ['model: ngModel'], + outputs: ['update: ngModelChange'], + exportAs: 'ngForm' + }), __param(0, core_1.Optional()), __param(0, core_1.Self()), __param(0, core_1.Inject(validators_1.NG_VALIDATORS)), __param(1, core_1.Optional()), __param(1, core_1.Self()), __param(1, core_1.Inject(validators_1.NG_ASYNC_VALIDATORS)), __param(2, core_1.Optional()), __param(2, core_1.Self()), __param(2, core_1.Inject(control_value_accessor_1.NG_VALUE_ACCESSOR)), __metadata('design:paramtypes', [Array, Array, Array])], NgModel); + return NgModel; + })(ng_control_1.NgControl); + exports.NgModel = NgModel; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/directives/ng_control_group", ["angular2/core", "angular2/src/facade/lang", "angular2/src/common/forms/directives/control_container", "angular2/src/common/forms/directives/shared", "angular2/src/common/forms/validators"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var core_1 = require("angular2/core"); + var lang_1 = require("angular2/src/facade/lang"); + var control_container_1 = require("angular2/src/common/forms/directives/control_container"); + var shared_1 = require("angular2/src/common/forms/directives/shared"); + var validators_1 = require("angular2/src/common/forms/validators"); + var controlGroupProvider = lang_1.CONST_EXPR(new core_1.Provider(control_container_1.ControlContainer, {useExisting: core_1.forwardRef(function() { + return NgControlGroup; + })})); + var NgControlGroup = (function(_super) { + __extends(NgControlGroup, _super); + function NgControlGroup(parent, _validators, _asyncValidators) { + _super.call(this); + this._validators = _validators; + this._asyncValidators = _asyncValidators; + this._parent = parent; + } + NgControlGroup.prototype.ngOnInit = function() { + this.formDirective.addControlGroup(this); + }; + NgControlGroup.prototype.ngOnDestroy = function() { + this.formDirective.removeControlGroup(this); + }; + Object.defineProperty(NgControlGroup.prototype, "control", { + get: function() { + return this.formDirective.getControlGroup(this); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgControlGroup.prototype, "path", { + get: function() { + return shared_1.controlPath(this.name, this._parent); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgControlGroup.prototype, "formDirective", { + get: function() { + return this._parent.formDirective; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgControlGroup.prototype, "validator", { + get: function() { + return shared_1.composeValidators(this._validators); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgControlGroup.prototype, "asyncValidator", { + get: function() { + return shared_1.composeAsyncValidators(this._asyncValidators); + }, + enumerable: true, + configurable: true + }); + NgControlGroup = __decorate([core_1.Directive({ + selector: '[ngControlGroup]', + providers: [controlGroupProvider], + inputs: ['name: ngControlGroup'], + exportAs: 'ngForm' + }), __param(0, core_1.Host()), __param(0, core_1.SkipSelf()), __param(1, core_1.Optional()), __param(1, core_1.Self()), __param(1, core_1.Inject(validators_1.NG_VALIDATORS)), __param(2, core_1.Optional()), __param(2, core_1.Self()), __param(2, core_1.Inject(validators_1.NG_ASYNC_VALIDATORS)), __metadata('design:paramtypes', [control_container_1.ControlContainer, Array, Array])], NgControlGroup); + return NgControlGroup; + })(control_container_1.ControlContainer); + exports.NgControlGroup = NgControlGroup; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/directives/ng_form_model", ["angular2/src/facade/lang", "angular2/src/facade/collection", "angular2/src/facade/async", "angular2/core", "angular2/src/common/forms/directives/control_container", "angular2/src/common/forms/directives/shared", "angular2/src/common/forms/validators"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var lang_1 = require("angular2/src/facade/lang"); + var collection_1 = require("angular2/src/facade/collection"); + var async_1 = require("angular2/src/facade/async"); + var core_1 = require("angular2/core"); + var control_container_1 = require("angular2/src/common/forms/directives/control_container"); + var shared_1 = require("angular2/src/common/forms/directives/shared"); + var validators_1 = require("angular2/src/common/forms/validators"); + var formDirectiveProvider = lang_1.CONST_EXPR(new core_1.Provider(control_container_1.ControlContainer, {useExisting: core_1.forwardRef(function() { + return NgFormModel; + })})); + var NgFormModel = (function(_super) { + __extends(NgFormModel, _super); + function NgFormModel(_validators, _asyncValidators) { + _super.call(this); + this._validators = _validators; + this._asyncValidators = _asyncValidators; + this.form = null; + this.directives = []; + this.ngSubmit = new async_1.EventEmitter(); + } + NgFormModel.prototype.ngOnChanges = function(changes) { + if (collection_1.StringMapWrapper.contains(changes, "form")) { + var sync = shared_1.composeValidators(this._validators); + this.form.validator = validators_1.Validators.compose([this.form.validator, sync]); + var async = shared_1.composeAsyncValidators(this._asyncValidators); + this.form.asyncValidator = validators_1.Validators.composeAsync([this.form.asyncValidator, async]); + this.form.updateValueAndValidity({ + onlySelf: true, + emitEvent: false + }); + } + this._updateDomValue(); + }; + Object.defineProperty(NgFormModel.prototype, "formDirective", { + get: function() { + return this; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgFormModel.prototype, "control", { + get: function() { + return this.form; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgFormModel.prototype, "path", { + get: function() { + return []; + }, + enumerable: true, + configurable: true + }); + NgFormModel.prototype.addControl = function(dir) { + var ctrl = this.form.find(dir.path); + shared_1.setUpControl(ctrl, dir); + ctrl.updateValueAndValidity({emitEvent: false}); + this.directives.push(dir); + }; + NgFormModel.prototype.getControl = function(dir) { + return this.form.find(dir.path); + }; + NgFormModel.prototype.removeControl = function(dir) { + collection_1.ListWrapper.remove(this.directives, dir); + }; + NgFormModel.prototype.addControlGroup = function(dir) { + var ctrl = this.form.find(dir.path); + shared_1.setUpControlGroup(ctrl, dir); + ctrl.updateValueAndValidity({emitEvent: false}); + }; + NgFormModel.prototype.removeControlGroup = function(dir) {}; + NgFormModel.prototype.getControlGroup = function(dir) { + return this.form.find(dir.path); + }; + NgFormModel.prototype.updateModel = function(dir, value) { + var ctrl = this.form.find(dir.path); + ctrl.updateValue(value); + }; + NgFormModel.prototype.onSubmit = function() { + async_1.ObservableWrapper.callEmit(this.ngSubmit, null); + return false; + }; + NgFormModel.prototype._updateDomValue = function() { + var _this = this; + this.directives.forEach(function(dir) { + var ctrl = _this.form.find(dir.path); + dir.valueAccessor.writeValue(ctrl.value); + }); + }; + NgFormModel = __decorate([core_1.Directive({ + selector: '[ngFormModel]', + bindings: [formDirectiveProvider], + inputs: ['form: ngFormModel'], + host: {'(submit)': 'onSubmit()'}, + outputs: ['ngSubmit'], + exportAs: 'ngForm' + }), __param(0, core_1.Optional()), __param(0, core_1.Self()), __param(0, core_1.Inject(validators_1.NG_VALIDATORS)), __param(1, core_1.Optional()), __param(1, core_1.Self()), __param(1, core_1.Inject(validators_1.NG_ASYNC_VALIDATORS)), __metadata('design:paramtypes', [Array, Array])], NgFormModel); + return NgFormModel; + })(control_container_1.ControlContainer); + exports.NgFormModel = NgFormModel; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/directives/ng_form", ["angular2/src/facade/async", "angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/core", "angular2/src/common/forms/directives/control_container", "angular2/src/common/forms/model", "angular2/src/common/forms/directives/shared", "angular2/src/common/forms/validators"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var async_1 = require("angular2/src/facade/async"); + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var core_1 = require("angular2/core"); + var control_container_1 = require("angular2/src/common/forms/directives/control_container"); + var model_1 = require("angular2/src/common/forms/model"); + var shared_1 = require("angular2/src/common/forms/directives/shared"); + var validators_1 = require("angular2/src/common/forms/validators"); + var formDirectiveProvider = lang_1.CONST_EXPR(new core_1.Provider(control_container_1.ControlContainer, {useExisting: core_1.forwardRef(function() { + return NgForm; + })})); + var NgForm = (function(_super) { + __extends(NgForm, _super); + function NgForm(validators, asyncValidators) { + _super.call(this); + this.ngSubmit = new async_1.EventEmitter(); + this.form = new model_1.ControlGroup({}, null, shared_1.composeValidators(validators), shared_1.composeAsyncValidators(asyncValidators)); + } + Object.defineProperty(NgForm.prototype, "formDirective", { + get: function() { + return this; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgForm.prototype, "control", { + get: function() { + return this.form; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgForm.prototype, "path", { + get: function() { + return []; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgForm.prototype, "controls", { + get: function() { + return this.form.controls; + }, + enumerable: true, + configurable: true + }); + NgForm.prototype.addControl = function(dir) { + var _this = this; + async_1.PromiseWrapper.scheduleMicrotask(function() { + var container = _this._findContainer(dir.path); + var ctrl = new model_1.Control(); + shared_1.setUpControl(ctrl, dir); + container.addControl(dir.name, ctrl); + ctrl.updateValueAndValidity({emitEvent: false}); + }); + }; + NgForm.prototype.getControl = function(dir) { + return this.form.find(dir.path); + }; + NgForm.prototype.removeControl = function(dir) { + var _this = this; + async_1.PromiseWrapper.scheduleMicrotask(function() { + var container = _this._findContainer(dir.path); + if (lang_1.isPresent(container)) { + container.removeControl(dir.name); + container.updateValueAndValidity({emitEvent: false}); + } + }); + }; + NgForm.prototype.addControlGroup = function(dir) { + var _this = this; + async_1.PromiseWrapper.scheduleMicrotask(function() { + var container = _this._findContainer(dir.path); + var group = new model_1.ControlGroup({}); + shared_1.setUpControlGroup(group, dir); + container.addControl(dir.name, group); + group.updateValueAndValidity({emitEvent: false}); + }); + }; + NgForm.prototype.removeControlGroup = function(dir) { + var _this = this; + async_1.PromiseWrapper.scheduleMicrotask(function() { + var container = _this._findContainer(dir.path); + if (lang_1.isPresent(container)) { + container.removeControl(dir.name); + container.updateValueAndValidity({emitEvent: false}); + } + }); + }; + NgForm.prototype.getControlGroup = function(dir) { + return this.form.find(dir.path); + }; + NgForm.prototype.updateModel = function(dir, value) { + var _this = this; + async_1.PromiseWrapper.scheduleMicrotask(function() { + var ctrl = _this.form.find(dir.path); + ctrl.updateValue(value); + }); + }; + NgForm.prototype.onSubmit = function() { + async_1.ObservableWrapper.callEmit(this.ngSubmit, null); + return false; + }; + NgForm.prototype._findContainer = function(path) { + path.pop(); + return collection_1.ListWrapper.isEmpty(path) ? this.form : this.form.find(path); + }; + NgForm = __decorate([core_1.Directive({ + selector: 'form:not([ngNoForm]):not([ngFormModel]),ngForm,[ngForm]', + bindings: [formDirectiveProvider], + host: {'(submit)': 'onSubmit()'}, + outputs: ['ngSubmit'], + exportAs: 'ngForm' + }), __param(0, core_1.Optional()), __param(0, core_1.Self()), __param(0, core_1.Inject(validators_1.NG_VALIDATORS)), __param(1, core_1.Optional()), __param(1, core_1.Self()), __param(1, core_1.Inject(validators_1.NG_ASYNC_VALIDATORS)), __metadata('design:paramtypes', [Array, Array])], NgForm); + return NgForm; + })(control_container_1.ControlContainer); + exports.NgForm = NgForm; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/directives/ng_control_status", ["angular2/core", "angular2/src/common/forms/directives/ng_control", "angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var core_1 = require("angular2/core"); + var ng_control_1 = require("angular2/src/common/forms/directives/ng_control"); + var lang_1 = require("angular2/src/facade/lang"); + var NgControlStatus = (function() { + function NgControlStatus(cd) { + this._cd = cd; + } + Object.defineProperty(NgControlStatus.prototype, "ngClassUntouched", { + get: function() { + return lang_1.isPresent(this._cd.control) ? this._cd.control.untouched : false; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgControlStatus.prototype, "ngClassTouched", { + get: function() { + return lang_1.isPresent(this._cd.control) ? this._cd.control.touched : false; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgControlStatus.prototype, "ngClassPristine", { + get: function() { + return lang_1.isPresent(this._cd.control) ? this._cd.control.pristine : false; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgControlStatus.prototype, "ngClassDirty", { + get: function() { + return lang_1.isPresent(this._cd.control) ? this._cd.control.dirty : false; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgControlStatus.prototype, "ngClassValid", { + get: function() { + return lang_1.isPresent(this._cd.control) ? this._cd.control.valid : false; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgControlStatus.prototype, "ngClassInvalid", { + get: function() { + return lang_1.isPresent(this._cd.control) ? !this._cd.control.valid : false; + }, + enumerable: true, + configurable: true + }); + NgControlStatus = __decorate([core_1.Directive({ + selector: '[ngControl],[ngModel],[ngFormControl]', + host: { + '[class.ng-untouched]': 'ngClassUntouched', + '[class.ng-touched]': 'ngClassTouched', + '[class.ng-pristine]': 'ngClassPristine', + '[class.ng-dirty]': 'ngClassDirty', + '[class.ng-valid]': 'ngClassValid', + '[class.ng-invalid]': 'ngClassInvalid' + } + }), __param(0, core_1.Self()), __metadata('design:paramtypes', [ng_control_1.NgControl])], NgControlStatus); + return NgControlStatus; + })(); + exports.NgControlStatus = NgControlStatus; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/directives/validators", ["angular2/core", "angular2/src/facade/lang", "angular2/src/common/forms/validators", "angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var core_1 = require("angular2/core"); + var lang_1 = require("angular2/src/facade/lang"); + var validators_1 = require("angular2/src/common/forms/validators"); + var lang_2 = require("angular2/src/facade/lang"); + var REQUIRED_VALIDATOR = lang_1.CONST_EXPR(new core_1.Provider(validators_1.NG_VALIDATORS, { + useValue: validators_1.Validators.required, + multi: true + })); + var RequiredValidator = (function() { + function RequiredValidator() {} + RequiredValidator = __decorate([core_1.Directive({ + selector: '[required][ngControl],[required][ngFormControl],[required][ngModel]', + providers: [REQUIRED_VALIDATOR] + }), __metadata('design:paramtypes', [])], RequiredValidator); + return RequiredValidator; + })(); + exports.RequiredValidator = RequiredValidator; + var MIN_LENGTH_VALIDATOR = lang_1.CONST_EXPR(new core_1.Provider(validators_1.NG_VALIDATORS, { + useExisting: core_1.forwardRef(function() { + return MinLengthValidator; + }), + multi: true + })); + var MinLengthValidator = (function() { + function MinLengthValidator(minLength) { + this._validator = validators_1.Validators.minLength(lang_2.NumberWrapper.parseInt(minLength, 10)); + } + MinLengthValidator.prototype.validate = function(c) { + return this._validator(c); + }; + MinLengthValidator = __decorate([core_1.Directive({ + selector: '[minlength][ngControl],[minlength][ngFormControl],[minlength][ngModel]', + providers: [MIN_LENGTH_VALIDATOR] + }), __param(0, core_1.Attribute("minlength")), __metadata('design:paramtypes', [String])], MinLengthValidator); + return MinLengthValidator; + })(); + exports.MinLengthValidator = MinLengthValidator; + var MAX_LENGTH_VALIDATOR = lang_1.CONST_EXPR(new core_1.Provider(validators_1.NG_VALIDATORS, { + useExisting: core_1.forwardRef(function() { + return MaxLengthValidator; + }), + multi: true + })); + var MaxLengthValidator = (function() { + function MaxLengthValidator(maxLength) { + this._validator = validators_1.Validators.maxLength(lang_2.NumberWrapper.parseInt(maxLength, 10)); + } + MaxLengthValidator.prototype.validate = function(c) { + return this._validator(c); + }; + MaxLengthValidator = __decorate([core_1.Directive({ + selector: '[maxlength][ngControl],[maxlength][ngFormControl],[maxlength][ngModel]', + providers: [MAX_LENGTH_VALIDATOR] + }), __param(0, core_1.Attribute("maxlength")), __metadata('design:paramtypes', [String])], MaxLengthValidator); + return MaxLengthValidator; + })(); + exports.MaxLengthValidator = MaxLengthValidator; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/form_builder", ["angular2/core", "angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/common/forms/model"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var core_1 = require("angular2/core"); + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var modelModule = require("angular2/src/common/forms/model"); + var FormBuilder = (function() { + function FormBuilder() {} + FormBuilder.prototype.group = function(controlsConfig, extra) { + if (extra === void 0) { + extra = null; + } + var controls = this._reduceControls(controlsConfig); + var optionals = lang_1.isPresent(extra) ? collection_1.StringMapWrapper.get(extra, "optionals") : null; + var validator = lang_1.isPresent(extra) ? collection_1.StringMapWrapper.get(extra, "validator") : null; + var asyncValidator = lang_1.isPresent(extra) ? collection_1.StringMapWrapper.get(extra, "asyncValidator") : null; + return new modelModule.ControlGroup(controls, optionals, validator, asyncValidator); + }; + FormBuilder.prototype.control = function(value, validator, asyncValidator) { + if (validator === void 0) { + validator = null; + } + if (asyncValidator === void 0) { + asyncValidator = null; + } + return new modelModule.Control(value, validator, asyncValidator); + }; + FormBuilder.prototype.array = function(controlsConfig, validator, asyncValidator) { + var _this = this; + if (validator === void 0) { + validator = null; + } + if (asyncValidator === void 0) { + asyncValidator = null; + } + var controls = controlsConfig.map(function(c) { + return _this._createControl(c); + }); + return new modelModule.ControlArray(controls, validator, asyncValidator); + }; + FormBuilder.prototype._reduceControls = function(controlsConfig) { + var _this = this; + var controls = {}; + collection_1.StringMapWrapper.forEach(controlsConfig, function(controlConfig, controlName) { + controls[controlName] = _this._createControl(controlConfig); + }); + return controls; + }; + FormBuilder.prototype._createControl = function(controlConfig) { + if (controlConfig instanceof modelModule.Control || controlConfig instanceof modelModule.ControlGroup || controlConfig instanceof modelModule.ControlArray) { + return controlConfig; + } else if (lang_1.isArray(controlConfig)) { + var value = controlConfig[0]; + var validator = controlConfig.length > 1 ? controlConfig[1] : null; + var asyncValidator = controlConfig.length > 2 ? controlConfig[2] : null; + return this.control(value, validator, asyncValidator); + } else { + return this.control(controlConfig); + } + }; + FormBuilder = __decorate([core_1.Injectable(), __metadata('design:paramtypes', [])], FormBuilder); + return FormBuilder; + })(); + exports.FormBuilder = FormBuilder; + exports.FORM_PROVIDERS = lang_1.CONST_EXPR([FormBuilder]); + exports.FORM_BINDINGS = exports.FORM_PROVIDERS; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/common_directives", ["angular2/src/facade/lang", "angular2/src/common/forms", "angular2/src/common/directives"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var forms_1 = require("angular2/src/common/forms"); + var directives_1 = require("angular2/src/common/directives"); + exports.COMMON_DIRECTIVES = lang_1.CONST_EXPR([directives_1.CORE_DIRECTIVES, forms_1.FORM_DIRECTIVES]); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/dom/events/key_events", ["angular2/src/platform/dom/dom_adapter", "angular2/src/facade/lang", "angular2/src/facade/collection", "angular2/src/platform/dom/events/event_manager", "angular2/src/core/di"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); + var lang_1 = require("angular2/src/facade/lang"); + var collection_1 = require("angular2/src/facade/collection"); + var event_manager_1 = require("angular2/src/platform/dom/events/event_manager"); + var di_1 = require("angular2/src/core/di"); + var modifierKeys = ['alt', 'control', 'meta', 'shift']; + var modifierKeyGetters = { + 'alt': function(event) { + return event.altKey; + }, + 'control': function(event) { + return event.ctrlKey; + }, + 'meta': function(event) { + return event.metaKey; + }, + 'shift': function(event) { + return event.shiftKey; + } + }; + var KeyEventsPlugin = (function(_super) { + __extends(KeyEventsPlugin, _super); + function KeyEventsPlugin() { + _super.call(this); + } + KeyEventsPlugin.prototype.supports = function(eventName) { + return lang_1.isPresent(KeyEventsPlugin.parseEventName(eventName)); + }; + KeyEventsPlugin.prototype.addEventListener = function(element, eventName, handler) { + var parsedEvent = KeyEventsPlugin.parseEventName(eventName); + var outsideHandler = KeyEventsPlugin.eventCallback(element, collection_1.StringMapWrapper.get(parsedEvent, 'fullKey'), handler, this.manager.getZone()); + this.manager.getZone().runOutsideAngular(function() { + dom_adapter_1.DOM.on(element, collection_1.StringMapWrapper.get(parsedEvent, 'domEventName'), outsideHandler); + }); + }; + KeyEventsPlugin.parseEventName = function(eventName) { + var parts = eventName.toLowerCase().split('.'); + var domEventName = parts.shift(); + if ((parts.length === 0) || !(lang_1.StringWrapper.equals(domEventName, 'keydown') || lang_1.StringWrapper.equals(domEventName, 'keyup'))) { + return null; + } + var key = KeyEventsPlugin._normalizeKey(parts.pop()); + var fullKey = ''; + modifierKeys.forEach(function(modifierName) { + if (collection_1.ListWrapper.contains(parts, modifierName)) { + collection_1.ListWrapper.remove(parts, modifierName); + fullKey += modifierName + '.'; + } + }); + fullKey += key; + if (parts.length != 0 || key.length === 0) { + return null; + } + var result = collection_1.StringMapWrapper.create(); + collection_1.StringMapWrapper.set(result, 'domEventName', domEventName); + collection_1.StringMapWrapper.set(result, 'fullKey', fullKey); + return result; + }; + KeyEventsPlugin.getEventFullKey = function(event) { + var fullKey = ''; + var key = dom_adapter_1.DOM.getEventKey(event); + key = key.toLowerCase(); + if (lang_1.StringWrapper.equals(key, ' ')) { + key = 'space'; + } else if (lang_1.StringWrapper.equals(key, '.')) { + key = 'dot'; + } + modifierKeys.forEach(function(modifierName) { + if (modifierName != key) { + var modifierGetter = collection_1.StringMapWrapper.get(modifierKeyGetters, modifierName); + if (modifierGetter(event)) { + fullKey += modifierName + '.'; + } + } + }); + fullKey += key; + return fullKey; + }; + KeyEventsPlugin.eventCallback = function(element, fullKey, handler, zone) { + return function(event) { + if (lang_1.StringWrapper.equals(KeyEventsPlugin.getEventFullKey(event), fullKey)) { + zone.run(function() { + return handler(event); + }); + } + }; + }; + KeyEventsPlugin._normalizeKey = function(keyName) { + switch (keyName) { + case 'esc': + return 'escape'; + default: + return keyName; + } + }; + KeyEventsPlugin = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], KeyEventsPlugin); + return KeyEventsPlugin; + })(event_manager_1.EventManagerPlugin); + exports.KeyEventsPlugin = KeyEventsPlugin; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/dom/events/hammer_common", ["angular2/src/platform/dom/events/event_manager", "angular2/src/facade/collection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var event_manager_1 = require("angular2/src/platform/dom/events/event_manager"); + var collection_1 = require("angular2/src/facade/collection"); + var _eventNames = { + 'pan': true, + 'panstart': true, + 'panmove': true, + 'panend': true, + 'pancancel': true, + 'panleft': true, + 'panright': true, + 'panup': true, + 'pandown': true, + 'pinch': true, + 'pinchstart': true, + 'pinchmove': true, + 'pinchend': true, + 'pinchcancel': true, + 'pinchin': true, + 'pinchout': true, + 'press': true, + 'pressup': true, + 'rotate': true, + 'rotatestart': true, + 'rotatemove': true, + 'rotateend': true, + 'rotatecancel': true, + 'swipe': true, + 'swipeleft': true, + 'swiperight': true, + 'swipeup': true, + 'swipedown': true, + 'tap': true + }; + var HammerGesturesPluginCommon = (function(_super) { + __extends(HammerGesturesPluginCommon, _super); + function HammerGesturesPluginCommon() { + _super.call(this); + } + HammerGesturesPluginCommon.prototype.supports = function(eventName) { + eventName = eventName.toLowerCase(); + return collection_1.StringMapWrapper.contains(_eventNames, eventName); + }; + return HammerGesturesPluginCommon; + })(event_manager_1.EventManagerPlugin); + exports.HammerGesturesPluginCommon = HammerGesturesPluginCommon; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/xhr", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var XHR = (function() { + function XHR() {} + XHR.prototype.get = function(url) { + return null; + }; + return XHR; + })(); + exports.XHR = XHR; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/browser/testability", ["angular2/src/facade/lang", "angular2/src/platform/dom/dom_adapter", "angular2/core"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); + var core_1 = require("angular2/core"); + var PublicTestability = (function() { + function PublicTestability(testability) { + this._testability = testability; + } + PublicTestability.prototype.isStable = function() { + return this._testability.isStable(); + }; + PublicTestability.prototype.whenStable = function(callback) { + this._testability.whenStable(callback); + }; + PublicTestability.prototype.findBindings = function(using, provider, exactMatch) { + return this.findProviders(using, provider, exactMatch); + }; + PublicTestability.prototype.findProviders = function(using, provider, exactMatch) { + return this._testability.findBindings(using, provider, exactMatch); + }; + return PublicTestability; + })(); + var BrowserGetTestability = (function() { + function BrowserGetTestability() {} + BrowserGetTestability.init = function() { + core_1.setTestabilityGetter(new BrowserGetTestability()); + }; + BrowserGetTestability.prototype.addToWindow = function(registry) { + lang_1.global.getAngularTestability = function(elem, findInAncestors) { + if (findInAncestors === void 0) { + findInAncestors = true; + } + var testability = registry.findTestabilityInTree(elem, findInAncestors); + if (testability == null) { + throw new Error('Could not find testability for element.'); + } + return new PublicTestability(testability); + }; + lang_1.global.getAllAngularTestabilities = function() { + var testabilities = registry.getAllTestabilities(); + return testabilities.map(function(testability) { + return new PublicTestability(testability); + }); + }; + }; + BrowserGetTestability.prototype.findTestabilityInTree = function(registry, elem, findInAncestors) { + if (elem == null) { + return null; + } + var t = registry.getTestability(elem); + if (lang_1.isPresent(t)) { + return t; + } else if (!findInAncestors) { + return null; + } + if (dom_adapter_1.DOM.isShadowRoot(elem)) { + return this.findTestabilityInTree(registry, dom_adapter_1.DOM.getHost(elem), true); + } + return this.findTestabilityInTree(registry, dom_adapter_1.DOM.parentElement(elem), true); + }; + return BrowserGetTestability; + })(); + exports.BrowserGetTestability = BrowserGetTestability; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/profile/wtf_init", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function wtfInit() {} + exports.wtfInit = wtfInit; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/browser/title", ["angular2/src/platform/dom/dom_adapter"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); + var Title = (function() { + function Title() {} + Title.prototype.getTitle = function() { + return dom_adapter_1.DOM.getTitle(); + }; + Title.prototype.setTitle = function(newTitle) { + dom_adapter_1.DOM.setTitle(newTitle); + }; + return Title; + })(); + exports.Title = Title; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/facade/browser", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var win = window; + exports.window = win; + exports.document = window.document; + exports.location = window.location; + exports.gc = window['gc'] ? function() { + return window['gc'](); + } : function() { + return null; + }; + exports.performance = window['performance'] ? window['performance'] : null; + exports.Event = window['Event']; + exports.MouseEvent = window['MouseEvent']; + exports.KeyboardEvent = window['KeyboardEvent']; + exports.EventTarget = window['EventTarget']; + exports.History = window['History']; + exports.Location = window['Location']; + exports.EventListener = window['EventListener']; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/url_resolver", ["angular2/src/core/di", "angular2/src/facade/lang", "angular2/src/core/application_tokens", "angular2/src/core/di"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var di_1 = require("angular2/src/core/di"); + var lang_1 = require("angular2/src/facade/lang"); + var application_tokens_1 = require("angular2/src/core/application_tokens"); + var di_2 = require("angular2/src/core/di"); + function createWithoutPackagePrefix() { + return new UrlResolver(); + } + exports.createWithoutPackagePrefix = createWithoutPackagePrefix; + exports.DEFAULT_PACKAGE_URL_PROVIDER = new di_2.Provider(application_tokens_1.PACKAGE_ROOT_URL, {useValue: "/"}); + var UrlResolver = (function() { + function UrlResolver(packagePrefix) { + if (packagePrefix === void 0) { + packagePrefix = null; + } + if (lang_1.isPresent(packagePrefix)) { + this._packagePrefix = lang_1.StringWrapper.stripRight(packagePrefix, "/") + "/"; + } + } + UrlResolver.prototype.resolve = function(baseUrl, url) { + var resolvedUrl = url; + if (lang_1.isPresent(baseUrl) && baseUrl.length > 0) { + resolvedUrl = _resolveUrl(baseUrl, resolvedUrl); + } + if (lang_1.isPresent(this._packagePrefix) && getUrlScheme(resolvedUrl) == "package") { + resolvedUrl = resolvedUrl.replace("package:", this._packagePrefix); + } + return resolvedUrl; + }; + UrlResolver = __decorate([di_1.Injectable(), __param(0, di_1.Inject(application_tokens_1.PACKAGE_ROOT_URL)), __metadata('design:paramtypes', [String])], UrlResolver); + return UrlResolver; + })(); + exports.UrlResolver = UrlResolver; + function getUrlScheme(url) { + var match = _split(url); + return (match && match[_ComponentIndex.Scheme]) || ""; + } + exports.getUrlScheme = getUrlScheme; + function _buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) { + var out = []; + if (lang_1.isPresent(opt_scheme)) { + out.push(opt_scheme + ':'); + } + if (lang_1.isPresent(opt_domain)) { + out.push('//'); + if (lang_1.isPresent(opt_userInfo)) { + out.push(opt_userInfo + '@'); + } + out.push(opt_domain); + if (lang_1.isPresent(opt_port)) { + out.push(':' + opt_port); + } + } + if (lang_1.isPresent(opt_path)) { + out.push(opt_path); + } + if (lang_1.isPresent(opt_queryData)) { + out.push('?' + opt_queryData); + } + if (lang_1.isPresent(opt_fragment)) { + out.push('#' + opt_fragment); + } + return out.join(''); + } + var _splitRe = lang_1.RegExpWrapper.create('^' + '(?:' + '([^:/?#.]+)' + ':)?' + '(?://' + '(?:([^/?#]*)@)?' + '([\\w\\d\\-\\u0100-\\uffff.%]*)' + '(?::([0-9]+))?' + ')?' + '([^?#]+)?' + '(?:\\?([^#]*))?' + '(?:#(.*))?' + '$'); + var _ComponentIndex; + (function(_ComponentIndex) { + _ComponentIndex[_ComponentIndex["Scheme"] = 1] = "Scheme"; + _ComponentIndex[_ComponentIndex["UserInfo"] = 2] = "UserInfo"; + _ComponentIndex[_ComponentIndex["Domain"] = 3] = "Domain"; + _ComponentIndex[_ComponentIndex["Port"] = 4] = "Port"; + _ComponentIndex[_ComponentIndex["Path"] = 5] = "Path"; + _ComponentIndex[_ComponentIndex["QueryData"] = 6] = "QueryData"; + _ComponentIndex[_ComponentIndex["Fragment"] = 7] = "Fragment"; + })(_ComponentIndex || (_ComponentIndex = {})); + function _split(uri) { + return lang_1.RegExpWrapper.firstMatch(_splitRe, uri); + } + function _removeDotSegments(path) { + if (path == '/') + return '/'; + var leadingSlash = path[0] == '/' ? '/' : ''; + var trailingSlash = path[path.length - 1] === '/' ? '/' : ''; + var segments = path.split('/'); + var out = []; + var up = 0; + for (var pos = 0; pos < segments.length; pos++) { + var segment = segments[pos]; + switch (segment) { + case '': + case '.': + break; + case '..': + if (out.length > 0) { + out.pop(); + } else { + up++; + } + break; + default: + out.push(segment); + } + } + if (leadingSlash == '') { + while (up-- > 0) { + out.unshift('..'); + } + if (out.length === 0) + out.push('.'); + } + return leadingSlash + out.join('/') + trailingSlash; + } + function _joinAndCanonicalizePath(parts) { + var path = parts[_ComponentIndex.Path]; + path = lang_1.isBlank(path) ? '' : _removeDotSegments(path); + parts[_ComponentIndex.Path] = path; + return _buildFromEncodedParts(parts[_ComponentIndex.Scheme], parts[_ComponentIndex.UserInfo], parts[_ComponentIndex.Domain], parts[_ComponentIndex.Port], path, parts[_ComponentIndex.QueryData], parts[_ComponentIndex.Fragment]); + } + function _resolveUrl(base, url) { + var parts = _split(encodeURI(url)); + var baseParts = _split(base); + if (lang_1.isPresent(parts[_ComponentIndex.Scheme])) { + return _joinAndCanonicalizePath(parts); + } else { + parts[_ComponentIndex.Scheme] = baseParts[_ComponentIndex.Scheme]; + } + for (var i = _ComponentIndex.Scheme; i <= _ComponentIndex.Port; i++) { + if (lang_1.isBlank(parts[i])) { + parts[i] = baseParts[i]; + } + } + if (parts[_ComponentIndex.Path][0] == '/') { + return _joinAndCanonicalizePath(parts); + } + var path = baseParts[_ComponentIndex.Path]; + if (lang_1.isBlank(path)) + path = '/'; + var index = path.lastIndexOf('/'); + path = path.substring(0, index + 1) + parts[_ComponentIndex.Path]; + parts[_ComponentIndex.Path] = path; + return _joinAndCanonicalizePath(parts); + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/selector", ["angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/facade/exceptions"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var _EMPTY_ATTR_VALUE = ''; + var _SELECTOR_REGEXP = lang_1.RegExpWrapper.create('(\\:not\\()|' + '([-\\w]+)|' + '(?:\\.([-\\w]+))|' + '(?:\\[([-\\w*]+)(?:=([^\\]]*))?\\])|' + '(\\))|' + '(\\s*,\\s*)'); + var CssSelector = (function() { + function CssSelector() { + this.element = null; + this.classNames = []; + this.attrs = []; + this.notSelectors = []; + } + CssSelector.parse = function(selector) { + var results = []; + var _addResult = function(res, cssSel) { + if (cssSel.notSelectors.length > 0 && lang_1.isBlank(cssSel.element) && collection_1.ListWrapper.isEmpty(cssSel.classNames) && collection_1.ListWrapper.isEmpty(cssSel.attrs)) { + cssSel.element = "*"; + } + res.push(cssSel); + }; + var cssSelector = new CssSelector(); + var matcher = lang_1.RegExpWrapper.matcher(_SELECTOR_REGEXP, selector); + var match; + var current = cssSelector; + var inNot = false; + while (lang_1.isPresent(match = lang_1.RegExpMatcherWrapper.next(matcher))) { + if (lang_1.isPresent(match[1])) { + if (inNot) { + throw new exceptions_1.BaseException('Nesting :not is not allowed in a selector'); + } + inNot = true; + current = new CssSelector(); + cssSelector.notSelectors.push(current); + } + if (lang_1.isPresent(match[2])) { + current.setElement(match[2]); + } + if (lang_1.isPresent(match[3])) { + current.addClassName(match[3]); + } + if (lang_1.isPresent(match[4])) { + current.addAttribute(match[4], match[5]); + } + if (lang_1.isPresent(match[6])) { + inNot = false; + current = cssSelector; + } + if (lang_1.isPresent(match[7])) { + if (inNot) { + throw new exceptions_1.BaseException('Multiple selectors in :not are not supported'); + } + _addResult(results, cssSelector); + cssSelector = current = new CssSelector(); + } + } + _addResult(results, cssSelector); + return results; + }; + CssSelector.prototype.isElementSelector = function() { + return lang_1.isPresent(this.element) && collection_1.ListWrapper.isEmpty(this.classNames) && collection_1.ListWrapper.isEmpty(this.attrs) && this.notSelectors.length === 0; + }; + CssSelector.prototype.setElement = function(element) { + if (element === void 0) { + element = null; + } + this.element = element; + }; + CssSelector.prototype.getMatchingElementTemplate = function() { + var tagName = lang_1.isPresent(this.element) ? this.element : 'div'; + var classAttr = this.classNames.length > 0 ? " class=\"" + this.classNames.join(' ') + "\"" : ''; + var attrs = ''; + for (var i = 0; i < this.attrs.length; i += 2) { + var attrName = this.attrs[i]; + var attrValue = this.attrs[i + 1] !== '' ? "=\"" + this.attrs[i + 1] + "\"" : ''; + attrs += " " + attrName + attrValue; + } + return "<" + tagName + classAttr + attrs + ">"; + }; + CssSelector.prototype.addAttribute = function(name, value) { + if (value === void 0) { + value = _EMPTY_ATTR_VALUE; + } + this.attrs.push(name); + if (lang_1.isPresent(value)) { + value = value.toLowerCase(); + } else { + value = _EMPTY_ATTR_VALUE; + } + this.attrs.push(value); + }; + CssSelector.prototype.addClassName = function(name) { + this.classNames.push(name.toLowerCase()); + }; + CssSelector.prototype.toString = function() { + var res = ''; + if (lang_1.isPresent(this.element)) { + res += this.element; + } + if (lang_1.isPresent(this.classNames)) { + for (var i = 0; i < this.classNames.length; i++) { + res += '.' + this.classNames[i]; + } + } + if (lang_1.isPresent(this.attrs)) { + for (var i = 0; i < this.attrs.length; ) { + var attrName = this.attrs[i++]; + var attrValue = this.attrs[i++]; + res += '[' + attrName; + if (attrValue.length > 0) { + res += '=' + attrValue; + } + res += ']'; + } + } + this.notSelectors.forEach(function(notSelector) { + return res += ":not(" + notSelector + ")"; + }); + return res; + }; + return CssSelector; + })(); + exports.CssSelector = CssSelector; + var SelectorMatcher = (function() { + function SelectorMatcher() { + this._elementMap = new collection_1.Map(); + this._elementPartialMap = new collection_1.Map(); + this._classMap = new collection_1.Map(); + this._classPartialMap = new collection_1.Map(); + this._attrValueMap = new collection_1.Map(); + this._attrValuePartialMap = new collection_1.Map(); + this._listContexts = []; + } + SelectorMatcher.createNotMatcher = function(notSelectors) { + var notMatcher = new SelectorMatcher(); + notMatcher.addSelectables(notSelectors, null); + return notMatcher; + }; + SelectorMatcher.prototype.addSelectables = function(cssSelectors, callbackCtxt) { + var listContext = null; + if (cssSelectors.length > 1) { + listContext = new SelectorListContext(cssSelectors); + this._listContexts.push(listContext); + } + for (var i = 0; i < cssSelectors.length; i++) { + this._addSelectable(cssSelectors[i], callbackCtxt, listContext); + } + }; + SelectorMatcher.prototype._addSelectable = function(cssSelector, callbackCtxt, listContext) { + var matcher = this; + var element = cssSelector.element; + var classNames = cssSelector.classNames; + var attrs = cssSelector.attrs; + var selectable = new SelectorContext(cssSelector, callbackCtxt, listContext); + if (lang_1.isPresent(element)) { + var isTerminal = attrs.length === 0 && classNames.length === 0; + if (isTerminal) { + this._addTerminal(matcher._elementMap, element, selectable); + } else { + matcher = this._addPartial(matcher._elementPartialMap, element); + } + } + if (lang_1.isPresent(classNames)) { + for (var index = 0; index < classNames.length; index++) { + var isTerminal = attrs.length === 0 && index === classNames.length - 1; + var className = classNames[index]; + if (isTerminal) { + this._addTerminal(matcher._classMap, className, selectable); + } else { + matcher = this._addPartial(matcher._classPartialMap, className); + } + } + } + if (lang_1.isPresent(attrs)) { + for (var index = 0; index < attrs.length; ) { + var isTerminal = index === attrs.length - 2; + var attrName = attrs[index++]; + var attrValue = attrs[index++]; + if (isTerminal) { + var terminalMap = matcher._attrValueMap; + var terminalValuesMap = terminalMap.get(attrName); + if (lang_1.isBlank(terminalValuesMap)) { + terminalValuesMap = new collection_1.Map(); + terminalMap.set(attrName, terminalValuesMap); + } + this._addTerminal(terminalValuesMap, attrValue, selectable); + } else { + var parttialMap = matcher._attrValuePartialMap; + var partialValuesMap = parttialMap.get(attrName); + if (lang_1.isBlank(partialValuesMap)) { + partialValuesMap = new collection_1.Map(); + parttialMap.set(attrName, partialValuesMap); + } + matcher = this._addPartial(partialValuesMap, attrValue); + } + } + } + }; + SelectorMatcher.prototype._addTerminal = function(map, name, selectable) { + var terminalList = map.get(name); + if (lang_1.isBlank(terminalList)) { + terminalList = []; + map.set(name, terminalList); + } + terminalList.push(selectable); + }; + SelectorMatcher.prototype._addPartial = function(map, name) { + var matcher = map.get(name); + if (lang_1.isBlank(matcher)) { + matcher = new SelectorMatcher(); + map.set(name, matcher); + } + return matcher; + }; + SelectorMatcher.prototype.match = function(cssSelector, matchedCallback) { + var result = false; + var element = cssSelector.element; + var classNames = cssSelector.classNames; + var attrs = cssSelector.attrs; + for (var i = 0; i < this._listContexts.length; i++) { + this._listContexts[i].alreadyMatched = false; + } + result = this._matchTerminal(this._elementMap, element, cssSelector, matchedCallback) || result; + result = this._matchPartial(this._elementPartialMap, element, cssSelector, matchedCallback) || result; + if (lang_1.isPresent(classNames)) { + for (var index = 0; index < classNames.length; index++) { + var className = classNames[index]; + result = this._matchTerminal(this._classMap, className, cssSelector, matchedCallback) || result; + result = this._matchPartial(this._classPartialMap, className, cssSelector, matchedCallback) || result; + } + } + if (lang_1.isPresent(attrs)) { + for (var index = 0; index < attrs.length; ) { + var attrName = attrs[index++]; + var attrValue = attrs[index++]; + var terminalValuesMap = this._attrValueMap.get(attrName); + if (!lang_1.StringWrapper.equals(attrValue, _EMPTY_ATTR_VALUE)) { + result = this._matchTerminal(terminalValuesMap, _EMPTY_ATTR_VALUE, cssSelector, matchedCallback) || result; + } + result = this._matchTerminal(terminalValuesMap, attrValue, cssSelector, matchedCallback) || result; + var partialValuesMap = this._attrValuePartialMap.get(attrName); + if (!lang_1.StringWrapper.equals(attrValue, _EMPTY_ATTR_VALUE)) { + result = this._matchPartial(partialValuesMap, _EMPTY_ATTR_VALUE, cssSelector, matchedCallback) || result; + } + result = this._matchPartial(partialValuesMap, attrValue, cssSelector, matchedCallback) || result; + } + } + return result; + }; + SelectorMatcher.prototype._matchTerminal = function(map, name, cssSelector, matchedCallback) { + if (lang_1.isBlank(map) || lang_1.isBlank(name)) { + return false; + } + var selectables = map.get(name); + var starSelectables = map.get("*"); + if (lang_1.isPresent(starSelectables)) { + selectables = selectables.concat(starSelectables); + } + if (lang_1.isBlank(selectables)) { + return false; + } + var selectable; + var result = false; + for (var index = 0; index < selectables.length; index++) { + selectable = selectables[index]; + result = selectable.finalize(cssSelector, matchedCallback) || result; + } + return result; + }; + SelectorMatcher.prototype._matchPartial = function(map, name, cssSelector, matchedCallback) { + if (lang_1.isBlank(map) || lang_1.isBlank(name)) { + return false; + } + var nestedSelector = map.get(name); + if (lang_1.isBlank(nestedSelector)) { + return false; + } + return nestedSelector.match(cssSelector, matchedCallback); + }; + return SelectorMatcher; + })(); + exports.SelectorMatcher = SelectorMatcher; + var SelectorListContext = (function() { + function SelectorListContext(selectors) { + this.selectors = selectors; + this.alreadyMatched = false; + } + return SelectorListContext; + })(); + exports.SelectorListContext = SelectorListContext; + var SelectorContext = (function() { + function SelectorContext(selector, cbContext, listContext) { + this.selector = selector; + this.cbContext = cbContext; + this.listContext = listContext; + this.notSelectors = selector.notSelectors; + } + SelectorContext.prototype.finalize = function(cssSelector, callback) { + var result = true; + if (this.notSelectors.length > 0 && (lang_1.isBlank(this.listContext) || !this.listContext.alreadyMatched)) { + var notMatcher = SelectorMatcher.createNotMatcher(this.notSelectors); + result = !notMatcher.match(cssSelector, null); + } + if (result && lang_1.isPresent(callback) && (lang_1.isBlank(this.listContext) || !this.listContext.alreadyMatched)) { + if (lang_1.isPresent(this.listContext)) { + this.listContext.alreadyMatched = true; + } + callback(this.selector, this.cbContext); + } + return result; + }; + return SelectorContext; + })(); + exports.SelectorContext = SelectorContext; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/util", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var CAMEL_CASE_REGEXP = /([A-Z])/g; + var DASH_CASE_REGEXP = /-([a-z])/g; + var SINGLE_QUOTE_ESCAPE_STRING_RE = /'|\\|\n|\r|\$/g; + var DOUBLE_QUOTE_ESCAPE_STRING_RE = /"|\\|\n|\r|\$/g; + exports.MODULE_SUFFIX = lang_1.IS_DART ? '.dart' : '.js'; + function camelCaseToDashCase(input) { + return lang_1.StringWrapper.replaceAllMapped(input, CAMEL_CASE_REGEXP, function(m) { + return '-' + m[1].toLowerCase(); + }); + } + exports.camelCaseToDashCase = camelCaseToDashCase; + function dashCaseToCamelCase(input) { + return lang_1.StringWrapper.replaceAllMapped(input, DASH_CASE_REGEXP, function(m) { + return m[1].toUpperCase(); + }); + } + exports.dashCaseToCamelCase = dashCaseToCamelCase; + function escapeSingleQuoteString(input) { + if (lang_1.isBlank(input)) { + return null; + } + return "'" + escapeString(input, SINGLE_QUOTE_ESCAPE_STRING_RE) + "'"; + } + exports.escapeSingleQuoteString = escapeSingleQuoteString; + function escapeDoubleQuoteString(input) { + if (lang_1.isBlank(input)) { + return null; + } + return "\"" + escapeString(input, DOUBLE_QUOTE_ESCAPE_STRING_RE) + "\""; + } + exports.escapeDoubleQuoteString = escapeDoubleQuoteString; + function escapeString(input, re) { + return lang_1.StringWrapper.replaceAllMapped(input, re, function(match) { + if (match[0] == '$') { + return lang_1.IS_DART ? '\\$' : '$'; + } else if (match[0] == '\n') { + return '\\n'; + } else if (match[0] == '\r') { + return '\\r'; + } else { + return "\\" + match[0]; + } + }); + } + function codeGenExportVariable(name) { + if (lang_1.IS_DART) { + return "const " + name + " = "; + } else { + return "var " + name + " = exports['" + name + "'] = "; + } + } + exports.codeGenExportVariable = codeGenExportVariable; + function codeGenConstConstructorCall(name) { + if (lang_1.IS_DART) { + return "const " + name; + } else { + return "new " + name; + } + } + exports.codeGenConstConstructorCall = codeGenConstConstructorCall; + function codeGenValueFn(params, value, fnName) { + if (fnName === void 0) { + fnName = ''; + } + if (lang_1.IS_DART) { + return fnName + "(" + params.join(',') + ") => " + value; + } else { + return "function " + fnName + "(" + params.join(',') + ") { return " + value + "; }"; + } + } + exports.codeGenValueFn = codeGenValueFn; + function codeGenToString(expr) { + if (lang_1.IS_DART) { + return "'${" + expr + "}'"; + } else { + return expr; + } + } + exports.codeGenToString = codeGenToString; + function splitAtColon(input, defaultValues) { + var parts = lang_1.StringWrapper.split(input.trim(), /\s*:\s*/g); + if (parts.length > 1) { + return parts; + } else { + return defaultValues; + } + } + exports.splitAtColon = splitAtColon; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/source_module", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var MODULE_REGEXP = /#MODULE\[([^\]]*)\]/g; + function moduleRef(moduleUrl) { + return "#MODULE[" + moduleUrl + "]"; + } + exports.moduleRef = moduleRef; + var SourceModule = (function() { + function SourceModule(moduleUrl, sourceWithModuleRefs) { + this.moduleUrl = moduleUrl; + this.sourceWithModuleRefs = sourceWithModuleRefs; + } + SourceModule.prototype.getSourceWithImports = function() { + var _this = this; + var moduleAliases = {}; + var imports = []; + var newSource = lang_1.StringWrapper.replaceAllMapped(this.sourceWithModuleRefs, MODULE_REGEXP, function(match) { + var moduleUrl = match[1]; + var alias = moduleAliases[moduleUrl]; + if (lang_1.isBlank(alias)) { + if (moduleUrl == _this.moduleUrl) { + alias = ''; + } else { + alias = "import" + imports.length; + imports.push([moduleUrl, alias]); + } + moduleAliases[moduleUrl] = alias; + } + return alias.length > 0 ? alias + "." : ''; + }); + return new SourceWithImports(newSource, imports); + }; + return SourceModule; + })(); + exports.SourceModule = SourceModule; + var SourceExpression = (function() { + function SourceExpression(declarations, expression) { + this.declarations = declarations; + this.expression = expression; + } + return SourceExpression; + })(); + exports.SourceExpression = SourceExpression; + var SourceExpressions = (function() { + function SourceExpressions(declarations, expressions) { + this.declarations = declarations; + this.expressions = expressions; + } + return SourceExpressions; + })(); + exports.SourceExpressions = SourceExpressions; + var SourceWithImports = (function() { + function SourceWithImports(source, imports) { + this.source = source; + this.imports = imports; + } + return SourceWithImports; + })(); + exports.SourceWithImports = SourceWithImports; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/template_ast", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var TextAst = (function() { + function TextAst(value, ngContentIndex, sourceSpan) { + this.value = value; + this.ngContentIndex = ngContentIndex; + this.sourceSpan = sourceSpan; + } + TextAst.prototype.visit = function(visitor, context) { + return visitor.visitText(this, context); + }; + return TextAst; + })(); + exports.TextAst = TextAst; + var BoundTextAst = (function() { + function BoundTextAst(value, ngContentIndex, sourceSpan) { + this.value = value; + this.ngContentIndex = ngContentIndex; + this.sourceSpan = sourceSpan; + } + BoundTextAst.prototype.visit = function(visitor, context) { + return visitor.visitBoundText(this, context); + }; + return BoundTextAst; + })(); + exports.BoundTextAst = BoundTextAst; + var AttrAst = (function() { + function AttrAst(name, value, sourceSpan) { + this.name = name; + this.value = value; + this.sourceSpan = sourceSpan; + } + AttrAst.prototype.visit = function(visitor, context) { + return visitor.visitAttr(this, context); + }; + return AttrAst; + })(); + exports.AttrAst = AttrAst; + var BoundElementPropertyAst = (function() { + function BoundElementPropertyAst(name, type, value, unit, sourceSpan) { + this.name = name; + this.type = type; + this.value = value; + this.unit = unit; + this.sourceSpan = sourceSpan; + } + BoundElementPropertyAst.prototype.visit = function(visitor, context) { + return visitor.visitElementProperty(this, context); + }; + return BoundElementPropertyAst; + })(); + exports.BoundElementPropertyAst = BoundElementPropertyAst; + var BoundEventAst = (function() { + function BoundEventAst(name, target, handler, sourceSpan) { + this.name = name; + this.target = target; + this.handler = handler; + this.sourceSpan = sourceSpan; + } + BoundEventAst.prototype.visit = function(visitor, context) { + return visitor.visitEvent(this, context); + }; + Object.defineProperty(BoundEventAst.prototype, "fullName", { + get: function() { + if (lang_1.isPresent(this.target)) { + return this.target + ":" + this.name; + } else { + return this.name; + } + }, + enumerable: true, + configurable: true + }); + return BoundEventAst; + })(); + exports.BoundEventAst = BoundEventAst; + var VariableAst = (function() { + function VariableAst(name, value, sourceSpan) { + this.name = name; + this.value = value; + this.sourceSpan = sourceSpan; + } + VariableAst.prototype.visit = function(visitor, context) { + return visitor.visitVariable(this, context); + }; + return VariableAst; + })(); + exports.VariableAst = VariableAst; + var ElementAst = (function() { + function ElementAst(name, attrs, inputs, outputs, exportAsVars, directives, children, ngContentIndex, sourceSpan) { + this.name = name; + this.attrs = attrs; + this.inputs = inputs; + this.outputs = outputs; + this.exportAsVars = exportAsVars; + this.directives = directives; + this.children = children; + this.ngContentIndex = ngContentIndex; + this.sourceSpan = sourceSpan; + } + ElementAst.prototype.visit = function(visitor, context) { + return visitor.visitElement(this, context); + }; + ElementAst.prototype.isBound = function() { + return (this.inputs.length > 0 || this.outputs.length > 0 || this.exportAsVars.length > 0 || this.directives.length > 0); + }; + ElementAst.prototype.getComponent = function() { + return this.directives.length > 0 && this.directives[0].directive.isComponent ? this.directives[0].directive : null; + }; + return ElementAst; + })(); + exports.ElementAst = ElementAst; + var EmbeddedTemplateAst = (function() { + function EmbeddedTemplateAst(attrs, outputs, vars, directives, children, ngContentIndex, sourceSpan) { + this.attrs = attrs; + this.outputs = outputs; + this.vars = vars; + this.directives = directives; + this.children = children; + this.ngContentIndex = ngContentIndex; + this.sourceSpan = sourceSpan; + } + EmbeddedTemplateAst.prototype.visit = function(visitor, context) { + return visitor.visitEmbeddedTemplate(this, context); + }; + return EmbeddedTemplateAst; + })(); + exports.EmbeddedTemplateAst = EmbeddedTemplateAst; + var BoundDirectivePropertyAst = (function() { + function BoundDirectivePropertyAst(directiveName, templateName, value, sourceSpan) { + this.directiveName = directiveName; + this.templateName = templateName; + this.value = value; + this.sourceSpan = sourceSpan; + } + BoundDirectivePropertyAst.prototype.visit = function(visitor, context) { + return visitor.visitDirectiveProperty(this, context); + }; + return BoundDirectivePropertyAst; + })(); + exports.BoundDirectivePropertyAst = BoundDirectivePropertyAst; + var DirectiveAst = (function() { + function DirectiveAst(directive, inputs, hostProperties, hostEvents, exportAsVars, sourceSpan) { + this.directive = directive; + this.inputs = inputs; + this.hostProperties = hostProperties; + this.hostEvents = hostEvents; + this.exportAsVars = exportAsVars; + this.sourceSpan = sourceSpan; + } + DirectiveAst.prototype.visit = function(visitor, context) { + return visitor.visitDirective(this, context); + }; + return DirectiveAst; + })(); + exports.DirectiveAst = DirectiveAst; + var NgContentAst = (function() { + function NgContentAst(index, ngContentIndex, sourceSpan) { + this.index = index; + this.ngContentIndex = ngContentIndex; + this.sourceSpan = sourceSpan; + } + NgContentAst.prototype.visit = function(visitor, context) { + return visitor.visitNgContent(this, context); + }; + return NgContentAst; + })(); + exports.NgContentAst = NgContentAst; + (function(PropertyBindingType) { + PropertyBindingType[PropertyBindingType["Property"] = 0] = "Property"; + PropertyBindingType[PropertyBindingType["Attribute"] = 1] = "Attribute"; + PropertyBindingType[PropertyBindingType["Class"] = 2] = "Class"; + PropertyBindingType[PropertyBindingType["Style"] = 3] = "Style"; + })(exports.PropertyBindingType || (exports.PropertyBindingType = {})); + var PropertyBindingType = exports.PropertyBindingType; + function templateVisitAll(visitor, asts, context) { + if (context === void 0) { + context = null; + } + var result = []; + asts.forEach(function(ast) { + var astResult = ast.visit(visitor, context); + if (lang_1.isPresent(astResult)) { + result.push(astResult); + } + }); + return result; + } + exports.templateVisitAll = templateVisitAll; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/transform/template_compiler/change_detector_codegen", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Codegen = (function() { + function Codegen(moduleAlias) {} + Codegen.prototype.generate = function(typeName, changeDetectorTypeName, def) { + throw "Not implemented in JS"; + }; + Codegen.prototype.toString = function() { + throw "Not implemented in JS"; + }; + return Codegen; + })(); + exports.Codegen = Codegen; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/shadow_css", ["angular2/src/facade/collection", "angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var ShadowCss = (function() { + function ShadowCss() { + this.strictStyling = true; + } + ShadowCss.prototype.shimCssText = function(cssText, selector, hostSelector) { + if (hostSelector === void 0) { + hostSelector = ''; + } + cssText = stripComments(cssText); + cssText = this._insertDirectives(cssText); + return this._scopeCssText(cssText, selector, hostSelector); + }; + ShadowCss.prototype._insertDirectives = function(cssText) { + cssText = this._insertPolyfillDirectivesInCssText(cssText); + return this._insertPolyfillRulesInCssText(cssText); + }; + ShadowCss.prototype._insertPolyfillDirectivesInCssText = function(cssText) { + return lang_1.StringWrapper.replaceAllMapped(cssText, _cssContentNextSelectorRe, function(m) { + return m[1] + '{'; + }); + }; + ShadowCss.prototype._insertPolyfillRulesInCssText = function(cssText) { + return lang_1.StringWrapper.replaceAllMapped(cssText, _cssContentRuleRe, function(m) { + var rule = m[0]; + rule = lang_1.StringWrapper.replace(rule, m[1], ''); + rule = lang_1.StringWrapper.replace(rule, m[2], ''); + return m[3] + rule; + }); + }; + ShadowCss.prototype._scopeCssText = function(cssText, scopeSelector, hostSelector) { + var unscoped = this._extractUnscopedRulesFromCssText(cssText); + cssText = this._insertPolyfillHostInCssText(cssText); + cssText = this._convertColonHost(cssText); + cssText = this._convertColonHostContext(cssText); + cssText = this._convertShadowDOMSelectors(cssText); + if (lang_1.isPresent(scopeSelector)) { + cssText = this._scopeSelectors(cssText, scopeSelector, hostSelector); + } + cssText = cssText + '\n' + unscoped; + return cssText.trim(); + }; + ShadowCss.prototype._extractUnscopedRulesFromCssText = function(cssText) { + var r = '', + m; + var matcher = lang_1.RegExpWrapper.matcher(_cssContentUnscopedRuleRe, cssText); + while (lang_1.isPresent(m = lang_1.RegExpMatcherWrapper.next(matcher))) { + var rule = m[0]; + rule = lang_1.StringWrapper.replace(rule, m[2], ''); + rule = lang_1.StringWrapper.replace(rule, m[1], m[3]); + r += rule + '\n\n'; + } + return r; + }; + ShadowCss.prototype._convertColonHost = function(cssText) { + return this._convertColonRule(cssText, _cssColonHostRe, this._colonHostPartReplacer); + }; + ShadowCss.prototype._convertColonHostContext = function(cssText) { + return this._convertColonRule(cssText, _cssColonHostContextRe, this._colonHostContextPartReplacer); + }; + ShadowCss.prototype._convertColonRule = function(cssText, regExp, partReplacer) { + return lang_1.StringWrapper.replaceAllMapped(cssText, regExp, function(m) { + if (lang_1.isPresent(m[2])) { + var parts = m[2].split(','), + r = []; + for (var i = 0; i < parts.length; i++) { + var p = parts[i]; + if (lang_1.isBlank(p)) + break; + p = p.trim(); + r.push(partReplacer(_polyfillHostNoCombinator, p, m[3])); + } + return r.join(','); + } else { + return _polyfillHostNoCombinator + m[3]; + } + }); + }; + ShadowCss.prototype._colonHostContextPartReplacer = function(host, part, suffix) { + if (lang_1.StringWrapper.contains(part, _polyfillHost)) { + return this._colonHostPartReplacer(host, part, suffix); + } else { + return host + part + suffix + ', ' + part + ' ' + host + suffix; + } + }; + ShadowCss.prototype._colonHostPartReplacer = function(host, part, suffix) { + return host + lang_1.StringWrapper.replace(part, _polyfillHost, '') + suffix; + }; + ShadowCss.prototype._convertShadowDOMSelectors = function(cssText) { + for (var i = 0; i < _shadowDOMSelectorsRe.length; i++) { + cssText = lang_1.StringWrapper.replaceAll(cssText, _shadowDOMSelectorsRe[i], ' '); + } + return cssText; + }; + ShadowCss.prototype._scopeSelectors = function(cssText, scopeSelector, hostSelector) { + var _this = this; + return processRules(cssText, function(rule) { + var selector = rule.selector; + var content = rule.content; + if (rule.selector[0] != '@' || rule.selector.startsWith('@page')) { + selector = _this._scopeSelector(rule.selector, scopeSelector, hostSelector, _this.strictStyling); + } else if (rule.selector.startsWith('@media')) { + content = _this._scopeSelectors(rule.content, scopeSelector, hostSelector); + } + return new CssRule(selector, content); + }); + }; + ShadowCss.prototype._scopeSelector = function(selector, scopeSelector, hostSelector, strict) { + var r = [], + parts = selector.split(','); + for (var i = 0; i < parts.length; i++) { + var p = parts[i]; + p = p.trim(); + if (this._selectorNeedsScoping(p, scopeSelector)) { + p = strict && !lang_1.StringWrapper.contains(p, _polyfillHostNoCombinator) ? this._applyStrictSelectorScope(p, scopeSelector) : this._applySelectorScope(p, scopeSelector, hostSelector); + } + r.push(p); + } + return r.join(', '); + }; + ShadowCss.prototype._selectorNeedsScoping = function(selector, scopeSelector) { + var re = this._makeScopeMatcher(scopeSelector); + return !lang_1.isPresent(lang_1.RegExpWrapper.firstMatch(re, selector)); + }; + ShadowCss.prototype._makeScopeMatcher = function(scopeSelector) { + var lre = /\[/g; + var rre = /\]/g; + scopeSelector = lang_1.StringWrapper.replaceAll(scopeSelector, lre, '\\['); + scopeSelector = lang_1.StringWrapper.replaceAll(scopeSelector, rre, '\\]'); + return lang_1.RegExpWrapper.create('^(' + scopeSelector + ')' + _selectorReSuffix, 'm'); + }; + ShadowCss.prototype._applySelectorScope = function(selector, scopeSelector, hostSelector) { + return this._applySimpleSelectorScope(selector, scopeSelector, hostSelector); + }; + ShadowCss.prototype._applySimpleSelectorScope = function(selector, scopeSelector, hostSelector) { + if (lang_1.isPresent(lang_1.RegExpWrapper.firstMatch(_polyfillHostRe, selector))) { + var replaceBy = this.strictStyling ? "[" + hostSelector + "]" : scopeSelector; + selector = lang_1.StringWrapper.replace(selector, _polyfillHostNoCombinator, replaceBy); + return lang_1.StringWrapper.replaceAll(selector, _polyfillHostRe, replaceBy + ' '); + } else { + return scopeSelector + ' ' + selector; + } + }; + ShadowCss.prototype._applyStrictSelectorScope = function(selector, scopeSelector) { + var isRe = /\[is=([^\]]*)\]/g; + scopeSelector = lang_1.StringWrapper.replaceAllMapped(scopeSelector, isRe, function(m) { + return m[1]; + }); + var splits = [' ', '>', '+', '~'], + scoped = selector, + attrName = '[' + scopeSelector + ']'; + for (var i = 0; i < splits.length; i++) { + var sep = splits[i]; + var parts = scoped.split(sep); + scoped = parts.map(function(p) { + var t = lang_1.StringWrapper.replaceAll(p.trim(), _polyfillHostRe, ''); + if (t.length > 0 && !collection_1.ListWrapper.contains(splits, t) && !lang_1.StringWrapper.contains(t, attrName)) { + var re = /([^:]*)(:*)(.*)/g; + var m = lang_1.RegExpWrapper.firstMatch(re, t); + if (lang_1.isPresent(m)) { + p = m[1] + attrName + m[2] + m[3]; + } + } + return p; + }).join(sep); + } + return scoped; + }; + ShadowCss.prototype._insertPolyfillHostInCssText = function(selector) { + selector = lang_1.StringWrapper.replaceAll(selector, _colonHostContextRe, _polyfillHostContext); + selector = lang_1.StringWrapper.replaceAll(selector, _colonHostRe, _polyfillHost); + return selector; + }; + return ShadowCss; + })(); + exports.ShadowCss = ShadowCss; + var _cssContentNextSelectorRe = /polyfill-next-selector[^}]*content:[\s]*?['"](.*?)['"][;\s]*}([^{]*?){/gim; + var _cssContentRuleRe = /(polyfill-rule)[^}]*(content:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim; + var _cssContentUnscopedRuleRe = /(polyfill-unscoped-rule)[^}]*(content:[\s]*['"](.*?)['"])[;\s]*[^}]*}/gim; + var _polyfillHost = '-shadowcsshost'; + var _polyfillHostContext = '-shadowcsscontext'; + var _parenSuffix = ')(?:\\((' + '(?:\\([^)(]*\\)|[^)(]*)+?' + ')\\))?([^,{]*)'; + var _cssColonHostRe = lang_1.RegExpWrapper.create('(' + _polyfillHost + _parenSuffix, 'im'); + var _cssColonHostContextRe = lang_1.RegExpWrapper.create('(' + _polyfillHostContext + _parenSuffix, 'im'); + var _polyfillHostNoCombinator = _polyfillHost + '-no-combinator'; + var _shadowDOMSelectorsRe = [/>>>/g, /::shadow/g, /::content/g, /\/deep\//g, /\/shadow-deep\//g, /\/shadow\//g]; + var _selectorReSuffix = '([>\\s~+\[.,{:][\\s\\S]*)?$'; + var _polyfillHostRe = lang_1.RegExpWrapper.create(_polyfillHost, 'im'); + var _colonHostRe = /:host/gim; + var _colonHostContextRe = /:host-context/gim; + var _commentRe = /\/\*[\s\S]*?\*\//g; + function stripComments(input) { + return lang_1.StringWrapper.replaceAllMapped(input, _commentRe, function(_) { + return ''; + }); + } + var _ruleRe = /(\s*)([^;\{\}]+?)(\s*)((?:{%BLOCK%}?\s*;?)|(?:\s*;))/g; + var _curlyRe = /([{}])/g; + var OPEN_CURLY = '{'; + var CLOSE_CURLY = '}'; + var BLOCK_PLACEHOLDER = '%BLOCK%'; + var CssRule = (function() { + function CssRule(selector, content) { + this.selector = selector; + this.content = content; + } + return CssRule; + })(); + exports.CssRule = CssRule; + function processRules(input, ruleCallback) { + var inputWithEscapedBlocks = escapeBlocks(input); + var nextBlockIndex = 0; + return lang_1.StringWrapper.replaceAllMapped(inputWithEscapedBlocks.escapedString, _ruleRe, function(m) { + var selector = m[2]; + var content = ''; + var suffix = m[4]; + var contentPrefix = ''; + if (lang_1.isPresent(m[4]) && m[4].startsWith('{' + BLOCK_PLACEHOLDER)) { + content = inputWithEscapedBlocks.blocks[nextBlockIndex++]; + suffix = m[4].substring(BLOCK_PLACEHOLDER.length + 1); + contentPrefix = '{'; + } + var rule = ruleCallback(new CssRule(selector, content)); + return "" + m[1] + rule.selector + m[3] + contentPrefix + rule.content + suffix; + }); + } + exports.processRules = processRules; + var StringWithEscapedBlocks = (function() { + function StringWithEscapedBlocks(escapedString, blocks) { + this.escapedString = escapedString; + this.blocks = blocks; + } + return StringWithEscapedBlocks; + })(); + function escapeBlocks(input) { + var inputParts = lang_1.StringWrapper.split(input, _curlyRe); + var resultParts = []; + var escapedBlocks = []; + var bracketCount = 0; + var currentBlockParts = []; + for (var partIndex = 0; partIndex < inputParts.length; partIndex++) { + var part = inputParts[partIndex]; + if (part == CLOSE_CURLY) { + bracketCount--; + } + if (bracketCount > 0) { + currentBlockParts.push(part); + } else { + if (currentBlockParts.length > 0) { + escapedBlocks.push(currentBlockParts.join('')); + resultParts.push(BLOCK_PLACEHOLDER); + currentBlockParts = []; + } + resultParts.push(part); + } + if (part == OPEN_CURLY) { + bracketCount++; + } + } + if (currentBlockParts.length > 0) { + escapedBlocks.push(currentBlockParts.join('')); + resultParts.push(BLOCK_PLACEHOLDER); + } + return new StringWithEscapedBlocks(resultParts.join(''), escapedBlocks); + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/style_url_resolver", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var StyleWithImports = (function() { + function StyleWithImports(style, styleUrls) { + this.style = style; + this.styleUrls = styleUrls; + } + return StyleWithImports; + })(); + exports.StyleWithImports = StyleWithImports; + function isStyleUrlResolvable(url) { + if (lang_1.isBlank(url) || url.length === 0 || url[0] == '/') + return false; + var schemeMatch = lang_1.RegExpWrapper.firstMatch(_urlWithSchemaRe, url); + return lang_1.isBlank(schemeMatch) || schemeMatch[1] == 'package' || schemeMatch[1] == 'asset'; + } + exports.isStyleUrlResolvable = isStyleUrlResolvable; + function extractStyleUrls(resolver, baseUrl, cssText) { + var foundUrls = []; + var modifiedCssText = lang_1.StringWrapper.replaceAllMapped(cssText, _cssImportRe, function(m) { + var url = lang_1.isPresent(m[1]) ? m[1] : m[2]; + if (!isStyleUrlResolvable(url)) { + return m[0]; + } + foundUrls.push(resolver.resolve(baseUrl, url)); + return ''; + }); + return new StyleWithImports(modifiedCssText, foundUrls); + } + exports.extractStyleUrls = extractStyleUrls; + var _cssImportRe = /@import\s+(?:url\()?\s*(?:(?:['"]([^'"]*))|([^;\)\s]*))[^;]*;?/g; + var _urlWithSchemaRe = /^([a-zA-Z\-\+\.]+):/g; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/command_compiler", ["angular2/src/facade/lang", "angular2/src/facade/collection", "angular2/src/core/linker/template_commands", "angular2/src/compiler/template_ast", "angular2/src/compiler/source_module", "angular2/src/compiler/util", "angular2/src/core/di"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var collection_1 = require("angular2/src/facade/collection"); + var template_commands_1 = require("angular2/src/core/linker/template_commands"); + var template_ast_1 = require("angular2/src/compiler/template_ast"); + var source_module_1 = require("angular2/src/compiler/source_module"); + var util_1 = require("angular2/src/compiler/util"); + var di_1 = require("angular2/src/core/di"); + exports.TEMPLATE_COMMANDS_MODULE_REF = source_module_1.moduleRef("package:angular2/src/core/linker/template_commands" + util_1.MODULE_SUFFIX); + var IMPLICIT_TEMPLATE_VAR = '\$implicit'; + var CLASS_ATTR = 'class'; + var STYLE_ATTR = 'style'; + var CommandCompiler = (function() { + function CommandCompiler() {} + CommandCompiler.prototype.compileComponentRuntime = function(component, template, changeDetectorFactories, componentTemplateFactory) { + var visitor = new CommandBuilderVisitor(new RuntimeCommandFactory(component, componentTemplateFactory, changeDetectorFactories), 0); + template_ast_1.templateVisitAll(visitor, template); + return visitor.result; + }; + CommandCompiler.prototype.compileComponentCodeGen = function(component, template, changeDetectorFactoryExpressions, componentTemplateFactory) { + var visitor = new CommandBuilderVisitor(new CodegenCommandFactory(component, componentTemplateFactory, changeDetectorFactoryExpressions), 0); + template_ast_1.templateVisitAll(visitor, template); + return new source_module_1.SourceExpression([], codeGenArray(visitor.result)); + }; + CommandCompiler = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], CommandCompiler); + return CommandCompiler; + })(); + exports.CommandCompiler = CommandCompiler; + var RuntimeCommandFactory = (function() { + function RuntimeCommandFactory(component, componentTemplateFactory, changeDetectorFactories) { + this.component = component; + this.componentTemplateFactory = componentTemplateFactory; + this.changeDetectorFactories = changeDetectorFactories; + } + RuntimeCommandFactory.prototype._mapDirectives = function(directives) { + return directives.map(function(directive) { + return directive.type.runtime; + }); + }; + RuntimeCommandFactory.prototype.createText = function(value, isBound, ngContentIndex) { + return new template_commands_1.TextCmd(value, isBound, ngContentIndex); + }; + RuntimeCommandFactory.prototype.createNgContent = function(index, ngContentIndex) { + return new template_commands_1.NgContentCmd(index, ngContentIndex); + }; + RuntimeCommandFactory.prototype.createBeginElement = function(name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, directives, isBound, ngContentIndex) { + return new template_commands_1.BeginElementCmd(name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, this._mapDirectives(directives), isBound, ngContentIndex); + }; + RuntimeCommandFactory.prototype.createEndElement = function() { + return new template_commands_1.EndElementCmd(); + }; + RuntimeCommandFactory.prototype.createBeginComponent = function(name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, directives, encapsulation, ngContentIndex) { + var nestedTemplateAccessor = this.componentTemplateFactory(directives[0]); + return new template_commands_1.BeginComponentCmd(name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, this._mapDirectives(directives), encapsulation, ngContentIndex, nestedTemplateAccessor); + }; + RuntimeCommandFactory.prototype.createEndComponent = function() { + return new template_commands_1.EndComponentCmd(); + }; + RuntimeCommandFactory.prototype.createEmbeddedTemplate = function(embeddedTemplateIndex, attrNameAndValues, variableNameAndValues, directives, isMerged, ngContentIndex, children) { + return new template_commands_1.EmbeddedTemplateCmd(attrNameAndValues, variableNameAndValues, this._mapDirectives(directives), isMerged, ngContentIndex, this.changeDetectorFactories[embeddedTemplateIndex], children); + }; + return RuntimeCommandFactory; + })(); + var CodegenCommandFactory = (function() { + function CodegenCommandFactory(component, componentTemplateFactory, changeDetectorFactoryExpressions) { + this.component = component; + this.componentTemplateFactory = componentTemplateFactory; + this.changeDetectorFactoryExpressions = changeDetectorFactoryExpressions; + } + CodegenCommandFactory.prototype.createText = function(value, isBound, ngContentIndex) { + return new Expression(util_1.codeGenConstConstructorCall(exports.TEMPLATE_COMMANDS_MODULE_REF + 'TextCmd') + "(" + util_1.escapeSingleQuoteString(value) + ", " + isBound + ", " + ngContentIndex + ")"); + }; + CodegenCommandFactory.prototype.createNgContent = function(index, ngContentIndex) { + return new Expression(util_1.codeGenConstConstructorCall(exports.TEMPLATE_COMMANDS_MODULE_REF + 'NgContentCmd') + "(" + index + ", " + ngContentIndex + ")"); + }; + CodegenCommandFactory.prototype.createBeginElement = function(name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, directives, isBound, ngContentIndex) { + var attrsExpression = codeGenArray(attrNameAndValues); + return new Expression((util_1.codeGenConstConstructorCall(exports.TEMPLATE_COMMANDS_MODULE_REF + 'BeginElementCmd') + "(" + util_1.escapeSingleQuoteString(name) + ", " + attrsExpression + ", ") + (codeGenArray(eventTargetAndNames) + ", " + codeGenArray(variableNameAndValues) + ", " + codeGenDirectivesArray(directives) + ", " + isBound + ", " + ngContentIndex + ")")); + }; + CodegenCommandFactory.prototype.createEndElement = function() { + return new Expression(util_1.codeGenConstConstructorCall(exports.TEMPLATE_COMMANDS_MODULE_REF + 'EndElementCmd') + "()"); + }; + CodegenCommandFactory.prototype.createBeginComponent = function(name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, directives, encapsulation, ngContentIndex) { + var attrsExpression = codeGenArray(attrNameAndValues); + return new Expression((util_1.codeGenConstConstructorCall(exports.TEMPLATE_COMMANDS_MODULE_REF + 'BeginComponentCmd') + "(" + util_1.escapeSingleQuoteString(name) + ", " + attrsExpression + ", ") + (codeGenArray(eventTargetAndNames) + ", " + codeGenArray(variableNameAndValues) + ", " + codeGenDirectivesArray(directives) + ", " + codeGenViewEncapsulation(encapsulation) + ", " + ngContentIndex + ", " + this.componentTemplateFactory(directives[0]) + ")")); + }; + CodegenCommandFactory.prototype.createEndComponent = function() { + return new Expression(util_1.codeGenConstConstructorCall(exports.TEMPLATE_COMMANDS_MODULE_REF + 'EndComponentCmd') + "()"); + }; + CodegenCommandFactory.prototype.createEmbeddedTemplate = function(embeddedTemplateIndex, attrNameAndValues, variableNameAndValues, directives, isMerged, ngContentIndex, children) { + return new Expression((util_1.codeGenConstConstructorCall(exports.TEMPLATE_COMMANDS_MODULE_REF + 'EmbeddedTemplateCmd') + "(" + codeGenArray(attrNameAndValues) + ", " + codeGenArray(variableNameAndValues) + ", ") + (codeGenDirectivesArray(directives) + ", " + isMerged + ", " + ngContentIndex + ", " + this.changeDetectorFactoryExpressions[embeddedTemplateIndex] + ", " + codeGenArray(children) + ")")); + }; + return CodegenCommandFactory; + })(); + function visitAndReturnContext(visitor, asts, context) { + template_ast_1.templateVisitAll(visitor, asts, context); + return context; + } + var CommandBuilderVisitor = (function() { + function CommandBuilderVisitor(commandFactory, embeddedTemplateIndex) { + this.commandFactory = commandFactory; + this.embeddedTemplateIndex = embeddedTemplateIndex; + this.result = []; + this.transitiveNgContentCount = 0; + } + CommandBuilderVisitor.prototype._readAttrNameAndValues = function(directives, attrAsts) { + var attrs = keyValueArrayToMap(visitAndReturnContext(this, attrAsts, [])); + directives.forEach(function(directiveMeta) { + collection_1.StringMapWrapper.forEach(directiveMeta.hostAttributes, function(value, name) { + var prevValue = attrs[name]; + attrs[name] = lang_1.isPresent(prevValue) ? mergeAttributeValue(name, prevValue, value) : value; + }); + }); + return mapToKeyValueArray(attrs); + }; + CommandBuilderVisitor.prototype.visitNgContent = function(ast, context) { + this.transitiveNgContentCount++; + this.result.push(this.commandFactory.createNgContent(ast.index, ast.ngContentIndex)); + return null; + }; + CommandBuilderVisitor.prototype.visitEmbeddedTemplate = function(ast, context) { + var _this = this; + this.embeddedTemplateIndex++; + var childVisitor = new CommandBuilderVisitor(this.commandFactory, this.embeddedTemplateIndex); + template_ast_1.templateVisitAll(childVisitor, ast.children); + var isMerged = childVisitor.transitiveNgContentCount > 0; + var variableNameAndValues = []; + ast.vars.forEach(function(varAst) { + variableNameAndValues.push(varAst.name); + variableNameAndValues.push(varAst.value.length > 0 ? varAst.value : IMPLICIT_TEMPLATE_VAR); + }); + var directives = []; + collection_1.ListWrapper.forEachWithIndex(ast.directives, function(directiveAst, index) { + directiveAst.visit(_this, new DirectiveContext(index, [], [], directives)); + }); + this.result.push(this.commandFactory.createEmbeddedTemplate(this.embeddedTemplateIndex, this._readAttrNameAndValues(directives, ast.attrs), variableNameAndValues, directives, isMerged, ast.ngContentIndex, childVisitor.result)); + this.transitiveNgContentCount += childVisitor.transitiveNgContentCount; + this.embeddedTemplateIndex = childVisitor.embeddedTemplateIndex; + return null; + }; + CommandBuilderVisitor.prototype.visitElement = function(ast, context) { + var _this = this; + var component = ast.getComponent(); + var eventTargetAndNames = visitAndReturnContext(this, ast.outputs, []); + var variableNameAndValues = []; + if (lang_1.isBlank(component)) { + ast.exportAsVars.forEach(function(varAst) { + variableNameAndValues.push(varAst.name); + variableNameAndValues.push(null); + }); + } + var directives = []; + collection_1.ListWrapper.forEachWithIndex(ast.directives, function(directiveAst, index) { + directiveAst.visit(_this, new DirectiveContext(index, eventTargetAndNames, variableNameAndValues, directives)); + }); + eventTargetAndNames = removeKeyValueArrayDuplicates(eventTargetAndNames); + var attrNameAndValues = this._readAttrNameAndValues(directives, ast.attrs); + if (lang_1.isPresent(component)) { + this.result.push(this.commandFactory.createBeginComponent(ast.name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, directives, component.template.encapsulation, ast.ngContentIndex)); + template_ast_1.templateVisitAll(this, ast.children); + this.result.push(this.commandFactory.createEndComponent()); + } else { + this.result.push(this.commandFactory.createBeginElement(ast.name, attrNameAndValues, eventTargetAndNames, variableNameAndValues, directives, ast.isBound(), ast.ngContentIndex)); + template_ast_1.templateVisitAll(this, ast.children); + this.result.push(this.commandFactory.createEndElement()); + } + return null; + }; + CommandBuilderVisitor.prototype.visitVariable = function(ast, ctx) { + return null; + }; + CommandBuilderVisitor.prototype.visitAttr = function(ast, attrNameAndValues) { + attrNameAndValues.push(ast.name); + attrNameAndValues.push(ast.value); + return null; + }; + CommandBuilderVisitor.prototype.visitBoundText = function(ast, context) { + this.result.push(this.commandFactory.createText(null, true, ast.ngContentIndex)); + return null; + }; + CommandBuilderVisitor.prototype.visitText = function(ast, context) { + this.result.push(this.commandFactory.createText(ast.value, false, ast.ngContentIndex)); + return null; + }; + CommandBuilderVisitor.prototype.visitDirective = function(ast, ctx) { + ctx.targetDirectives.push(ast.directive); + template_ast_1.templateVisitAll(this, ast.hostEvents, ctx.eventTargetAndNames); + ast.exportAsVars.forEach(function(varAst) { + ctx.targetVariableNameAndValues.push(varAst.name); + ctx.targetVariableNameAndValues.push(ctx.index); + }); + return null; + }; + CommandBuilderVisitor.prototype.visitEvent = function(ast, eventTargetAndNames) { + eventTargetAndNames.push(ast.target); + eventTargetAndNames.push(ast.name); + return null; + }; + CommandBuilderVisitor.prototype.visitDirectiveProperty = function(ast, context) { + return null; + }; + CommandBuilderVisitor.prototype.visitElementProperty = function(ast, context) { + return null; + }; + return CommandBuilderVisitor; + })(); + function removeKeyValueArrayDuplicates(keyValueArray) { + var knownPairs = new Set(); + var resultKeyValueArray = []; + for (var i = 0; i < keyValueArray.length; i += 2) { + var key = keyValueArray[i]; + var value = keyValueArray[i + 1]; + var pairId = key + ":" + value; + if (!collection_1.SetWrapper.has(knownPairs, pairId)) { + resultKeyValueArray.push(key); + resultKeyValueArray.push(value); + knownPairs.add(pairId); + } + } + return resultKeyValueArray; + } + function keyValueArrayToMap(keyValueArr) { + var data = {}; + for (var i = 0; i < keyValueArr.length; i += 2) { + data[keyValueArr[i]] = keyValueArr[i + 1]; + } + return data; + } + function mapToKeyValueArray(data) { + var entryArray = []; + collection_1.StringMapWrapper.forEach(data, function(value, name) { + entryArray.push([name, value]); + }); + collection_1.ListWrapper.sort(entryArray, function(entry1, entry2) { + return lang_1.StringWrapper.compare(entry1[0], entry2[0]); + }); + var keyValueArray = []; + entryArray.forEach(function(entry) { + keyValueArray.push(entry[0]); + keyValueArray.push(entry[1]); + }); + return keyValueArray; + } + function mergeAttributeValue(attrName, attrValue1, attrValue2) { + if (attrName == CLASS_ATTR || attrName == STYLE_ATTR) { + return attrValue1 + " " + attrValue2; + } else { + return attrValue2; + } + } + var DirectiveContext = (function() { + function DirectiveContext(index, eventTargetAndNames, targetVariableNameAndValues, targetDirectives) { + this.index = index; + this.eventTargetAndNames = eventTargetAndNames; + this.targetVariableNameAndValues = targetVariableNameAndValues; + this.targetDirectives = targetDirectives; + } + return DirectiveContext; + })(); + var Expression = (function() { + function Expression(value) { + this.value = value; + } + return Expression; + })(); + function escapeValue(value) { + if (value instanceof Expression) { + return value.value; + } else if (lang_1.isString(value)) { + return util_1.escapeSingleQuoteString(value); + } else if (lang_1.isBlank(value)) { + return 'null'; + } else { + return "" + value; + } + } + function codeGenArray(data) { + var base = "[" + data.map(escapeValue).join(',') + "]"; + return lang_1.IS_DART ? "const " + base : base; + } + function codeGenDirectivesArray(directives) { + var expressions = directives.map(function(directiveType) { + return ("" + source_module_1.moduleRef(directiveType.type.moduleUrl) + directiveType.type.name); + }); + var base = "[" + expressions.join(',') + "]"; + return lang_1.IS_DART ? "const " + base : base; + } + function codeGenViewEncapsulation(value) { + if (lang_1.IS_DART) { + return "" + exports.TEMPLATE_COMMANDS_MODULE_REF + value; + } else { + return "" + value; + } + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/html_ast", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var HtmlTextAst = (function() { + function HtmlTextAst(value, sourceSpan) { + this.value = value; + this.sourceSpan = sourceSpan; + } + HtmlTextAst.prototype.visit = function(visitor, context) { + return visitor.visitText(this, context); + }; + return HtmlTextAst; + })(); + exports.HtmlTextAst = HtmlTextAst; + var HtmlAttrAst = (function() { + function HtmlAttrAst(name, value, sourceSpan) { + this.name = name; + this.value = value; + this.sourceSpan = sourceSpan; + } + HtmlAttrAst.prototype.visit = function(visitor, context) { + return visitor.visitAttr(this, context); + }; + return HtmlAttrAst; + })(); + exports.HtmlAttrAst = HtmlAttrAst; + var HtmlElementAst = (function() { + function HtmlElementAst(name, attrs, children, sourceSpan) { + this.name = name; + this.attrs = attrs; + this.children = children; + this.sourceSpan = sourceSpan; + } + HtmlElementAst.prototype.visit = function(visitor, context) { + return visitor.visitElement(this, context); + }; + return HtmlElementAst; + })(); + exports.HtmlElementAst = HtmlElementAst; + function htmlVisitAll(visitor, asts, context) { + if (context === void 0) { + context = null; + } + var result = []; + asts.forEach(function(ast) { + var astResult = ast.visit(visitor, context); + if (lang_1.isPresent(astResult)) { + result.push(astResult); + } + }); + return result; + } + exports.htmlVisitAll = htmlVisitAll; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/parse_util", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var ParseLocation = (function() { + function ParseLocation(file, offset, line, col) { + this.file = file; + this.offset = offset; + this.line = line; + this.col = col; + } + ParseLocation.prototype.toString = function() { + return this.file.url + "@" + this.line + ":" + this.col; + }; + return ParseLocation; + })(); + exports.ParseLocation = ParseLocation; + var ParseSourceFile = (function() { + function ParseSourceFile(content, url) { + this.content = content; + this.url = url; + } + return ParseSourceFile; + })(); + exports.ParseSourceFile = ParseSourceFile; + var ParseError = (function() { + function ParseError(location, msg) { + this.location = location; + this.msg = msg; + } + ParseError.prototype.toString = function() { + var source = this.location.file.content; + var ctxStart = this.location.offset; + if (ctxStart > source.length - 1) { + ctxStart = source.length - 1; + } + var ctxEnd = ctxStart; + var ctxLen = 0; + var ctxLines = 0; + while (ctxLen < 100 && ctxStart > 0) { + ctxStart--; + ctxLen++; + if (source[ctxStart] == "\n") { + if (++ctxLines == 3) { + break; + } + } + } + ctxLen = 0; + ctxLines = 0; + while (ctxLen < 100 && ctxEnd < source.length - 1) { + ctxEnd++; + ctxLen++; + if (source[ctxEnd] == "\n") { + if (++ctxLines == 3) { + break; + } + } + } + var context = source.substring(ctxStart, this.location.offset) + '[ERROR ->]' + source.substring(this.location.offset, ctxEnd + 1); + return this.msg + " (\"" + context + "\"): " + this.location; + }; + return ParseError; + })(); + exports.ParseError = ParseError; + var ParseSourceSpan = (function() { + function ParseSourceSpan(start, end) { + this.start = start; + this.end = end; + } + ParseSourceSpan.prototype.toString = function() { + return this.start.file.content.substring(this.start.offset, this.end.offset); + }; + return ParseSourceSpan; + })(); + exports.ParseSourceSpan = ParseSourceSpan; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/html_tags", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + exports.NAMED_ENTITIES = lang_1.CONST_EXPR({ + 'Aacute': '\u00C1', + 'aacute': '\u00E1', + 'Acirc': '\u00C2', + 'acirc': '\u00E2', + 'acute': '\u00B4', + 'AElig': '\u00C6', + 'aelig': '\u00E6', + 'Agrave': '\u00C0', + 'agrave': '\u00E0', + 'alefsym': '\u2135', + 'Alpha': '\u0391', + 'alpha': '\u03B1', + 'amp': '&', + 'and': '\u2227', + 'ang': '\u2220', + 'apos': '\u0027', + 'Aring': '\u00C5', + 'aring': '\u00E5', + 'asymp': '\u2248', + 'Atilde': '\u00C3', + 'atilde': '\u00E3', + 'Auml': '\u00C4', + 'auml': '\u00E4', + 'bdquo': '\u201E', + 'Beta': '\u0392', + 'beta': '\u03B2', + 'brvbar': '\u00A6', + 'bull': '\u2022', + 'cap': '\u2229', + 'Ccedil': '\u00C7', + 'ccedil': '\u00E7', + 'cedil': '\u00B8', + 'cent': '\u00A2', + 'Chi': '\u03A7', + 'chi': '\u03C7', + 'circ': '\u02C6', + 'clubs': '\u2663', + 'cong': '\u2245', + 'copy': '\u00A9', + 'crarr': '\u21B5', + 'cup': '\u222A', + 'curren': '\u00A4', + 'dagger': '\u2020', + 'Dagger': '\u2021', + 'darr': '\u2193', + 'dArr': '\u21D3', + 'deg': '\u00B0', + 'Delta': '\u0394', + 'delta': '\u03B4', + 'diams': '\u2666', + 'divide': '\u00F7', + 'Eacute': '\u00C9', + 'eacute': '\u00E9', + 'Ecirc': '\u00CA', + 'ecirc': '\u00EA', + 'Egrave': '\u00C8', + 'egrave': '\u00E8', + 'empty': '\u2205', + 'emsp': '\u2003', + 'ensp': '\u2002', + 'Epsilon': '\u0395', + 'epsilon': '\u03B5', + 'equiv': '\u2261', + 'Eta': '\u0397', + 'eta': '\u03B7', + 'ETH': '\u00D0', + 'eth': '\u00F0', + 'Euml': '\u00CB', + 'euml': '\u00EB', + 'euro': '\u20AC', + 'exist': '\u2203', + 'fnof': '\u0192', + 'forall': '\u2200', + 'frac12': '\u00BD', + 'frac14': '\u00BC', + 'frac34': '\u00BE', + 'frasl': '\u2044', + 'Gamma': '\u0393', + 'gamma': '\u03B3', + 'ge': '\u2265', + 'gt': '>', + 'harr': '\u2194', + 'hArr': '\u21D4', + 'hearts': '\u2665', + 'hellip': '\u2026', + 'Iacute': '\u00CD', + 'iacute': '\u00ED', + 'Icirc': '\u00CE', + 'icirc': '\u00EE', + 'iexcl': '\u00A1', + 'Igrave': '\u00CC', + 'igrave': '\u00EC', + 'image': '\u2111', + 'infin': '\u221E', + 'int': '\u222B', + 'Iota': '\u0399', + 'iota': '\u03B9', + 'iquest': '\u00BF', + 'isin': '\u2208', + 'Iuml': '\u00CF', + 'iuml': '\u00EF', + 'Kappa': '\u039A', + 'kappa': '\u03BA', + 'Lambda': '\u039B', + 'lambda': '\u03BB', + 'lang': '\u27E8', + 'laquo': '\u00AB', + 'larr': '\u2190', + 'lArr': '\u21D0', + 'lceil': '\u2308', + 'ldquo': '\u201C', + 'le': '\u2264', + 'lfloor': '\u230A', + 'lowast': '\u2217', + 'loz': '\u25CA', + 'lrm': '\u200E', + 'lsaquo': '\u2039', + 'lsquo': '\u2018', + 'lt': '<', + 'macr': '\u00AF', + 'mdash': '\u2014', + 'micro': '\u00B5', + 'middot': '\u00B7', + 'minus': '\u2212', + 'Mu': '\u039C', + 'mu': '\u03BC', + 'nabla': '\u2207', + 'nbsp': '\u00A0', + 'ndash': '\u2013', + 'ne': '\u2260', + 'ni': '\u220B', + 'not': '\u00AC', + 'notin': '\u2209', + 'nsub': '\u2284', + 'Ntilde': '\u00D1', + 'ntilde': '\u00F1', + 'Nu': '\u039D', + 'nu': '\u03BD', + 'Oacute': '\u00D3', + 'oacute': '\u00F3', + 'Ocirc': '\u00D4', + 'ocirc': '\u00F4', + 'OElig': '\u0152', + 'oelig': '\u0153', + 'Ograve': '\u00D2', + 'ograve': '\u00F2', + 'oline': '\u203E', + 'Omega': '\u03A9', + 'omega': '\u03C9', + 'Omicron': '\u039F', + 'omicron': '\u03BF', + 'oplus': '\u2295', + 'or': '\u2228', + 'ordf': '\u00AA', + 'ordm': '\u00BA', + 'Oslash': '\u00D8', + 'oslash': '\u00F8', + 'Otilde': '\u00D5', + 'otilde': '\u00F5', + 'otimes': '\u2297', + 'Ouml': '\u00D6', + 'ouml': '\u00F6', + 'para': '\u00B6', + 'permil': '\u2030', + 'perp': '\u22A5', + 'Phi': '\u03A6', + 'phi': '\u03C6', + 'Pi': '\u03A0', + 'pi': '\u03C0', + 'piv': '\u03D6', + 'plusmn': '\u00B1', + 'pound': '\u00A3', + 'prime': '\u2032', + 'Prime': '\u2033', + 'prod': '\u220F', + 'prop': '\u221D', + 'Psi': '\u03A8', + 'psi': '\u03C8', + 'quot': '\u0022', + 'radic': '\u221A', + 'rang': '\u27E9', + 'raquo': '\u00BB', + 'rarr': '\u2192', + 'rArr': '\u21D2', + 'rceil': '\u2309', + 'rdquo': '\u201D', + 'real': '\u211C', + 'reg': '\u00AE', + 'rfloor': '\u230B', + 'Rho': '\u03A1', + 'rho': '\u03C1', + 'rlm': '\u200F', + 'rsaquo': '\u203A', + 'rsquo': '\u2019', + 'sbquo': '\u201A', + 'Scaron': '\u0160', + 'scaron': '\u0161', + 'sdot': '\u22C5', + 'sect': '\u00A7', + 'shy': '\u00AD', + 'Sigma': '\u03A3', + 'sigma': '\u03C3', + 'sigmaf': '\u03C2', + 'sim': '\u223C', + 'spades': '\u2660', + 'sub': '\u2282', + 'sube': '\u2286', + 'sum': '\u2211', + 'sup': '\u2283', + 'sup1': '\u00B9', + 'sup2': '\u00B2', + 'sup3': '\u00B3', + 'supe': '\u2287', + 'szlig': '\u00DF', + 'Tau': '\u03A4', + 'tau': '\u03C4', + 'there4': '\u2234', + 'Theta': '\u0398', + 'theta': '\u03B8', + 'thetasym': '\u03D1', + 'thinsp': '\u2009', + 'THORN': '\u00DE', + 'thorn': '\u00FE', + 'tilde': '\u02DC', + 'times': '\u00D7', + 'trade': '\u2122', + 'Uacute': '\u00DA', + 'uacute': '\u00FA', + 'uarr': '\u2191', + 'uArr': '\u21D1', + 'Ucirc': '\u00DB', + 'ucirc': '\u00FB', + 'Ugrave': '\u00D9', + 'ugrave': '\u00F9', + 'uml': '\u00A8', + 'upsih': '\u03D2', + 'Upsilon': '\u03A5', + 'upsilon': '\u03C5', + 'Uuml': '\u00DC', + 'uuml': '\u00FC', + 'weierp': '\u2118', + 'Xi': '\u039E', + 'xi': '\u03BE', + 'Yacute': '\u00DD', + 'yacute': '\u00FD', + 'yen': '\u00A5', + 'yuml': '\u00FF', + 'Yuml': '\u0178', + 'Zeta': '\u0396', + 'zeta': '\u03B6', + 'zwj': '\u200D', + 'zwnj': '\u200C' + }); + (function(HtmlTagContentType) { + HtmlTagContentType[HtmlTagContentType["RAW_TEXT"] = 0] = "RAW_TEXT"; + HtmlTagContentType[HtmlTagContentType["ESCAPABLE_RAW_TEXT"] = 1] = "ESCAPABLE_RAW_TEXT"; + HtmlTagContentType[HtmlTagContentType["PARSABLE_DATA"] = 2] = "PARSABLE_DATA"; + })(exports.HtmlTagContentType || (exports.HtmlTagContentType = {})); + var HtmlTagContentType = exports.HtmlTagContentType; + var HtmlTagDefinition = (function() { + function HtmlTagDefinition(_a) { + var _this = this; + var _b = _a === void 0 ? {} : _a, + closedByChildren = _b.closedByChildren, + requiredParents = _b.requiredParents, + implicitNamespacePrefix = _b.implicitNamespacePrefix, + contentType = _b.contentType, + closedByParent = _b.closedByParent, + isVoid = _b.isVoid, + ignoreFirstLf = _b.ignoreFirstLf; + this.closedByChildren = {}; + this.closedByParent = false; + if (lang_1.isPresent(closedByChildren) && closedByChildren.length > 0) { + closedByChildren.forEach(function(tagName) { + return _this.closedByChildren[tagName] = true; + }); + } + this.isVoid = lang_1.normalizeBool(isVoid); + this.closedByParent = lang_1.normalizeBool(closedByParent) || this.isVoid; + if (lang_1.isPresent(requiredParents) && requiredParents.length > 0) { + this.requiredParents = {}; + this.parentToAdd = requiredParents[0]; + requiredParents.forEach(function(tagName) { + return _this.requiredParents[tagName] = true; + }); + } + this.implicitNamespacePrefix = implicitNamespacePrefix; + this.contentType = lang_1.isPresent(contentType) ? contentType : HtmlTagContentType.PARSABLE_DATA; + this.ignoreFirstLf = lang_1.normalizeBool(ignoreFirstLf); + } + HtmlTagDefinition.prototype.requireExtraParent = function(currentParent) { + if (lang_1.isBlank(this.requiredParents)) { + return false; + } + if (lang_1.isBlank(currentParent)) { + return true; + } + var lcParent = currentParent.toLowerCase(); + return this.requiredParents[lcParent] != true && lcParent != 'template'; + }; + HtmlTagDefinition.prototype.isClosedByChild = function(name) { + return this.isVoid || lang_1.normalizeBool(this.closedByChildren[name.toLowerCase()]); + }; + return HtmlTagDefinition; + })(); + exports.HtmlTagDefinition = HtmlTagDefinition; + var TAG_DEFINITIONS = { + 'area': new HtmlTagDefinition({isVoid: true}), + 'embed': new HtmlTagDefinition({isVoid: true}), + 'link': new HtmlTagDefinition({isVoid: true}), + 'img': new HtmlTagDefinition({isVoid: true}), + 'input': new HtmlTagDefinition({isVoid: true}), + 'param': new HtmlTagDefinition({isVoid: true}), + 'hr': new HtmlTagDefinition({isVoid: true}), + 'br': new HtmlTagDefinition({isVoid: true}), + 'source': new HtmlTagDefinition({isVoid: true}), + 'track': new HtmlTagDefinition({isVoid: true}), + 'wbr': new HtmlTagDefinition({isVoid: true}), + 'p': new HtmlTagDefinition({ + closedByChildren: ['address', 'article', 'aside', 'blockquote', 'div', 'dl', 'fieldset', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul'], + closedByParent: true + }), + 'thead': new HtmlTagDefinition({closedByChildren: ['tbody', 'tfoot']}), + 'tbody': new HtmlTagDefinition({ + closedByChildren: ['tbody', 'tfoot'], + closedByParent: true + }), + 'tfoot': new HtmlTagDefinition({ + closedByChildren: ['tbody'], + closedByParent: true + }), + 'tr': new HtmlTagDefinition({ + closedByChildren: ['tr'], + requiredParents: ['tbody', 'tfoot', 'thead'], + closedByParent: true + }), + 'td': new HtmlTagDefinition({ + closedByChildren: ['td', 'th'], + closedByParent: true + }), + 'th': new HtmlTagDefinition({ + closedByChildren: ['td', 'th'], + closedByParent: true + }), + 'col': new HtmlTagDefinition({ + requiredParents: ['colgroup'], + isVoid: true + }), + 'svg': new HtmlTagDefinition({implicitNamespacePrefix: 'svg'}), + 'math': new HtmlTagDefinition({implicitNamespacePrefix: 'math'}), + 'li': new HtmlTagDefinition({ + closedByChildren: ['li'], + closedByParent: true + }), + 'dt': new HtmlTagDefinition({closedByChildren: ['dt', 'dd']}), + 'dd': new HtmlTagDefinition({ + closedByChildren: ['dt', 'dd'], + closedByParent: true + }), + 'rb': new HtmlTagDefinition({ + closedByChildren: ['rb', 'rt', 'rtc', 'rp'], + closedByParent: true + }), + 'rt': new HtmlTagDefinition({ + closedByChildren: ['rb', 'rt', 'rtc', 'rp'], + closedByParent: true + }), + 'rtc': new HtmlTagDefinition({ + closedByChildren: ['rb', 'rtc', 'rp'], + closedByParent: true + }), + 'rp': new HtmlTagDefinition({ + closedByChildren: ['rb', 'rt', 'rtc', 'rp'], + closedByParent: true + }), + 'optgroup': new HtmlTagDefinition({ + closedByChildren: ['optgroup'], + closedByParent: true + }), + 'option': new HtmlTagDefinition({ + closedByChildren: ['option', 'optgroup'], + closedByParent: true + }), + 'pre': new HtmlTagDefinition({ignoreFirstLf: true}), + 'listing': new HtmlTagDefinition({ignoreFirstLf: true}), + 'style': new HtmlTagDefinition({contentType: HtmlTagContentType.RAW_TEXT}), + 'script': new HtmlTagDefinition({contentType: HtmlTagContentType.RAW_TEXT}), + 'title': new HtmlTagDefinition({contentType: HtmlTagContentType.ESCAPABLE_RAW_TEXT}), + 'textarea': new HtmlTagDefinition({ + contentType: HtmlTagContentType.ESCAPABLE_RAW_TEXT, + ignoreFirstLf: true + }) + }; + var DEFAULT_TAG_DEFINITION = new HtmlTagDefinition(); + function getHtmlTagDefinition(tagName) { + var result = TAG_DEFINITIONS[tagName.toLowerCase()]; + return lang_1.isPresent(result) ? result : DEFAULT_TAG_DEFINITION; + } + exports.getHtmlTagDefinition = getHtmlTagDefinition; + var NS_PREFIX_RE = /^@([^:]+):(.+)/g; + function splitNsName(elementName) { + if (elementName[0] != '@') { + return [null, elementName]; + } + var match = lang_1.RegExpWrapper.firstMatch(NS_PREFIX_RE, elementName); + return [match[1], match[2]]; + } + exports.splitNsName = splitNsName; + function getNsPrefix(elementName) { + return splitNsName(elementName)[0]; + } + exports.getNsPrefix = getNsPrefix; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/schema/element_schema_registry", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var ElementSchemaRegistry = (function() { + function ElementSchemaRegistry() {} + ElementSchemaRegistry.prototype.hasProperty = function(tagName, propName) { + return true; + }; + ElementSchemaRegistry.prototype.getMappedPropName = function(propName) { + return propName; + }; + return ElementSchemaRegistry; + })(); + exports.ElementSchemaRegistry = ElementSchemaRegistry; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/template_preparser", ["angular2/src/facade/lang", "angular2/src/compiler/html_tags"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var html_tags_1 = require("angular2/src/compiler/html_tags"); + var NG_CONTENT_SELECT_ATTR = 'select'; + var NG_CONTENT_ELEMENT = 'ng-content'; + var LINK_ELEMENT = 'link'; + var LINK_STYLE_REL_ATTR = 'rel'; + var LINK_STYLE_HREF_ATTR = 'href'; + var LINK_STYLE_REL_VALUE = 'stylesheet'; + var STYLE_ELEMENT = 'style'; + var SCRIPT_ELEMENT = 'script'; + var NG_NON_BINDABLE_ATTR = 'ngNonBindable'; + function preparseElement(ast) { + var selectAttr = null; + var hrefAttr = null; + var relAttr = null; + var nonBindable = false; + ast.attrs.forEach(function(attr) { + var lcAttrName = attr.name.toLowerCase(); + if (lcAttrName == NG_CONTENT_SELECT_ATTR) { + selectAttr = attr.value; + } else if (lcAttrName == LINK_STYLE_HREF_ATTR) { + hrefAttr = attr.value; + } else if (lcAttrName == LINK_STYLE_REL_ATTR) { + relAttr = attr.value; + } else if (attr.name == NG_NON_BINDABLE_ATTR) { + nonBindable = true; + } + }); + selectAttr = normalizeNgContentSelect(selectAttr); + var nodeName = ast.name.toLowerCase(); + var type = PreparsedElementType.OTHER; + if (html_tags_1.splitNsName(nodeName)[1] == NG_CONTENT_ELEMENT) { + type = PreparsedElementType.NG_CONTENT; + } else if (nodeName == STYLE_ELEMENT) { + type = PreparsedElementType.STYLE; + } else if (nodeName == SCRIPT_ELEMENT) { + type = PreparsedElementType.SCRIPT; + } else if (nodeName == LINK_ELEMENT && relAttr == LINK_STYLE_REL_VALUE) { + type = PreparsedElementType.STYLESHEET; + } + return new PreparsedElement(type, selectAttr, hrefAttr, nonBindable); + } + exports.preparseElement = preparseElement; + (function(PreparsedElementType) { + PreparsedElementType[PreparsedElementType["NG_CONTENT"] = 0] = "NG_CONTENT"; + PreparsedElementType[PreparsedElementType["STYLE"] = 1] = "STYLE"; + PreparsedElementType[PreparsedElementType["STYLESHEET"] = 2] = "STYLESHEET"; + PreparsedElementType[PreparsedElementType["SCRIPT"] = 3] = "SCRIPT"; + PreparsedElementType[PreparsedElementType["OTHER"] = 4] = "OTHER"; + })(exports.PreparsedElementType || (exports.PreparsedElementType = {})); + var PreparsedElementType = exports.PreparsedElementType; + var PreparsedElement = (function() { + function PreparsedElement(type, selectAttr, hrefAttr, nonBindable) { + this.type = type; + this.selectAttr = selectAttr; + this.hrefAttr = hrefAttr; + this.nonBindable = nonBindable; + } + return PreparsedElement; + })(); + exports.PreparsedElement = PreparsedElement; + function normalizeNgContentSelect(selectAttr) { + if (lang_1.isBlank(selectAttr) || selectAttr.length === 0) { + return '*'; + } + return selectAttr; + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/template_normalizer", ["angular2/src/compiler/directive_metadata", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/async", "angular2/src/compiler/xhr", "angular2/src/compiler/url_resolver", "angular2/src/compiler/style_url_resolver", "angular2/src/core/di", "angular2/src/core/metadata/view", "angular2/src/compiler/html_ast", "angular2/src/compiler/html_parser", "angular2/src/compiler/template_preparser"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var directive_metadata_1 = require("angular2/src/compiler/directive_metadata"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var async_1 = require("angular2/src/facade/async"); + var xhr_1 = require("angular2/src/compiler/xhr"); + var url_resolver_1 = require("angular2/src/compiler/url_resolver"); + var style_url_resolver_1 = require("angular2/src/compiler/style_url_resolver"); + var di_1 = require("angular2/src/core/di"); + var view_1 = require("angular2/src/core/metadata/view"); + var html_ast_1 = require("angular2/src/compiler/html_ast"); + var html_parser_1 = require("angular2/src/compiler/html_parser"); + var template_preparser_1 = require("angular2/src/compiler/template_preparser"); + var TemplateNormalizer = (function() { + function TemplateNormalizer(_xhr, _urlResolver, _htmlParser) { + this._xhr = _xhr; + this._urlResolver = _urlResolver; + this._htmlParser = _htmlParser; + } + TemplateNormalizer.prototype.normalizeTemplate = function(directiveType, template) { + var _this = this; + if (lang_1.isPresent(template.template)) { + return async_1.PromiseWrapper.resolve(this.normalizeLoadedTemplate(directiveType, template, template.template, directiveType.moduleUrl)); + } else if (lang_1.isPresent(template.templateUrl)) { + var sourceAbsUrl = this._urlResolver.resolve(directiveType.moduleUrl, template.templateUrl); + return this._xhr.get(sourceAbsUrl).then(function(templateContent) { + return _this.normalizeLoadedTemplate(directiveType, template, templateContent, sourceAbsUrl); + }); + } else { + throw new exceptions_1.BaseException("No template specified for component " + directiveType.name); + } + }; + TemplateNormalizer.prototype.normalizeLoadedTemplate = function(directiveType, templateMeta, template, templateAbsUrl) { + var _this = this; + var rootNodesAndErrors = this._htmlParser.parse(template, directiveType.name); + if (rootNodesAndErrors.errors.length > 0) { + var errorString = rootNodesAndErrors.errors.join('\n'); + throw new exceptions_1.BaseException("Template parse errors:\n" + errorString); + } + var visitor = new TemplatePreparseVisitor(); + html_ast_1.htmlVisitAll(visitor, rootNodesAndErrors.rootNodes); + var allStyles = templateMeta.styles.concat(visitor.styles); + var allStyleAbsUrls = visitor.styleUrls.filter(style_url_resolver_1.isStyleUrlResolvable).map(function(url) { + return _this._urlResolver.resolve(templateAbsUrl, url); + }).concat(templateMeta.styleUrls.filter(style_url_resolver_1.isStyleUrlResolvable).map(function(url) { + return _this._urlResolver.resolve(directiveType.moduleUrl, url); + })); + var allResolvedStyles = allStyles.map(function(style) { + var styleWithImports = style_url_resolver_1.extractStyleUrls(_this._urlResolver, templateAbsUrl, style); + styleWithImports.styleUrls.forEach(function(styleUrl) { + return allStyleAbsUrls.push(styleUrl); + }); + return styleWithImports.style; + }); + var encapsulation = templateMeta.encapsulation; + if (encapsulation === view_1.ViewEncapsulation.Emulated && allResolvedStyles.length === 0 && allStyleAbsUrls.length === 0) { + encapsulation = view_1.ViewEncapsulation.None; + } + return new directive_metadata_1.CompileTemplateMetadata({ + encapsulation: encapsulation, + template: template, + templateUrl: templateAbsUrl, + styles: allResolvedStyles, + styleUrls: allStyleAbsUrls, + ngContentSelectors: visitor.ngContentSelectors + }); + }; + TemplateNormalizer = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [xhr_1.XHR, url_resolver_1.UrlResolver, html_parser_1.HtmlParser])], TemplateNormalizer); + return TemplateNormalizer; + })(); + exports.TemplateNormalizer = TemplateNormalizer; + var TemplatePreparseVisitor = (function() { + function TemplatePreparseVisitor() { + this.ngContentSelectors = []; + this.styles = []; + this.styleUrls = []; + this.ngNonBindableStackCount = 0; + } + TemplatePreparseVisitor.prototype.visitElement = function(ast, context) { + var preparsedElement = template_preparser_1.preparseElement(ast); + switch (preparsedElement.type) { + case template_preparser_1.PreparsedElementType.NG_CONTENT: + if (this.ngNonBindableStackCount === 0) { + this.ngContentSelectors.push(preparsedElement.selectAttr); + } + break; + case template_preparser_1.PreparsedElementType.STYLE: + var textContent = ''; + ast.children.forEach(function(child) { + if (child instanceof html_ast_1.HtmlTextAst) { + textContent += child.value; + } + }); + this.styles.push(textContent); + break; + case template_preparser_1.PreparsedElementType.STYLESHEET: + this.styleUrls.push(preparsedElement.hrefAttr); + break; + } + if (preparsedElement.nonBindable) { + this.ngNonBindableStackCount++; + } + html_ast_1.htmlVisitAll(this, ast.children); + if (preparsedElement.nonBindable) { + this.ngNonBindableStackCount--; + } + return null; + }; + TemplatePreparseVisitor.prototype.visitAttr = function(ast, context) { + return null; + }; + TemplatePreparseVisitor.prototype.visitText = function(ast, context) { + return null; + }; + return TemplatePreparseVisitor; + })(); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/runtime_metadata", ["angular2/src/core/di", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/compiler/directive_metadata", "angular2/src/core/metadata/directives", "angular2/src/core/linker/directive_resolver", "angular2/src/core/linker/view_resolver", "angular2/src/core/linker/directive_lifecycle_reflector", "angular2/src/core/linker/interfaces", "angular2/src/core/reflection/reflection", "angular2/src/core/di", "angular2/src/core/platform_directives_and_pipes", "angular2/src/compiler/util", "angular2/src/compiler/url_resolver"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var di_1 = require("angular2/src/core/di"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var cpl = require("angular2/src/compiler/directive_metadata"); + var md = require("angular2/src/core/metadata/directives"); + var directive_resolver_1 = require("angular2/src/core/linker/directive_resolver"); + var view_resolver_1 = require("angular2/src/core/linker/view_resolver"); + var directive_lifecycle_reflector_1 = require("angular2/src/core/linker/directive_lifecycle_reflector"); + var interfaces_1 = require("angular2/src/core/linker/interfaces"); + var reflection_1 = require("angular2/src/core/reflection/reflection"); + var di_2 = require("angular2/src/core/di"); + var platform_directives_and_pipes_1 = require("angular2/src/core/platform_directives_and_pipes"); + var util_1 = require("angular2/src/compiler/util"); + var url_resolver_1 = require("angular2/src/compiler/url_resolver"); + var RuntimeMetadataResolver = (function() { + function RuntimeMetadataResolver(_directiveResolver, _viewResolver, _platformDirectives) { + this._directiveResolver = _directiveResolver; + this._viewResolver = _viewResolver; + this._platformDirectives = _platformDirectives; + this._cache = new Map(); + } + RuntimeMetadataResolver.prototype.getMetadata = function(directiveType) { + var meta = this._cache.get(directiveType); + if (lang_1.isBlank(meta)) { + var dirMeta = this._directiveResolver.resolve(directiveType); + var moduleUrl = null; + var templateMeta = null; + var changeDetectionStrategy = null; + if (dirMeta instanceof md.ComponentMetadata) { + var cmpMeta = dirMeta; + moduleUrl = calcModuleUrl(directiveType, cmpMeta); + var viewMeta = this._viewResolver.resolve(directiveType); + templateMeta = new cpl.CompileTemplateMetadata({ + encapsulation: viewMeta.encapsulation, + template: viewMeta.template, + templateUrl: viewMeta.templateUrl, + styles: viewMeta.styles, + styleUrls: viewMeta.styleUrls + }); + changeDetectionStrategy = cmpMeta.changeDetection; + } + meta = cpl.CompileDirectiveMetadata.create({ + selector: dirMeta.selector, + exportAs: dirMeta.exportAs, + isComponent: lang_1.isPresent(templateMeta), + dynamicLoadable: true, + type: new cpl.CompileTypeMetadata({ + name: lang_1.stringify(directiveType), + moduleUrl: moduleUrl, + runtime: directiveType + }), + template: templateMeta, + changeDetection: changeDetectionStrategy, + inputs: dirMeta.inputs, + outputs: dirMeta.outputs, + host: dirMeta.host, + lifecycleHooks: interfaces_1.LIFECYCLE_HOOKS_VALUES.filter(function(hook) { + return directive_lifecycle_reflector_1.hasLifecycleHook(hook, directiveType); + }) + }); + this._cache.set(directiveType, meta); + } + return meta; + }; + RuntimeMetadataResolver.prototype.getViewDirectivesMetadata = function(component) { + var _this = this; + var view = this._viewResolver.resolve(component); + var directives = flattenDirectives(view, this._platformDirectives); + for (var i = 0; i < directives.length; i++) { + if (!isValidDirective(directives[i])) { + throw new exceptions_1.BaseException("Unexpected directive value '" + lang_1.stringify(directives[i]) + "' on the View of component '" + lang_1.stringify(component) + "'"); + } + } + return directives.map(function(type) { + return _this.getMetadata(type); + }); + }; + RuntimeMetadataResolver = __decorate([di_2.Injectable(), __param(2, di_2.Optional()), __param(2, di_2.Inject(platform_directives_and_pipes_1.PLATFORM_DIRECTIVES)), __metadata('design:paramtypes', [directive_resolver_1.DirectiveResolver, view_resolver_1.ViewResolver, Array])], RuntimeMetadataResolver); + return RuntimeMetadataResolver; + })(); + exports.RuntimeMetadataResolver = RuntimeMetadataResolver; + function flattenDirectives(view, platformDirectives) { + var directives = []; + if (lang_1.isPresent(platformDirectives)) { + flattenArray(platformDirectives, directives); + } + if (lang_1.isPresent(view.directives)) { + flattenArray(view.directives, directives); + } + return directives; + } + function flattenArray(tree, out) { + for (var i = 0; i < tree.length; i++) { + var item = di_1.resolveForwardRef(tree[i]); + if (lang_1.isArray(item)) { + flattenArray(item, out); + } else { + out.push(item); + } + } + } + function isValidDirective(value) { + return lang_1.isPresent(value) && (value instanceof lang_1.Type); + } + function calcModuleUrl(type, cmpMetadata) { + var moduleId = cmpMetadata.moduleId; + if (lang_1.isPresent(moduleId)) { + var scheme = url_resolver_1.getUrlScheme(moduleId); + return lang_1.isPresent(scheme) && scheme.length > 0 ? moduleId : "package:" + moduleId + util_1.MODULE_SUFFIX; + } else { + return reflection_1.reflector.importUri(type); + } + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/schema/dom_element_schema_registry", ["angular2/src/core/di", "angular2/src/facade/lang", "angular2/src/facade/collection", "angular2/src/platform/dom/dom_adapter", "angular2/src/compiler/html_tags", "angular2/src/compiler/schema/element_schema_registry"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var di_1 = require("angular2/src/core/di"); + var lang_1 = require("angular2/src/facade/lang"); + var collection_1 = require("angular2/src/facade/collection"); + var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); + var html_tags_1 = require("angular2/src/compiler/html_tags"); + var element_schema_registry_1 = require("angular2/src/compiler/schema/element_schema_registry"); + var NAMESPACE_URIS = lang_1.CONST_EXPR({ + 'xlink': 'http://www.w3.org/1999/xlink', + 'svg': 'http://www.w3.org/2000/svg' + }); + var DomElementSchemaRegistry = (function(_super) { + __extends(DomElementSchemaRegistry, _super); + function DomElementSchemaRegistry() { + _super.apply(this, arguments); + this._protoElements = new Map(); + } + DomElementSchemaRegistry.prototype._getProtoElement = function(tagName) { + var element = this._protoElements.get(tagName); + if (lang_1.isBlank(element)) { + var nsAndName = html_tags_1.splitNsName(tagName); + element = lang_1.isPresent(nsAndName[0]) ? dom_adapter_1.DOM.createElementNS(NAMESPACE_URIS[nsAndName[0]], nsAndName[1]) : dom_adapter_1.DOM.createElement(nsAndName[1]); + this._protoElements.set(tagName, element); + } + return element; + }; + DomElementSchemaRegistry.prototype.hasProperty = function(tagName, propName) { + if (tagName.indexOf('-') !== -1) { + return true; + } else { + var elm = this._getProtoElement(tagName); + return dom_adapter_1.DOM.hasProperty(elm, propName); + } + }; + DomElementSchemaRegistry.prototype.getMappedPropName = function(propName) { + var mappedPropName = collection_1.StringMapWrapper.get(dom_adapter_1.DOM.attrToPropMap, propName); + return lang_1.isPresent(mappedPropName) ? mappedPropName : propName; + }; + DomElementSchemaRegistry = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], DomElementSchemaRegistry); + return DomElementSchemaRegistry; + })(element_schema_registry_1.ElementSchemaRegistry); + exports.DomElementSchemaRegistry = DomElementSchemaRegistry; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/angular_entrypoint", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var AngularEntrypoint = (function() { + function AngularEntrypoint(name) { + this.name = name; + } + AngularEntrypoint = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [String])], AngularEntrypoint); + return AngularEntrypoint; + })(); + exports.AngularEntrypoint = AngularEntrypoint; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/pipes/async_pipe", ["angular2/src/facade/lang", "angular2/src/facade/async", "angular2/core", "angular2/src/common/pipes/invalid_pipe_argument_exception"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var async_1 = require("angular2/src/facade/async"); + var core_1 = require("angular2/core"); + var invalid_pipe_argument_exception_1 = require("angular2/src/common/pipes/invalid_pipe_argument_exception"); + var ObservableStrategy = (function() { + function ObservableStrategy() {} + ObservableStrategy.prototype.createSubscription = function(async, updateLatestValue) { + return async_1.ObservableWrapper.subscribe(async, updateLatestValue, function(e) { + throw e; + }); + }; + ObservableStrategy.prototype.dispose = function(subscription) { + async_1.ObservableWrapper.dispose(subscription); + }; + ObservableStrategy.prototype.onDestroy = function(subscription) { + async_1.ObservableWrapper.dispose(subscription); + }; + return ObservableStrategy; + })(); + var PromiseStrategy = (function() { + function PromiseStrategy() {} + PromiseStrategy.prototype.createSubscription = function(async, updateLatestValue) { + return async.then(updateLatestValue); + }; + PromiseStrategy.prototype.dispose = function(subscription) {}; + PromiseStrategy.prototype.onDestroy = function(subscription) {}; + return PromiseStrategy; + })(); + var _promiseStrategy = new PromiseStrategy(); + var _observableStrategy = new ObservableStrategy(); + var AsyncPipe = (function() { + function AsyncPipe(_ref) { + this._latestValue = null; + this._latestReturnedValue = null; + this._subscription = null; + this._obj = null; + this._strategy = null; + this._ref = _ref; + } + AsyncPipe.prototype.ngOnDestroy = function() { + if (lang_1.isPresent(this._subscription)) { + this._dispose(); + } + }; + AsyncPipe.prototype.transform = function(obj, args) { + if (lang_1.isBlank(this._obj)) { + if (lang_1.isPresent(obj)) { + this._subscribe(obj); + } + return this._latestValue; + } + if (obj !== this._obj) { + this._dispose(); + return this.transform(obj); + } + if (this._latestValue === this._latestReturnedValue) { + return this._latestReturnedValue; + } else { + this._latestReturnedValue = this._latestValue; + return core_1.WrappedValue.wrap(this._latestValue); + } + }; + AsyncPipe.prototype._subscribe = function(obj) { + var _this = this; + this._obj = obj; + this._strategy = this._selectStrategy(obj); + this._subscription = this._strategy.createSubscription(obj, function(value) { + return _this._updateLatestValue(obj, value); + }); + }; + AsyncPipe.prototype._selectStrategy = function(obj) { + if (lang_1.isPromise(obj)) { + return _promiseStrategy; + } else if (async_1.ObservableWrapper.isObservable(obj)) { + return _observableStrategy; + } else { + throw new invalid_pipe_argument_exception_1.InvalidPipeArgumentException(AsyncPipe, obj); + } + }; + AsyncPipe.prototype._dispose = function() { + this._strategy.dispose(this._subscription); + this._latestValue = null; + this._latestReturnedValue = null; + this._subscription = null; + this._obj = null; + }; + AsyncPipe.prototype._updateLatestValue = function(async, value) { + if (async === this._obj) { + this._latestValue = value; + this._ref.markForCheck(); + } + }; + AsyncPipe = __decorate([core_1.Pipe({ + name: 'async', + pure: false + }), core_1.Injectable(), __metadata('design:paramtypes', [core_1.ChangeDetectorRef])], AsyncPipe); + return AsyncPipe; + })(); + exports.AsyncPipe = AsyncPipe; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/pipes/date_pipe", ["angular2/src/facade/lang", "angular2/src/facade/intl", "angular2/core", "angular2/src/facade/collection", "angular2/src/common/pipes/invalid_pipe_argument_exception"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var intl_1 = require("angular2/src/facade/intl"); + var core_1 = require("angular2/core"); + var collection_1 = require("angular2/src/facade/collection"); + var invalid_pipe_argument_exception_1 = require("angular2/src/common/pipes/invalid_pipe_argument_exception"); + var defaultLocale = 'en-US'; + var DatePipe = (function() { + function DatePipe() {} + DatePipe.prototype.transform = function(value, args) { + if (lang_1.isBlank(value)) + return null; + if (!this.supports(value)) { + throw new invalid_pipe_argument_exception_1.InvalidPipeArgumentException(DatePipe, value); + } + var pattern = lang_1.isPresent(args) && args.length > 0 ? args[0] : 'mediumDate'; + if (lang_1.isNumber(value)) { + value = lang_1.DateWrapper.fromMillis(value); + } + if (collection_1.StringMapWrapper.contains(DatePipe._ALIASES, pattern)) { + pattern = collection_1.StringMapWrapper.get(DatePipe._ALIASES, pattern); + } + return intl_1.DateFormatter.format(value, defaultLocale, pattern); + }; + DatePipe.prototype.supports = function(obj) { + return lang_1.isDate(obj) || lang_1.isNumber(obj); + }; + DatePipe._ALIASES = { + 'medium': 'yMMMdjms', + 'short': 'yMdjm', + 'fullDate': 'yMMMMEEEEd', + 'longDate': 'yMMMMd', + 'mediumDate': 'yMMMd', + 'shortDate': 'yMd', + 'mediumTime': 'jms', + 'shortTime': 'jm' + }; + DatePipe = __decorate([lang_1.CONST(), core_1.Pipe({ + name: 'date', + pure: true + }), core_1.Injectable(), __metadata('design:paramtypes', [])], DatePipe); + return DatePipe; + })(); + exports.DatePipe = DatePipe; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/directives", ["angular2/src/common/directives/ng_class", "angular2/src/common/directives/ng_for", "angular2/src/common/directives/ng_if", "angular2/src/common/directives/ng_style", "angular2/src/common/directives/ng_switch", "angular2/src/common/directives/observable_list_diff", "angular2/src/common/directives/core_directives"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function __export(m) { + for (var p in m) + if (!exports.hasOwnProperty(p)) + exports[p] = m[p]; + } + var ng_class_1 = require("angular2/src/common/directives/ng_class"); + exports.NgClass = ng_class_1.NgClass; + var ng_for_1 = require("angular2/src/common/directives/ng_for"); + exports.NgFor = ng_for_1.NgFor; + var ng_if_1 = require("angular2/src/common/directives/ng_if"); + exports.NgIf = ng_if_1.NgIf; + var ng_style_1 = require("angular2/src/common/directives/ng_style"); + exports.NgStyle = ng_style_1.NgStyle; + var ng_switch_1 = require("angular2/src/common/directives/ng_switch"); + exports.NgSwitch = ng_switch_1.NgSwitch; + exports.NgSwitchWhen = ng_switch_1.NgSwitchWhen; + exports.NgSwitchDefault = ng_switch_1.NgSwitchDefault; + __export(require("angular2/src/common/directives/observable_list_diff")); + var core_directives_1 = require("angular2/src/common/directives/core_directives"); + exports.CORE_DIRECTIVES = core_directives_1.CORE_DIRECTIVES; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/directives/shared", ["angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/common/forms/validators", "angular2/src/common/forms/directives/default_value_accessor", "angular2/src/common/forms/directives/number_value_accessor", "angular2/src/common/forms/directives/checkbox_value_accessor", "angular2/src/common/forms/directives/select_control_value_accessor", "angular2/src/common/forms/directives/normalize_validator"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var validators_1 = require("angular2/src/common/forms/validators"); + var default_value_accessor_1 = require("angular2/src/common/forms/directives/default_value_accessor"); + var number_value_accessor_1 = require("angular2/src/common/forms/directives/number_value_accessor"); + var checkbox_value_accessor_1 = require("angular2/src/common/forms/directives/checkbox_value_accessor"); + var select_control_value_accessor_1 = require("angular2/src/common/forms/directives/select_control_value_accessor"); + var normalize_validator_1 = require("angular2/src/common/forms/directives/normalize_validator"); + function controlPath(name, parent) { + var p = collection_1.ListWrapper.clone(parent.path); + p.push(name); + return p; + } + exports.controlPath = controlPath; + function setUpControl(control, dir) { + if (lang_1.isBlank(control)) + _throwError(dir, "Cannot find control"); + if (lang_1.isBlank(dir.valueAccessor)) + _throwError(dir, "No value accessor for"); + control.validator = validators_1.Validators.compose([control.validator, dir.validator]); + control.asyncValidator = validators_1.Validators.composeAsync([control.asyncValidator, dir.asyncValidator]); + dir.valueAccessor.writeValue(control.value); + dir.valueAccessor.registerOnChange(function(newValue) { + dir.viewToModelUpdate(newValue); + control.updateValue(newValue, {emitModelToViewChange: false}); + control.markAsDirty(); + }); + control.registerOnChange(function(newValue) { + return dir.valueAccessor.writeValue(newValue); + }); + dir.valueAccessor.registerOnTouched(function() { + return control.markAsTouched(); + }); + } + exports.setUpControl = setUpControl; + function setUpControlGroup(control, dir) { + if (lang_1.isBlank(control)) + _throwError(dir, "Cannot find control"); + control.validator = validators_1.Validators.compose([control.validator, dir.validator]); + control.asyncValidator = validators_1.Validators.composeAsync([control.asyncValidator, dir.asyncValidator]); + } + exports.setUpControlGroup = setUpControlGroup; + function _throwError(dir, message) { + var path = dir.path.join(" -> "); + throw new exceptions_1.BaseException(message + " '" + path + "'"); + } + function composeValidators(validators) { + return lang_1.isPresent(validators) ? validators_1.Validators.compose(validators.map(normalize_validator_1.normalizeValidator)) : null; + } + exports.composeValidators = composeValidators; + function composeAsyncValidators(validators) { + return lang_1.isPresent(validators) ? validators_1.Validators.composeAsync(validators.map(normalize_validator_1.normalizeValidator)) : null; + } + exports.composeAsyncValidators = composeAsyncValidators; + function isPropertyUpdated(changes, viewModel) { + if (!collection_1.StringMapWrapper.contains(changes, "model")) + return false; + var change = changes["model"]; + if (change.isFirstChange()) + return true; + return !lang_1.looseIdentical(viewModel, change.currentValue); + } + exports.isPropertyUpdated = isPropertyUpdated; + function selectValueAccessor(dir, valueAccessors) { + if (lang_1.isBlank(valueAccessors)) + return null; + var defaultAccessor; + var builtinAccessor; + var customAccessor; + valueAccessors.forEach(function(v) { + if (v instanceof default_value_accessor_1.DefaultValueAccessor) { + defaultAccessor = v; + } else if (v instanceof checkbox_value_accessor_1.CheckboxControlValueAccessor || v instanceof number_value_accessor_1.NumberValueAccessor || v instanceof select_control_value_accessor_1.SelectControlValueAccessor) { + if (lang_1.isPresent(builtinAccessor)) + _throwError(dir, "More than one built-in value accessor matches"); + builtinAccessor = v; + } else { + if (lang_1.isPresent(customAccessor)) + _throwError(dir, "More than one custom value accessor matches"); + customAccessor = v; + } + }); + if (lang_1.isPresent(customAccessor)) + return customAccessor; + if (lang_1.isPresent(builtinAccessor)) + return builtinAccessor; + if (lang_1.isPresent(defaultAccessor)) + return defaultAccessor; + _throwError(dir, "No valid value accessor for"); + return null; + } + exports.selectValueAccessor = selectValueAccessor; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/directives", ["angular2/src/facade/lang", "angular2/src/common/forms/directives/ng_control_name", "angular2/src/common/forms/directives/ng_form_control", "angular2/src/common/forms/directives/ng_model", "angular2/src/common/forms/directives/ng_control_group", "angular2/src/common/forms/directives/ng_form_model", "angular2/src/common/forms/directives/ng_form", "angular2/src/common/forms/directives/default_value_accessor", "angular2/src/common/forms/directives/checkbox_value_accessor", "angular2/src/common/forms/directives/number_value_accessor", "angular2/src/common/forms/directives/ng_control_status", "angular2/src/common/forms/directives/select_control_value_accessor", "angular2/src/common/forms/directives/validators", "angular2/src/common/forms/directives/ng_control_name", "angular2/src/common/forms/directives/ng_form_control", "angular2/src/common/forms/directives/ng_model", "angular2/src/common/forms/directives/ng_control_group", "angular2/src/common/forms/directives/ng_form_model", "angular2/src/common/forms/directives/ng_form", "angular2/src/common/forms/directives/default_value_accessor", "angular2/src/common/forms/directives/checkbox_value_accessor", "angular2/src/common/forms/directives/number_value_accessor", "angular2/src/common/forms/directives/ng_control_status", "angular2/src/common/forms/directives/select_control_value_accessor", "angular2/src/common/forms/directives/validators", "angular2/src/common/forms/directives/ng_control"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var ng_control_name_1 = require("angular2/src/common/forms/directives/ng_control_name"); + var ng_form_control_1 = require("angular2/src/common/forms/directives/ng_form_control"); + var ng_model_1 = require("angular2/src/common/forms/directives/ng_model"); + var ng_control_group_1 = require("angular2/src/common/forms/directives/ng_control_group"); + var ng_form_model_1 = require("angular2/src/common/forms/directives/ng_form_model"); + var ng_form_1 = require("angular2/src/common/forms/directives/ng_form"); + var default_value_accessor_1 = require("angular2/src/common/forms/directives/default_value_accessor"); + var checkbox_value_accessor_1 = require("angular2/src/common/forms/directives/checkbox_value_accessor"); + var number_value_accessor_1 = require("angular2/src/common/forms/directives/number_value_accessor"); + var ng_control_status_1 = require("angular2/src/common/forms/directives/ng_control_status"); + var select_control_value_accessor_1 = require("angular2/src/common/forms/directives/select_control_value_accessor"); + var validators_1 = require("angular2/src/common/forms/directives/validators"); + var ng_control_name_2 = require("angular2/src/common/forms/directives/ng_control_name"); + exports.NgControlName = ng_control_name_2.NgControlName; + var ng_form_control_2 = require("angular2/src/common/forms/directives/ng_form_control"); + exports.NgFormControl = ng_form_control_2.NgFormControl; + var ng_model_2 = require("angular2/src/common/forms/directives/ng_model"); + exports.NgModel = ng_model_2.NgModel; + var ng_control_group_2 = require("angular2/src/common/forms/directives/ng_control_group"); + exports.NgControlGroup = ng_control_group_2.NgControlGroup; + var ng_form_model_2 = require("angular2/src/common/forms/directives/ng_form_model"); + exports.NgFormModel = ng_form_model_2.NgFormModel; + var ng_form_2 = require("angular2/src/common/forms/directives/ng_form"); + exports.NgForm = ng_form_2.NgForm; + var default_value_accessor_2 = require("angular2/src/common/forms/directives/default_value_accessor"); + exports.DefaultValueAccessor = default_value_accessor_2.DefaultValueAccessor; + var checkbox_value_accessor_2 = require("angular2/src/common/forms/directives/checkbox_value_accessor"); + exports.CheckboxControlValueAccessor = checkbox_value_accessor_2.CheckboxControlValueAccessor; + var number_value_accessor_2 = require("angular2/src/common/forms/directives/number_value_accessor"); + exports.NumberValueAccessor = number_value_accessor_2.NumberValueAccessor; + var ng_control_status_2 = require("angular2/src/common/forms/directives/ng_control_status"); + exports.NgControlStatus = ng_control_status_2.NgControlStatus; + var select_control_value_accessor_2 = require("angular2/src/common/forms/directives/select_control_value_accessor"); + exports.SelectControlValueAccessor = select_control_value_accessor_2.SelectControlValueAccessor; + exports.NgSelectOption = select_control_value_accessor_2.NgSelectOption; + var validators_2 = require("angular2/src/common/forms/directives/validators"); + exports.RequiredValidator = validators_2.RequiredValidator; + exports.MinLengthValidator = validators_2.MinLengthValidator; + exports.MaxLengthValidator = validators_2.MaxLengthValidator; + var ng_control_1 = require("angular2/src/common/forms/directives/ng_control"); + exports.NgControl = ng_control_1.NgControl; + exports.FORM_DIRECTIVES = lang_1.CONST_EXPR([ng_control_name_1.NgControlName, ng_control_group_1.NgControlGroup, ng_form_control_1.NgFormControl, ng_model_1.NgModel, ng_form_model_1.NgFormModel, ng_form_1.NgForm, select_control_value_accessor_1.NgSelectOption, default_value_accessor_1.DefaultValueAccessor, number_value_accessor_1.NumberValueAccessor, checkbox_value_accessor_1.CheckboxControlValueAccessor, select_control_value_accessor_1.SelectControlValueAccessor, ng_control_status_1.NgControlStatus, validators_1.RequiredValidator, validators_1.MinLengthValidator, validators_1.MaxLengthValidator]); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/dom/events/hammer_gestures", ["angular2/src/platform/dom/events/hammer_common", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/core/di"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var hammer_common_1 = require("angular2/src/platform/dom/events/hammer_common"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var di_1 = require("angular2/src/core/di"); + var HammerGesturesPlugin = (function(_super) { + __extends(HammerGesturesPlugin, _super); + function HammerGesturesPlugin() { + _super.apply(this, arguments); + } + HammerGesturesPlugin.prototype.supports = function(eventName) { + if (!_super.prototype.supports.call(this, eventName)) + return false; + if (!lang_1.isPresent(window['Hammer'])) { + throw new exceptions_1.BaseException("Hammer.js is not loaded, can not bind " + eventName + " event"); + } + return true; + }; + HammerGesturesPlugin.prototype.addEventListener = function(element, eventName, handler) { + var zone = this.manager.getZone(); + eventName = eventName.toLowerCase(); + zone.runOutsideAngular(function() { + var mc = new Hammer(element); + mc.get('pinch').set({enable: true}); + mc.get('rotate').set({enable: true}); + mc.on(eventName, function(eventObj) { + zone.run(function() { + handler(eventObj); + }); + }); + }); + }; + HammerGesturesPlugin = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], HammerGesturesPlugin); + return HammerGesturesPlugin; + })(hammer_common_1.HammerGesturesPluginCommon); + exports.HammerGesturesPlugin = HammerGesturesPlugin; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/browser/xhr_impl", ["angular2/src/facade/promise", "angular2/src/facade/lang", "angular2/src/compiler/xhr"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var promise_1 = require("angular2/src/facade/promise"); + var lang_1 = require("angular2/src/facade/lang"); + var xhr_1 = require("angular2/src/compiler/xhr"); + var XHRImpl = (function(_super) { + __extends(XHRImpl, _super); + function XHRImpl() { + _super.apply(this, arguments); + } + XHRImpl.prototype.get = function(url) { + var completer = promise_1.PromiseWrapper.completer(); + var xhr = new XMLHttpRequest(); + xhr.open('GET', url, true); + xhr.responseType = 'text'; + xhr.onload = function() { + var response = lang_1.isPresent(xhr.response) ? xhr.response : xhr.responseText; + var status = xhr.status === 1223 ? 204 : xhr.status; + if (status === 0) { + status = response ? 200 : 0; + } + if (200 <= status && status <= 300) { + completer.resolve(response); + } else { + completer.reject("Failed to load " + url, null); + } + }; + xhr.onerror = function() { + completer.reject("Failed to load " + url, null); + }; + xhr.send(); + return completer.promise; + }; + return XHRImpl; + })(xhr_1.XHR); + exports.XHRImpl = XHRImpl; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/browser/tools/common_tools", ["angular2/src/core/application_ref", "angular2/src/facade/lang", "angular2/src/facade/browser", "angular2/src/platform/dom/dom_adapter"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var application_ref_1 = require("angular2/src/core/application_ref"); + var lang_1 = require("angular2/src/facade/lang"); + var browser_1 = require("angular2/src/facade/browser"); + var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); + var AngularTools = (function() { + function AngularTools(ref) { + this.profiler = new AngularProfiler(ref); + } + return AngularTools; + })(); + exports.AngularTools = AngularTools; + var AngularProfiler = (function() { + function AngularProfiler(ref) { + this.appRef = ref.injector.get(application_ref_1.ApplicationRef); + } + AngularProfiler.prototype.timeChangeDetection = function(config) { + var record = lang_1.isPresent(config) && config['record']; + var profileName = 'Change Detection'; + var isProfilerAvailable = lang_1.isPresent(browser_1.window.console.profile); + if (record && isProfilerAvailable) { + browser_1.window.console.profile(profileName); + } + var start = dom_adapter_1.DOM.performanceNow(); + var numTicks = 0; + while (numTicks < 5 || (dom_adapter_1.DOM.performanceNow() - start) < 500) { + this.appRef.tick(); + numTicks++; + } + var end = dom_adapter_1.DOM.performanceNow(); + if (record && isProfilerAvailable) { + browser_1.window.console.profileEnd(profileName); + } + var msPerTick = (end - start) / numTicks; + browser_1.window.console.log("ran " + numTicks + " change detection cycles"); + browser_1.window.console.log(lang_1.NumberWrapper.toFixed(msPerTick, 2) + " ms per check"); + }; + return AngularProfiler; + })(); + exports.AngularProfiler = AngularProfiler; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/directive_metadata", ["angular2/src/facade/lang", "angular2/src/facade/collection", "angular2/src/core/change_detection/change_detection", "angular2/src/core/metadata/view", "angular2/src/compiler/selector", "angular2/src/compiler/util", "angular2/src/core/linker/interfaces"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var collection_1 = require("angular2/src/facade/collection"); + var change_detection_1 = require("angular2/src/core/change_detection/change_detection"); + var view_1 = require("angular2/src/core/metadata/view"); + var selector_1 = require("angular2/src/compiler/selector"); + var util_1 = require("angular2/src/compiler/util"); + var interfaces_1 = require("angular2/src/core/linker/interfaces"); + var HOST_REG_EXP = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\)))$/g; + var CompileTypeMetadata = (function() { + function CompileTypeMetadata(_a) { + var _b = _a === void 0 ? {} : _a, + runtime = _b.runtime, + name = _b.name, + moduleUrl = _b.moduleUrl, + isHost = _b.isHost; + this.runtime = runtime; + this.name = name; + this.moduleUrl = moduleUrl; + this.isHost = lang_1.normalizeBool(isHost); + } + CompileTypeMetadata.fromJson = function(data) { + return new CompileTypeMetadata({ + name: data['name'], + moduleUrl: data['moduleUrl'], + isHost: data['isHost'] + }); + }; + CompileTypeMetadata.prototype.toJson = function() { + return { + 'name': this.name, + 'moduleUrl': this.moduleUrl, + 'isHost': this.isHost + }; + }; + return CompileTypeMetadata; + })(); + exports.CompileTypeMetadata = CompileTypeMetadata; + var CompileTemplateMetadata = (function() { + function CompileTemplateMetadata(_a) { + var _b = _a === void 0 ? {} : _a, + encapsulation = _b.encapsulation, + template = _b.template, + templateUrl = _b.templateUrl, + styles = _b.styles, + styleUrls = _b.styleUrls, + ngContentSelectors = _b.ngContentSelectors; + this.encapsulation = lang_1.isPresent(encapsulation) ? encapsulation : view_1.ViewEncapsulation.Emulated; + this.template = template; + this.templateUrl = templateUrl; + this.styles = lang_1.isPresent(styles) ? styles : []; + this.styleUrls = lang_1.isPresent(styleUrls) ? styleUrls : []; + this.ngContentSelectors = lang_1.isPresent(ngContentSelectors) ? ngContentSelectors : []; + } + CompileTemplateMetadata.fromJson = function(data) { + return new CompileTemplateMetadata({ + encapsulation: lang_1.isPresent(data['encapsulation']) ? view_1.VIEW_ENCAPSULATION_VALUES[data['encapsulation']] : data['encapsulation'], + template: data['template'], + templateUrl: data['templateUrl'], + styles: data['styles'], + styleUrls: data['styleUrls'], + ngContentSelectors: data['ngContentSelectors'] + }); + }; + CompileTemplateMetadata.prototype.toJson = function() { + return { + 'encapsulation': lang_1.isPresent(this.encapsulation) ? lang_1.serializeEnum(this.encapsulation) : this.encapsulation, + 'template': this.template, + 'templateUrl': this.templateUrl, + 'styles': this.styles, + 'styleUrls': this.styleUrls, + 'ngContentSelectors': this.ngContentSelectors + }; + }; + return CompileTemplateMetadata; + })(); + exports.CompileTemplateMetadata = CompileTemplateMetadata; + var CompileDirectiveMetadata = (function() { + function CompileDirectiveMetadata(_a) { + var _b = _a === void 0 ? {} : _a, + type = _b.type, + isComponent = _b.isComponent, + dynamicLoadable = _b.dynamicLoadable, + selector = _b.selector, + exportAs = _b.exportAs, + changeDetection = _b.changeDetection, + inputs = _b.inputs, + outputs = _b.outputs, + hostListeners = _b.hostListeners, + hostProperties = _b.hostProperties, + hostAttributes = _b.hostAttributes, + lifecycleHooks = _b.lifecycleHooks, + template = _b.template; + this.type = type; + this.isComponent = isComponent; + this.dynamicLoadable = dynamicLoadable; + this.selector = selector; + this.exportAs = exportAs; + this.changeDetection = changeDetection; + this.inputs = inputs; + this.outputs = outputs; + this.hostListeners = hostListeners; + this.hostProperties = hostProperties; + this.hostAttributes = hostAttributes; + this.lifecycleHooks = lifecycleHooks; + this.template = template; + } + CompileDirectiveMetadata.create = function(_a) { + var _b = _a === void 0 ? {} : _a, + type = _b.type, + isComponent = _b.isComponent, + dynamicLoadable = _b.dynamicLoadable, + selector = _b.selector, + exportAs = _b.exportAs, + changeDetection = _b.changeDetection, + inputs = _b.inputs, + outputs = _b.outputs, + host = _b.host, + lifecycleHooks = _b.lifecycleHooks, + template = _b.template; + var hostListeners = {}; + var hostProperties = {}; + var hostAttributes = {}; + if (lang_1.isPresent(host)) { + collection_1.StringMapWrapper.forEach(host, function(value, key) { + var matches = lang_1.RegExpWrapper.firstMatch(HOST_REG_EXP, key); + if (lang_1.isBlank(matches)) { + hostAttributes[key] = value; + } else if (lang_1.isPresent(matches[1])) { + hostProperties[matches[1]] = value; + } else if (lang_1.isPresent(matches[2])) { + hostListeners[matches[2]] = value; + } + }); + } + var inputsMap = {}; + if (lang_1.isPresent(inputs)) { + inputs.forEach(function(bindConfig) { + var parts = util_1.splitAtColon(bindConfig, [bindConfig, bindConfig]); + inputsMap[parts[0]] = parts[1]; + }); + } + var outputsMap = {}; + if (lang_1.isPresent(outputs)) { + outputs.forEach(function(bindConfig) { + var parts = util_1.splitAtColon(bindConfig, [bindConfig, bindConfig]); + outputsMap[parts[0]] = parts[1]; + }); + } + return new CompileDirectiveMetadata({ + type: type, + isComponent: lang_1.normalizeBool(isComponent), + dynamicLoadable: lang_1.normalizeBool(dynamicLoadable), + selector: selector, + exportAs: exportAs, + changeDetection: changeDetection, + inputs: inputsMap, + outputs: outputsMap, + hostListeners: hostListeners, + hostProperties: hostProperties, + hostAttributes: hostAttributes, + lifecycleHooks: lang_1.isPresent(lifecycleHooks) ? lifecycleHooks : [], + template: template + }); + }; + CompileDirectiveMetadata.fromJson = function(data) { + return new CompileDirectiveMetadata({ + isComponent: data['isComponent'], + dynamicLoadable: data['dynamicLoadable'], + selector: data['selector'], + exportAs: data['exportAs'], + type: lang_1.isPresent(data['type']) ? CompileTypeMetadata.fromJson(data['type']) : data['type'], + changeDetection: lang_1.isPresent(data['changeDetection']) ? change_detection_1.CHANGE_DETECTION_STRATEGY_VALUES[data['changeDetection']] : data['changeDetection'], + inputs: data['inputs'], + outputs: data['outputs'], + hostListeners: data['hostListeners'], + hostProperties: data['hostProperties'], + hostAttributes: data['hostAttributes'], + lifecycleHooks: data['lifecycleHooks'].map(function(hookValue) { + return interfaces_1.LIFECYCLE_HOOKS_VALUES[hookValue]; + }), + template: lang_1.isPresent(data['template']) ? CompileTemplateMetadata.fromJson(data['template']) : data['template'] + }); + }; + CompileDirectiveMetadata.prototype.toJson = function() { + return { + 'isComponent': this.isComponent, + 'dynamicLoadable': this.dynamicLoadable, + 'selector': this.selector, + 'exportAs': this.exportAs, + 'type': lang_1.isPresent(this.type) ? this.type.toJson() : this.type, + 'changeDetection': lang_1.isPresent(this.changeDetection) ? lang_1.serializeEnum(this.changeDetection) : this.changeDetection, + 'inputs': this.inputs, + 'outputs': this.outputs, + 'hostListeners': this.hostListeners, + 'hostProperties': this.hostProperties, + 'hostAttributes': this.hostAttributes, + 'lifecycleHooks': this.lifecycleHooks.map(function(hook) { + return lang_1.serializeEnum(hook); + }), + 'template': lang_1.isPresent(this.template) ? this.template.toJson() : this.template + }; + }; + return CompileDirectiveMetadata; + })(); + exports.CompileDirectiveMetadata = CompileDirectiveMetadata; + function createHostComponentMeta(componentType, componentSelector) { + var template = selector_1.CssSelector.parse(componentSelector)[0].getMatchingElementTemplate(); + return CompileDirectiveMetadata.create({ + type: new CompileTypeMetadata({ + runtime: Object, + name: "Host" + componentType.name, + moduleUrl: componentType.moduleUrl, + isHost: true + }), + template: new CompileTemplateMetadata({ + template: template, + templateUrl: '', + styles: [], + styleUrls: [], + ngContentSelectors: [] + }), + changeDetection: change_detection_1.ChangeDetectionStrategy.Default, + inputs: [], + outputs: [], + host: {}, + lifecycleHooks: [], + isComponent: true, + dynamicLoadable: false, + selector: '*' + }); + } + exports.createHostComponentMeta = createHostComponentMeta; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/change_definition_factory", ["angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/core/reflection/reflection", "angular2/src/core/change_detection/change_detection", "angular2/src/compiler/template_ast", "angular2/src/core/linker/interfaces"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var reflection_1 = require("angular2/src/core/reflection/reflection"); + var change_detection_1 = require("angular2/src/core/change_detection/change_detection"); + var template_ast_1 = require("angular2/src/compiler/template_ast"); + var interfaces_1 = require("angular2/src/core/linker/interfaces"); + function createChangeDetectorDefinitions(componentType, componentStrategy, genConfig, parsedTemplate) { + var pvVisitors = []; + var visitor = new ProtoViewVisitor(null, pvVisitors, componentStrategy); + template_ast_1.templateVisitAll(visitor, parsedTemplate); + return createChangeDefinitions(pvVisitors, componentType, genConfig); + } + exports.createChangeDetectorDefinitions = createChangeDetectorDefinitions; + var ProtoViewVisitor = (function() { + function ProtoViewVisitor(parent, allVisitors, strategy) { + this.parent = parent; + this.allVisitors = allVisitors; + this.strategy = strategy; + this.boundTextCount = 0; + this.boundElementCount = 0; + this.variableNames = []; + this.bindingRecords = []; + this.eventRecords = []; + this.directiveRecords = []; + this.viewIndex = allVisitors.length; + allVisitors.push(this); + } + ProtoViewVisitor.prototype.visitEmbeddedTemplate = function(ast, context) { + this.boundElementCount++; + template_ast_1.templateVisitAll(this, ast.outputs); + for (var i = 0; i < ast.directives.length; i++) { + ast.directives[i].visit(this, i); + } + var childVisitor = new ProtoViewVisitor(this, this.allVisitors, change_detection_1.ChangeDetectionStrategy.Default); + template_ast_1.templateVisitAll(childVisitor, ast.vars); + template_ast_1.templateVisitAll(childVisitor, ast.children); + return null; + }; + ProtoViewVisitor.prototype.visitElement = function(ast, context) { + if (ast.isBound()) { + this.boundElementCount++; + } + template_ast_1.templateVisitAll(this, ast.inputs, null); + template_ast_1.templateVisitAll(this, ast.outputs); + template_ast_1.templateVisitAll(this, ast.exportAsVars); + for (var i = 0; i < ast.directives.length; i++) { + ast.directives[i].visit(this, i); + } + template_ast_1.templateVisitAll(this, ast.children); + return null; + }; + ProtoViewVisitor.prototype.visitNgContent = function(ast, context) { + return null; + }; + ProtoViewVisitor.prototype.visitVariable = function(ast, context) { + this.variableNames.push(ast.name); + return null; + }; + ProtoViewVisitor.prototype.visitEvent = function(ast, directiveRecord) { + var bindingRecord = lang_1.isPresent(directiveRecord) ? change_detection_1.BindingRecord.createForHostEvent(ast.handler, ast.fullName, directiveRecord) : change_detection_1.BindingRecord.createForEvent(ast.handler, ast.fullName, this.boundElementCount - 1); + this.eventRecords.push(bindingRecord); + return null; + }; + ProtoViewVisitor.prototype.visitElementProperty = function(ast, directiveRecord) { + var boundElementIndex = this.boundElementCount - 1; + var dirIndex = lang_1.isPresent(directiveRecord) ? directiveRecord.directiveIndex : null; + var bindingRecord; + if (ast.type === template_ast_1.PropertyBindingType.Property) { + bindingRecord = lang_1.isPresent(dirIndex) ? change_detection_1.BindingRecord.createForHostProperty(dirIndex, ast.value, ast.name) : change_detection_1.BindingRecord.createForElementProperty(ast.value, boundElementIndex, ast.name); + } else if (ast.type === template_ast_1.PropertyBindingType.Attribute) { + bindingRecord = lang_1.isPresent(dirIndex) ? change_detection_1.BindingRecord.createForHostAttribute(dirIndex, ast.value, ast.name) : change_detection_1.BindingRecord.createForElementAttribute(ast.value, boundElementIndex, ast.name); + } else if (ast.type === template_ast_1.PropertyBindingType.Class) { + bindingRecord = lang_1.isPresent(dirIndex) ? change_detection_1.BindingRecord.createForHostClass(dirIndex, ast.value, ast.name) : change_detection_1.BindingRecord.createForElementClass(ast.value, boundElementIndex, ast.name); + } else if (ast.type === template_ast_1.PropertyBindingType.Style) { + bindingRecord = lang_1.isPresent(dirIndex) ? change_detection_1.BindingRecord.createForHostStyle(dirIndex, ast.value, ast.name, ast.unit) : change_detection_1.BindingRecord.createForElementStyle(ast.value, boundElementIndex, ast.name, ast.unit); + } + this.bindingRecords.push(bindingRecord); + return null; + }; + ProtoViewVisitor.prototype.visitAttr = function(ast, context) { + return null; + }; + ProtoViewVisitor.prototype.visitBoundText = function(ast, context) { + var boundTextIndex = this.boundTextCount++; + this.bindingRecords.push(change_detection_1.BindingRecord.createForTextNode(ast.value, boundTextIndex)); + return null; + }; + ProtoViewVisitor.prototype.visitText = function(ast, context) { + return null; + }; + ProtoViewVisitor.prototype.visitDirective = function(ast, directiveIndexAsNumber) { + var directiveIndex = new change_detection_1.DirectiveIndex(this.boundElementCount - 1, directiveIndexAsNumber); + var directiveMetadata = ast.directive; + var directiveRecord = new change_detection_1.DirectiveRecord({ + directiveIndex: directiveIndex, + callAfterContentInit: directiveMetadata.lifecycleHooks.indexOf(interfaces_1.LifecycleHooks.AfterContentInit) !== -1, + callAfterContentChecked: directiveMetadata.lifecycleHooks.indexOf(interfaces_1.LifecycleHooks.AfterContentChecked) !== -1, + callAfterViewInit: directiveMetadata.lifecycleHooks.indexOf(interfaces_1.LifecycleHooks.AfterViewInit) !== -1, + callAfterViewChecked: directiveMetadata.lifecycleHooks.indexOf(interfaces_1.LifecycleHooks.AfterViewChecked) !== -1, + callOnChanges: directiveMetadata.lifecycleHooks.indexOf(interfaces_1.LifecycleHooks.OnChanges) !== -1, + callDoCheck: directiveMetadata.lifecycleHooks.indexOf(interfaces_1.LifecycleHooks.DoCheck) !== -1, + callOnInit: directiveMetadata.lifecycleHooks.indexOf(interfaces_1.LifecycleHooks.OnInit) !== -1, + changeDetection: directiveMetadata.changeDetection + }); + this.directiveRecords.push(directiveRecord); + template_ast_1.templateVisitAll(this, ast.inputs, directiveRecord); + var bindingRecords = this.bindingRecords; + if (directiveRecord.callOnChanges) { + bindingRecords.push(change_detection_1.BindingRecord.createDirectiveOnChanges(directiveRecord)); + } + if (directiveRecord.callOnInit) { + bindingRecords.push(change_detection_1.BindingRecord.createDirectiveOnInit(directiveRecord)); + } + if (directiveRecord.callDoCheck) { + bindingRecords.push(change_detection_1.BindingRecord.createDirectiveDoCheck(directiveRecord)); + } + template_ast_1.templateVisitAll(this, ast.hostProperties, directiveRecord); + template_ast_1.templateVisitAll(this, ast.hostEvents, directiveRecord); + template_ast_1.templateVisitAll(this, ast.exportAsVars); + return null; + }; + ProtoViewVisitor.prototype.visitDirectiveProperty = function(ast, directiveRecord) { + var setter = reflection_1.reflector.setter(ast.directiveName); + this.bindingRecords.push(change_detection_1.BindingRecord.createForDirective(ast.value, ast.directiveName, setter, directiveRecord)); + return null; + }; + return ProtoViewVisitor; + })(); + function createChangeDefinitions(pvVisitors, componentType, genConfig) { + var pvVariableNames = _collectNestedProtoViewsVariableNames(pvVisitors); + return pvVisitors.map(function(pvVisitor) { + var id = componentType.name + "_" + pvVisitor.viewIndex; + return new change_detection_1.ChangeDetectorDefinition(id, pvVisitor.strategy, pvVariableNames[pvVisitor.viewIndex], pvVisitor.bindingRecords, pvVisitor.eventRecords, pvVisitor.directiveRecords, genConfig); + }); + } + function _collectNestedProtoViewsVariableNames(pvVisitors) { + var nestedPvVariableNames = collection_1.ListWrapper.createFixedSize(pvVisitors.length); + pvVisitors.forEach(function(pv) { + var parentVariableNames = lang_1.isPresent(pv.parent) ? nestedPvVariableNames[pv.parent.viewIndex] : []; + nestedPvVariableNames[pv.viewIndex] = parentVariableNames.concat(pv.variableNames); + }); + return nestedPvVariableNames; + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/style_compiler", ["angular2/src/compiler/source_module", "angular2/src/core/metadata/view", "angular2/src/compiler/xhr", "angular2/src/facade/lang", "angular2/src/facade/async", "angular2/src/compiler/shadow_css", "angular2/src/compiler/url_resolver", "angular2/src/compiler/style_url_resolver", "angular2/src/compiler/util", "angular2/src/core/di", "angular2/src/core/render/view_factory"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var source_module_1 = require("angular2/src/compiler/source_module"); + var view_1 = require("angular2/src/core/metadata/view"); + var xhr_1 = require("angular2/src/compiler/xhr"); + var lang_1 = require("angular2/src/facade/lang"); + var async_1 = require("angular2/src/facade/async"); + var shadow_css_1 = require("angular2/src/compiler/shadow_css"); + var url_resolver_1 = require("angular2/src/compiler/url_resolver"); + var style_url_resolver_1 = require("angular2/src/compiler/style_url_resolver"); + var util_1 = require("angular2/src/compiler/util"); + var di_1 = require("angular2/src/core/di"); + var view_factory_1 = require("angular2/src/core/render/view_factory"); + var StyleCompiler = (function() { + function StyleCompiler(_xhr, _urlResolver) { + this._xhr = _xhr; + this._urlResolver = _urlResolver; + this._styleCache = new Map(); + this._shadowCss = new shadow_css_1.ShadowCss(); + } + StyleCompiler.prototype.compileComponentRuntime = function(template) { + var styles = template.styles; + var styleAbsUrls = template.styleUrls; + return this._loadStyles(styles, styleAbsUrls, template.encapsulation === view_1.ViewEncapsulation.Emulated); + }; + StyleCompiler.prototype.compileComponentCodeGen = function(template) { + var shim = template.encapsulation === view_1.ViewEncapsulation.Emulated; + return this._styleCodeGen(template.styles, template.styleUrls, shim); + }; + StyleCompiler.prototype.compileStylesheetCodeGen = function(stylesheetUrl, cssText) { + var styleWithImports = style_url_resolver_1.extractStyleUrls(this._urlResolver, stylesheetUrl, cssText); + return [this._styleModule(stylesheetUrl, false, this._styleCodeGen([styleWithImports.style], styleWithImports.styleUrls, false)), this._styleModule(stylesheetUrl, true, this._styleCodeGen([styleWithImports.style], styleWithImports.styleUrls, true))]; + }; + StyleCompiler.prototype.clearCache = function() { + this._styleCache.clear(); + }; + StyleCompiler.prototype._loadStyles = function(plainStyles, absUrls, encapsulate) { + var _this = this; + var promises = absUrls.map(function(absUrl) { + var cacheKey = "" + absUrl + (encapsulate ? '.shim' : ''); + var result = _this._styleCache.get(cacheKey); + if (lang_1.isBlank(result)) { + result = _this._xhr.get(absUrl).then(function(style) { + var styleWithImports = style_url_resolver_1.extractStyleUrls(_this._urlResolver, absUrl, style); + return _this._loadStyles([styleWithImports.style], styleWithImports.styleUrls, encapsulate); + }); + _this._styleCache.set(cacheKey, result); + } + return result; + }); + return async_1.PromiseWrapper.all(promises).then(function(nestedStyles) { + var result = plainStyles.map(function(plainStyle) { + return _this._shimIfNeeded(plainStyle, encapsulate); + }); + nestedStyles.forEach(function(styles) { + return result.push(styles); + }); + return result; + }); + }; + StyleCompiler.prototype._styleCodeGen = function(plainStyles, absUrls, shim) { + var _this = this; + var arrayPrefix = lang_1.IS_DART ? "const" : ''; + var styleExpressions = plainStyles.map(function(plainStyle) { + return util_1.escapeSingleQuoteString(_this._shimIfNeeded(plainStyle, shim)); + }); + for (var i = 0; i < absUrls.length; i++) { + var moduleUrl = this._createModuleUrl(absUrls[i], shim); + styleExpressions.push(source_module_1.moduleRef(moduleUrl) + "STYLES"); + } + var expressionSource = arrayPrefix + " [" + styleExpressions.join(',') + "]"; + return new source_module_1.SourceExpression([], expressionSource); + }; + StyleCompiler.prototype._styleModule = function(stylesheetUrl, shim, expression) { + var moduleSource = "\n " + expression.declarations.join('\n') + "\n " + util_1.codeGenExportVariable('STYLES') + expression.expression + ";\n "; + return new source_module_1.SourceModule(this._createModuleUrl(stylesheetUrl, shim), moduleSource); + }; + StyleCompiler.prototype._shimIfNeeded = function(style, shim) { + return shim ? this._shadowCss.shimCssText(style, view_factory_1.CONTENT_ATTR, view_factory_1.HOST_ATTR) : style; + }; + StyleCompiler.prototype._createModuleUrl = function(stylesheetUrl, shim) { + return shim ? stylesheetUrl + ".shim" + util_1.MODULE_SUFFIX : "" + stylesheetUrl + util_1.MODULE_SUFFIX; + }; + StyleCompiler = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [xhr_1.XHR, url_resolver_1.UrlResolver])], StyleCompiler); + return StyleCompiler; + })(); + exports.StyleCompiler = StyleCompiler; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", "angular2/src/facade/collection", "angular2/src/compiler/parse_util", "angular2/src/compiler/html_tags"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var lang_1 = require("angular2/src/facade/lang"); + var collection_1 = require("angular2/src/facade/collection"); + var parse_util_1 = require("angular2/src/compiler/parse_util"); + var html_tags_1 = require("angular2/src/compiler/html_tags"); + (function(HtmlTokenType) { + HtmlTokenType[HtmlTokenType["TAG_OPEN_START"] = 0] = "TAG_OPEN_START"; + HtmlTokenType[HtmlTokenType["TAG_OPEN_END"] = 1] = "TAG_OPEN_END"; + HtmlTokenType[HtmlTokenType["TAG_OPEN_END_VOID"] = 2] = "TAG_OPEN_END_VOID"; + HtmlTokenType[HtmlTokenType["TAG_CLOSE"] = 3] = "TAG_CLOSE"; + HtmlTokenType[HtmlTokenType["TEXT"] = 4] = "TEXT"; + HtmlTokenType[HtmlTokenType["ESCAPABLE_RAW_TEXT"] = 5] = "ESCAPABLE_RAW_TEXT"; + HtmlTokenType[HtmlTokenType["RAW_TEXT"] = 6] = "RAW_TEXT"; + HtmlTokenType[HtmlTokenType["COMMENT_START"] = 7] = "COMMENT_START"; + HtmlTokenType[HtmlTokenType["COMMENT_END"] = 8] = "COMMENT_END"; + HtmlTokenType[HtmlTokenType["CDATA_START"] = 9] = "CDATA_START"; + HtmlTokenType[HtmlTokenType["CDATA_END"] = 10] = "CDATA_END"; + HtmlTokenType[HtmlTokenType["ATTR_NAME"] = 11] = "ATTR_NAME"; + HtmlTokenType[HtmlTokenType["ATTR_VALUE"] = 12] = "ATTR_VALUE"; + HtmlTokenType[HtmlTokenType["DOC_TYPE"] = 13] = "DOC_TYPE"; + HtmlTokenType[HtmlTokenType["EOF"] = 14] = "EOF"; + })(exports.HtmlTokenType || (exports.HtmlTokenType = {})); + var HtmlTokenType = exports.HtmlTokenType; + var HtmlToken = (function() { + function HtmlToken(type, parts, sourceSpan) { + this.type = type; + this.parts = parts; + this.sourceSpan = sourceSpan; + } + return HtmlToken; + })(); + exports.HtmlToken = HtmlToken; + var HtmlTokenError = (function(_super) { + __extends(HtmlTokenError, _super); + function HtmlTokenError(errorMsg, tokenType, location) { + _super.call(this, location, errorMsg); + this.tokenType = tokenType; + } + return HtmlTokenError; + })(parse_util_1.ParseError); + exports.HtmlTokenError = HtmlTokenError; + var HtmlTokenizeResult = (function() { + function HtmlTokenizeResult(tokens, errors) { + this.tokens = tokens; + this.errors = errors; + } + return HtmlTokenizeResult; + })(); + exports.HtmlTokenizeResult = HtmlTokenizeResult; + function tokenizeHtml(sourceContent, sourceUrl) { + return new _HtmlTokenizer(new parse_util_1.ParseSourceFile(sourceContent, sourceUrl)).tokenize(); + } + exports.tokenizeHtml = tokenizeHtml; + var $EOF = 0; + var $TAB = 9; + var $LF = 10; + var $FF = 12; + var $CR = 13; + var $SPACE = 32; + var $BANG = 33; + var $DQ = 34; + var $HASH = 35; + var $$ = 36; + var $AMPERSAND = 38; + var $SQ = 39; + var $MINUS = 45; + var $SLASH = 47; + var $0 = 48; + var $SEMICOLON = 59; + var $9 = 57; + var $COLON = 58; + var $LT = 60; + var $EQ = 61; + var $GT = 62; + var $QUESTION = 63; + var $A = 65; + var $Z = 90; + var $LBRACKET = 91; + var $RBRACKET = 93; + var $a = 97; + var $f = 102; + var $z = 122; + var $x = 120; + var $NBSP = 160; + var CR_OR_CRLF_REGEXP = /\r\n?/g; + function unexpectedCharacterErrorMsg(charCode) { + var char = charCode === $EOF ? 'EOF' : lang_1.StringWrapper.fromCharCode(charCode); + return "Unexpected character \"" + char + "\""; + } + function unknownEntityErrorMsg(entitySrc) { + return "Unknown entity \"" + entitySrc + "\" - use the \"&#;\" or \"&#x;\" syntax"; + } + var ControlFlowError = (function() { + function ControlFlowError(error) { + this.error = error; + } + return ControlFlowError; + })(); + var _HtmlTokenizer = (function() { + function _HtmlTokenizer(file) { + this.file = file; + this.peek = -1; + this.index = -1; + this.line = 0; + this.column = -1; + this.tokens = []; + this.errors = []; + this.input = file.content; + this.inputLowercase = file.content.toLowerCase(); + this.length = file.content.length; + this._advance(); + } + _HtmlTokenizer.prototype._processCarriageReturns = function(content) { + return lang_1.StringWrapper.replaceAll(content, CR_OR_CRLF_REGEXP, '\n'); + }; + _HtmlTokenizer.prototype.tokenize = function() { + while (this.peek !== $EOF) { + var start = this._getLocation(); + try { + if (this._attemptChar($LT)) { + if (this._attemptChar($BANG)) { + if (this._attemptChar($LBRACKET)) { + this._consumeCdata(start); + } else if (this._attemptChar($MINUS)) { + this._consumeComment(start); + } else { + this._consumeDocType(start); + } + } else if (this._attemptChar($SLASH)) { + this._consumeTagClose(start); + } else { + this._consumeTagOpen(start); + } + } else { + this._consumeText(); + } + } catch (e) { + if (e instanceof ControlFlowError) { + this.errors.push(e.error); + } else { + throw e; + } + } + } + this._beginToken(HtmlTokenType.EOF); + this._endToken([]); + return new HtmlTokenizeResult(mergeTextTokens(this.tokens), this.errors); + }; + _HtmlTokenizer.prototype._getLocation = function() { + return new parse_util_1.ParseLocation(this.file, this.index, this.line, this.column); + }; + _HtmlTokenizer.prototype._beginToken = function(type, start) { + if (start === void 0) { + start = null; + } + if (lang_1.isBlank(start)) { + start = this._getLocation(); + } + this.currentTokenStart = start; + this.currentTokenType = type; + }; + _HtmlTokenizer.prototype._endToken = function(parts, end) { + if (end === void 0) { + end = null; + } + if (lang_1.isBlank(end)) { + end = this._getLocation(); + } + var token = new HtmlToken(this.currentTokenType, parts, new parse_util_1.ParseSourceSpan(this.currentTokenStart, end)); + this.tokens.push(token); + this.currentTokenStart = null; + this.currentTokenType = null; + return token; + }; + _HtmlTokenizer.prototype._createError = function(msg, position) { + var error = new HtmlTokenError(msg, this.currentTokenType, position); + this.currentTokenStart = null; + this.currentTokenType = null; + return new ControlFlowError(error); + }; + _HtmlTokenizer.prototype._advance = function() { + if (this.index >= this.length) { + throw this._createError(unexpectedCharacterErrorMsg($EOF), this._getLocation()); + } + if (this.peek === $LF) { + this.line++; + this.column = 0; + } else if (this.peek !== $LF && this.peek !== $CR) { + this.column++; + } + this.index++; + this.peek = this.index >= this.length ? $EOF : lang_1.StringWrapper.charCodeAt(this.inputLowercase, this.index); + }; + _HtmlTokenizer.prototype._attemptChar = function(charCode) { + if (this.peek === charCode) { + this._advance(); + return true; + } + return false; + }; + _HtmlTokenizer.prototype._requireChar = function(charCode) { + var location = this._getLocation(); + if (!this._attemptChar(charCode)) { + throw this._createError(unexpectedCharacterErrorMsg(this.peek), location); + } + }; + _HtmlTokenizer.prototype._attemptChars = function(chars) { + for (var i = 0; i < chars.length; i++) { + if (!this._attemptChar(lang_1.StringWrapper.charCodeAt(chars, i))) { + return false; + } + } + return true; + }; + _HtmlTokenizer.prototype._requireChars = function(chars) { + var location = this._getLocation(); + if (!this._attemptChars(chars)) { + throw this._createError(unexpectedCharacterErrorMsg(this.peek), location); + } + }; + _HtmlTokenizer.prototype._attemptUntilFn = function(predicate) { + while (!predicate(this.peek)) { + this._advance(); + } + }; + _HtmlTokenizer.prototype._requireUntilFn = function(predicate, len) { + var start = this._getLocation(); + this._attemptUntilFn(predicate); + if (this.index - start.offset < len) { + throw this._createError(unexpectedCharacterErrorMsg(this.peek), start); + } + }; + _HtmlTokenizer.prototype._attemptUntilChar = function(char) { + while (this.peek !== char) { + this._advance(); + } + }; + _HtmlTokenizer.prototype._readChar = function(decodeEntities) { + if (decodeEntities && this.peek === $AMPERSAND) { + return this._decodeEntity(); + } else { + var index = this.index; + this._advance(); + return this.input[index]; + } + }; + _HtmlTokenizer.prototype._decodeEntity = function() { + var start = this._getLocation(); + this._advance(); + if (this._attemptChar($HASH)) { + var isHex = this._attemptChar($x); + var numberStart = this._getLocation().offset; + this._attemptUntilFn(isDigitEntityEnd); + if (this.peek != $SEMICOLON) { + throw this._createError(unexpectedCharacterErrorMsg(this.peek), this._getLocation()); + } + this._advance(); + var strNum = this.input.substring(numberStart, this.index - 1); + try { + var charCode = lang_1.NumberWrapper.parseInt(strNum, isHex ? 16 : 10); + return lang_1.StringWrapper.fromCharCode(charCode); + } catch (e) { + var entity = this.input.substring(start.offset + 1, this.index - 1); + throw this._createError(unknownEntityErrorMsg(entity), start); + } + } else { + var startPosition = this._savePosition(); + this._attemptUntilFn(isNamedEntityEnd); + if (this.peek != $SEMICOLON) { + this._restorePosition(startPosition); + return '&'; + } + this._advance(); + var name_1 = this.input.substring(start.offset + 1, this.index - 1); + var char = html_tags_1.NAMED_ENTITIES[name_1]; + if (lang_1.isBlank(char)) { + throw this._createError(unknownEntityErrorMsg(name_1), start); + } + return char; + } + }; + _HtmlTokenizer.prototype._consumeRawText = function(decodeEntities, firstCharOfEnd, attemptEndRest) { + var tagCloseStart; + var textStart = this._getLocation(); + this._beginToken(decodeEntities ? HtmlTokenType.ESCAPABLE_RAW_TEXT : HtmlTokenType.RAW_TEXT, textStart); + var parts = []; + while (true) { + tagCloseStart = this._getLocation(); + if (this._attemptChar(firstCharOfEnd) && attemptEndRest()) { + break; + } + if (this.index > tagCloseStart.offset) { + parts.push(this.input.substring(tagCloseStart.offset, this.index)); + } + while (this.peek !== firstCharOfEnd) { + parts.push(this._readChar(decodeEntities)); + } + } + return this._endToken([this._processCarriageReturns(parts.join(''))], tagCloseStart); + }; + _HtmlTokenizer.prototype._consumeComment = function(start) { + var _this = this; + this._beginToken(HtmlTokenType.COMMENT_START, start); + this._requireChar($MINUS); + this._endToken([]); + var textToken = this._consumeRawText(false, $MINUS, function() { + return _this._attemptChars('->'); + }); + this._beginToken(HtmlTokenType.COMMENT_END, textToken.sourceSpan.end); + this._endToken([]); + }; + _HtmlTokenizer.prototype._consumeCdata = function(start) { + var _this = this; + this._beginToken(HtmlTokenType.CDATA_START, start); + this._requireChars('cdata['); + this._endToken([]); + var textToken = this._consumeRawText(false, $RBRACKET, function() { + return _this._attemptChars(']>'); + }); + this._beginToken(HtmlTokenType.CDATA_END, textToken.sourceSpan.end); + this._endToken([]); + }; + _HtmlTokenizer.prototype._consumeDocType = function(start) { + this._beginToken(HtmlTokenType.DOC_TYPE, start); + this._attemptUntilChar($GT); + this._advance(); + this._endToken([this.input.substring(start.offset + 2, this.index - 1)]); + }; + _HtmlTokenizer.prototype._consumePrefixAndName = function() { + var nameOrPrefixStart = this.index; + var prefix = null; + while (this.peek !== $COLON && !isPrefixEnd(this.peek)) { + this._advance(); + } + var nameStart; + if (this.peek === $COLON) { + this._advance(); + prefix = this.input.substring(nameOrPrefixStart, this.index - 1); + nameStart = this.index; + } else { + nameStart = nameOrPrefixStart; + } + this._requireUntilFn(isNameEnd, this.index === nameStart ? 1 : 0); + var name = this.input.substring(nameStart, this.index); + return [prefix, name]; + }; + _HtmlTokenizer.prototype._consumeTagOpen = function(start) { + var savedPos = this._savePosition(); + var lowercaseTagName; + try { + if (!isAsciiLetter(this.peek)) { + throw this._createError(unexpectedCharacterErrorMsg(this.peek), this._getLocation()); + } + var nameStart = this.index; + this._consumeTagOpenStart(start); + lowercaseTagName = this.inputLowercase.substring(nameStart, this.index); + this._attemptUntilFn(isNotWhitespace); + while (this.peek !== $SLASH && this.peek !== $GT) { + this._consumeAttributeName(); + this._attemptUntilFn(isNotWhitespace); + if (this._attemptChar($EQ)) { + this._attemptUntilFn(isNotWhitespace); + this._consumeAttributeValue(); + } + this._attemptUntilFn(isNotWhitespace); + } + this._consumeTagOpenEnd(); + } catch (e) { + if (e instanceof ControlFlowError) { + this._restorePosition(savedPos); + this._beginToken(HtmlTokenType.TEXT, start); + this._endToken(['<']); + return ; + } + throw e; + } + var contentTokenType = html_tags_1.getHtmlTagDefinition(lowercaseTagName).contentType; + if (contentTokenType === html_tags_1.HtmlTagContentType.RAW_TEXT) { + this._consumeRawTextWithTagClose(lowercaseTagName, false); + } else if (contentTokenType === html_tags_1.HtmlTagContentType.ESCAPABLE_RAW_TEXT) { + this._consumeRawTextWithTagClose(lowercaseTagName, true); + } + }; + _HtmlTokenizer.prototype._consumeRawTextWithTagClose = function(lowercaseTagName, decodeEntities) { + var _this = this; + var textToken = this._consumeRawText(decodeEntities, $LT, function() { + if (!_this._attemptChar($SLASH)) + return false; + _this._attemptUntilFn(isNotWhitespace); + if (!_this._attemptChars(lowercaseTagName)) + return false; + _this._attemptUntilFn(isNotWhitespace); + if (!_this._attemptChar($GT)) + return false; + return true; + }); + this._beginToken(HtmlTokenType.TAG_CLOSE, textToken.sourceSpan.end); + this._endToken([null, lowercaseTagName]); + }; + _HtmlTokenizer.prototype._consumeTagOpenStart = function(start) { + this._beginToken(HtmlTokenType.TAG_OPEN_START, start); + var parts = this._consumePrefixAndName(); + this._endToken(parts); + }; + _HtmlTokenizer.prototype._consumeAttributeName = function() { + this._beginToken(HtmlTokenType.ATTR_NAME); + var prefixAndName = this._consumePrefixAndName(); + this._endToken(prefixAndName); + }; + _HtmlTokenizer.prototype._consumeAttributeValue = function() { + this._beginToken(HtmlTokenType.ATTR_VALUE); + var value; + if (this.peek === $SQ || this.peek === $DQ) { + var quoteChar = this.peek; + this._advance(); + var parts = []; + while (this.peek !== quoteChar) { + parts.push(this._readChar(true)); + } + value = parts.join(''); + this._advance(); + } else { + var valueStart = this.index; + this._requireUntilFn(isNameEnd, 1); + value = this.input.substring(valueStart, this.index); + } + this._endToken([this._processCarriageReturns(value)]); + }; + _HtmlTokenizer.prototype._consumeTagOpenEnd = function() { + var tokenType = this._attemptChar($SLASH) ? HtmlTokenType.TAG_OPEN_END_VOID : HtmlTokenType.TAG_OPEN_END; + this._beginToken(tokenType); + this._requireChar($GT); + this._endToken([]); + }; + _HtmlTokenizer.prototype._consumeTagClose = function(start) { + this._beginToken(HtmlTokenType.TAG_CLOSE, start); + this._attemptUntilFn(isNotWhitespace); + var prefixAndName; + prefixAndName = this._consumePrefixAndName(); + this._attemptUntilFn(isNotWhitespace); + this._requireChar($GT); + this._endToken(prefixAndName); + }; + _HtmlTokenizer.prototype._consumeText = function() { + var start = this._getLocation(); + this._beginToken(HtmlTokenType.TEXT, start); + var parts = [this._readChar(true)]; + while (!isTextEnd(this.peek)) { + parts.push(this._readChar(true)); + } + this._endToken([this._processCarriageReturns(parts.join(''))]); + }; + _HtmlTokenizer.prototype._savePosition = function() { + return [this.peek, this.index, this.column, this.line, this.tokens.length]; + }; + _HtmlTokenizer.prototype._restorePosition = function(position) { + this.peek = position[0]; + this.index = position[1]; + this.column = position[2]; + this.line = position[3]; + var nbTokens = position[4]; + if (nbTokens < this.tokens.length) { + this.tokens = collection_1.ListWrapper.slice(this.tokens, 0, nbTokens); + } + }; + return _HtmlTokenizer; + })(); + function isNotWhitespace(code) { + return !isWhitespace(code) || code === $EOF; + } + function isWhitespace(code) { + return (code >= $TAB && code <= $SPACE) || (code === $NBSP); + } + function isNameEnd(code) { + return isWhitespace(code) || code === $GT || code === $SLASH || code === $SQ || code === $DQ || code === $EQ; + } + function isPrefixEnd(code) { + return (code < $a || $z < code) && (code < $A || $Z < code) && (code < $0 || code > $9); + } + function isDigitEntityEnd(code) { + return code == $SEMICOLON || code == $EOF || !isAsciiHexDigit(code); + } + function isNamedEntityEnd(code) { + return code == $SEMICOLON || code == $EOF || !isAsciiLetter(code); + } + function isTextEnd(code) { + return code === $LT || code === $EOF; + } + function isAsciiLetter(code) { + return code >= $a && code <= $z; + } + function isAsciiHexDigit(code) { + return code >= $a && code <= $f || code >= $0 && code <= $9; + } + function mergeTextTokens(srcTokens) { + var dstTokens = []; + var lastDstToken; + for (var i = 0; i < srcTokens.length; i++) { + var token = srcTokens[i]; + if (lang_1.isPresent(lastDstToken) && lastDstToken.type == HtmlTokenType.TEXT && token.type == HtmlTokenType.TEXT) { + lastDstToken.parts[0] += token.parts[0]; + lastDstToken.sourceSpan.end = token.sourceSpan.end; + } else { + lastDstToken = token; + dstTokens.push(lastDstToken); + } + } + return dstTokens; + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/pipes", ["angular2/src/common/pipes/async_pipe", "angular2/src/common/pipes/uppercase_pipe", "angular2/src/common/pipes/lowercase_pipe", "angular2/src/common/pipes/json_pipe", "angular2/src/common/pipes/slice_pipe", "angular2/src/common/pipes/date_pipe", "angular2/src/common/pipes/number_pipe", "angular2/src/facade/lang", "angular2/src/common/pipes/async_pipe", "angular2/src/common/pipes/date_pipe", "angular2/src/common/pipes/json_pipe", "angular2/src/common/pipes/slice_pipe", "angular2/src/common/pipes/lowercase_pipe", "angular2/src/common/pipes/number_pipe", "angular2/src/common/pipes/uppercase_pipe"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var async_pipe_1 = require("angular2/src/common/pipes/async_pipe"); + var uppercase_pipe_1 = require("angular2/src/common/pipes/uppercase_pipe"); + var lowercase_pipe_1 = require("angular2/src/common/pipes/lowercase_pipe"); + var json_pipe_1 = require("angular2/src/common/pipes/json_pipe"); + var slice_pipe_1 = require("angular2/src/common/pipes/slice_pipe"); + var date_pipe_1 = require("angular2/src/common/pipes/date_pipe"); + var number_pipe_1 = require("angular2/src/common/pipes/number_pipe"); + var lang_1 = require("angular2/src/facade/lang"); + var async_pipe_2 = require("angular2/src/common/pipes/async_pipe"); + exports.AsyncPipe = async_pipe_2.AsyncPipe; + var date_pipe_2 = require("angular2/src/common/pipes/date_pipe"); + exports.DatePipe = date_pipe_2.DatePipe; + var json_pipe_2 = require("angular2/src/common/pipes/json_pipe"); + exports.JsonPipe = json_pipe_2.JsonPipe; + var slice_pipe_2 = require("angular2/src/common/pipes/slice_pipe"); + exports.SlicePipe = slice_pipe_2.SlicePipe; + var lowercase_pipe_2 = require("angular2/src/common/pipes/lowercase_pipe"); + exports.LowerCasePipe = lowercase_pipe_2.LowerCasePipe; + var number_pipe_2 = require("angular2/src/common/pipes/number_pipe"); + exports.NumberPipe = number_pipe_2.NumberPipe; + exports.DecimalPipe = number_pipe_2.DecimalPipe; + exports.PercentPipe = number_pipe_2.PercentPipe; + exports.CurrencyPipe = number_pipe_2.CurrencyPipe; + var uppercase_pipe_2 = require("angular2/src/common/pipes/uppercase_pipe"); + exports.UpperCasePipe = uppercase_pipe_2.UpperCasePipe; + exports.COMMON_PIPES = lang_1.CONST_EXPR([async_pipe_1.AsyncPipe, uppercase_pipe_1.UpperCasePipe, lowercase_pipe_1.LowerCasePipe, json_pipe_1.JsonPipe, slice_pipe_1.SlicePipe, number_pipe_1.DecimalPipe, number_pipe_1.PercentPipe, number_pipe_1.CurrencyPipe, date_pipe_1.DatePipe]); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms/directives/ng_control_name", ["angular2/src/facade/lang", "angular2/src/facade/async", "angular2/core", "angular2/src/common/forms/directives/control_container", "angular2/src/common/forms/directives/ng_control", "angular2/src/common/forms/directives/control_value_accessor", "angular2/src/common/forms/directives/shared", "angular2/src/common/forms/validators"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var lang_1 = require("angular2/src/facade/lang"); + var async_1 = require("angular2/src/facade/async"); + var core_1 = require("angular2/core"); + var control_container_1 = require("angular2/src/common/forms/directives/control_container"); + var ng_control_1 = require("angular2/src/common/forms/directives/ng_control"); + var control_value_accessor_1 = require("angular2/src/common/forms/directives/control_value_accessor"); + var shared_1 = require("angular2/src/common/forms/directives/shared"); + var validators_1 = require("angular2/src/common/forms/validators"); + var controlNameBinding = lang_1.CONST_EXPR(new core_1.Provider(ng_control_1.NgControl, {useExisting: core_1.forwardRef(function() { + return NgControlName; + })})); + var NgControlName = (function(_super) { + __extends(NgControlName, _super); + function NgControlName(_parent, _validators, _asyncValidators, valueAccessors) { + _super.call(this); + this._parent = _parent; + this._validators = _validators; + this._asyncValidators = _asyncValidators; + this.update = new async_1.EventEmitter(); + this._added = false; + this.valueAccessor = shared_1.selectValueAccessor(this, valueAccessors); + } + NgControlName.prototype.ngOnChanges = function(changes) { + if (!this._added) { + this.formDirective.addControl(this); + this._added = true; + } + if (shared_1.isPropertyUpdated(changes, this.viewModel)) { + this.viewModel = this.model; + this.formDirective.updateModel(this, this.model); + } + }; + NgControlName.prototype.ngOnDestroy = function() { + this.formDirective.removeControl(this); + }; + NgControlName.prototype.viewToModelUpdate = function(newValue) { + this.viewModel = newValue; + async_1.ObservableWrapper.callEmit(this.update, newValue); + }; + Object.defineProperty(NgControlName.prototype, "path", { + get: function() { + return shared_1.controlPath(this.name, this._parent); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgControlName.prototype, "formDirective", { + get: function() { + return this._parent.formDirective; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgControlName.prototype, "validator", { + get: function() { + return shared_1.composeValidators(this._validators); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgControlName.prototype, "asyncValidator", { + get: function() { + return shared_1.composeAsyncValidators(this._asyncValidators); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgControlName.prototype, "control", { + get: function() { + return this.formDirective.getControl(this); + }, + enumerable: true, + configurable: true + }); + NgControlName = __decorate([core_1.Directive({ + selector: '[ngControl]', + bindings: [controlNameBinding], + inputs: ['name: ngControl', 'model: ngModel'], + outputs: ['update: ngModelChange'], + exportAs: 'ngForm' + }), __param(0, core_1.Host()), __param(0, core_1.SkipSelf()), __param(1, core_1.Optional()), __param(1, core_1.Self()), __param(1, core_1.Inject(validators_1.NG_VALIDATORS)), __param(2, core_1.Optional()), __param(2, core_1.Self()), __param(2, core_1.Inject(validators_1.NG_ASYNC_VALIDATORS)), __param(3, core_1.Optional()), __param(3, core_1.Self()), __param(3, core_1.Inject(control_value_accessor_1.NG_VALUE_ACCESSOR)), __metadata('design:paramtypes', [control_container_1.ControlContainer, Array, Array, Array])], NgControlName); + return NgControlName; + })(ng_control_1.NgControl); + exports.NgControlName = NgControlName; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/browser/generic_browser_adapter", ["angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/platform/dom/dom_adapter", "angular2/src/platform/browser/xhr_impl"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); + var xhr_impl_1 = require("angular2/src/platform/browser/xhr_impl"); + var GenericBrowserDomAdapter = (function(_super) { + __extends(GenericBrowserDomAdapter, _super); + function GenericBrowserDomAdapter() { + var _this = this; + _super.call(this); + this._animationPrefix = null; + this._transitionEnd = null; + try { + var element = this.createElement('div', this.defaultDoc()); + if (lang_1.isPresent(this.getStyle(element, 'animationName'))) { + this._animationPrefix = ''; + } else { + var domPrefixes = ['Webkit', 'Moz', 'O', 'ms']; + for (var i = 0; i < domPrefixes.length; i++) { + if (lang_1.isPresent(this.getStyle(element, domPrefixes[i] + 'AnimationName'))) { + this._animationPrefix = '-' + domPrefixes[i].toLowerCase() + '-'; + break; + } + } + } + var transEndEventNames = { + WebkitTransition: 'webkitTransitionEnd', + MozTransition: 'transitionend', + OTransition: 'oTransitionEnd otransitionend', + transition: 'transitionend' + }; + collection_1.StringMapWrapper.forEach(transEndEventNames, function(value, key) { + if (lang_1.isPresent(_this.getStyle(element, key))) { + _this._transitionEnd = value; + } + }); + } catch (e) { + this._animationPrefix = null; + this._transitionEnd = null; + } + } + GenericBrowserDomAdapter.prototype.getXHR = function() { + return xhr_impl_1.XHRImpl; + }; + GenericBrowserDomAdapter.prototype.getDistributedNodes = function(el) { + return el.getDistributedNodes(); + }; + GenericBrowserDomAdapter.prototype.resolveAndSetHref = function(el, baseUrl, href) { + el.href = href == null ? baseUrl : baseUrl + '/../' + href; + }; + GenericBrowserDomAdapter.prototype.supportsDOMEvents = function() { + return true; + }; + GenericBrowserDomAdapter.prototype.supportsNativeShadowDOM = function() { + return lang_1.isFunction(this.defaultDoc().body.createShadowRoot); + }; + GenericBrowserDomAdapter.prototype.getAnimationPrefix = function() { + return lang_1.isPresent(this._animationPrefix) ? this._animationPrefix : ""; + }; + GenericBrowserDomAdapter.prototype.getTransitionEnd = function() { + return lang_1.isPresent(this._transitionEnd) ? this._transitionEnd : ""; + }; + GenericBrowserDomAdapter.prototype.supportsAnimation = function() { + return lang_1.isPresent(this._animationPrefix) && lang_1.isPresent(this._transitionEnd); + }; + return GenericBrowserDomAdapter; + })(dom_adapter_1.DomAdapter); + exports.GenericBrowserDomAdapter = GenericBrowserDomAdapter; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/browser/tools/tools", ["angular2/src/facade/lang", "angular2/src/platform/browser/tools/common_tools"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var common_tools_1 = require("angular2/src/platform/browser/tools/common_tools"); + var context = lang_1.global; + function enableDebugTools(ref) { + context.ng = new common_tools_1.AngularTools(ref); + } + exports.enableDebugTools = enableDebugTools; + function disableDebugTools() { + delete context.ng; + } + exports.disableDebugTools = disableDebugTools; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/change_detector_compiler", ["angular2/src/compiler/source_module", "angular2/src/core/change_detection/change_detection_jit_generator", "angular2/src/compiler/change_definition_factory", "angular2/src/facade/lang", "angular2/src/core/change_detection/change_detection", "angular2/src/transform/template_compiler/change_detector_codegen", "angular2/src/compiler/util", "angular2/src/core/di"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var source_module_1 = require("angular2/src/compiler/source_module"); + var change_detection_jit_generator_1 = require("angular2/src/core/change_detection/change_detection_jit_generator"); + var change_definition_factory_1 = require("angular2/src/compiler/change_definition_factory"); + var lang_1 = require("angular2/src/facade/lang"); + var change_detection_1 = require("angular2/src/core/change_detection/change_detection"); + var change_detector_codegen_1 = require("angular2/src/transform/template_compiler/change_detector_codegen"); + var util_1 = require("angular2/src/compiler/util"); + var di_1 = require("angular2/src/core/di"); + var ABSTRACT_CHANGE_DETECTOR = "AbstractChangeDetector"; + var UTIL = "ChangeDetectionUtil"; + var CHANGE_DETECTOR_STATE = "ChangeDetectorState"; + var ABSTRACT_CHANGE_DETECTOR_MODULE = source_module_1.moduleRef("package:angular2/src/core/change_detection/abstract_change_detector" + util_1.MODULE_SUFFIX); + var UTIL_MODULE = source_module_1.moduleRef("package:angular2/src/core/change_detection/change_detection_util" + util_1.MODULE_SUFFIX); + var PREGEN_PROTO_CHANGE_DETECTOR_MODULE = source_module_1.moduleRef("package:angular2/src/core/change_detection/pregen_proto_change_detector" + util_1.MODULE_SUFFIX); + var CONSTANTS_MODULE = source_module_1.moduleRef("package:angular2/src/core/change_detection/constants" + util_1.MODULE_SUFFIX); + var ChangeDetectionCompiler = (function() { + function ChangeDetectionCompiler(_genConfig) { + this._genConfig = _genConfig; + } + ChangeDetectionCompiler.prototype.compileComponentRuntime = function(componentType, strategy, parsedTemplate) { + var _this = this; + var changeDetectorDefinitions = change_definition_factory_1.createChangeDetectorDefinitions(componentType, strategy, this._genConfig, parsedTemplate); + return changeDetectorDefinitions.map(function(definition) { + return _this._createChangeDetectorFactory(definition); + }); + }; + ChangeDetectionCompiler.prototype._createChangeDetectorFactory = function(definition) { + if (lang_1.IS_DART || !this._genConfig.useJit) { + var proto = new change_detection_1.DynamicProtoChangeDetector(definition); + return function(dispatcher) { + return proto.instantiate(dispatcher); + }; + } else { + return new change_detection_jit_generator_1.ChangeDetectorJITGenerator(definition, UTIL, ABSTRACT_CHANGE_DETECTOR, CHANGE_DETECTOR_STATE).generate(); + } + }; + ChangeDetectionCompiler.prototype.compileComponentCodeGen = function(componentType, strategy, parsedTemplate) { + var changeDetectorDefinitions = change_definition_factory_1.createChangeDetectorDefinitions(componentType, strategy, this._genConfig, parsedTemplate); + var factories = []; + var index = 0; + var sourceParts = changeDetectorDefinitions.map(function(definition) { + var codegen; + var sourcePart; + if (lang_1.IS_DART) { + codegen = new change_detector_codegen_1.Codegen(PREGEN_PROTO_CHANGE_DETECTOR_MODULE); + var className = "_" + definition.id; + var typeRef = (index === 0 && componentType.isHost) ? 'dynamic' : "" + source_module_1.moduleRef(componentType.moduleUrl) + componentType.name; + codegen.generate(typeRef, className, definition); + factories.push(className + ".newChangeDetector"); + sourcePart = codegen.toString(); + } else { + codegen = new change_detection_jit_generator_1.ChangeDetectorJITGenerator(definition, "" + UTIL_MODULE + UTIL, "" + ABSTRACT_CHANGE_DETECTOR_MODULE + ABSTRACT_CHANGE_DETECTOR, "" + CONSTANTS_MODULE + CHANGE_DETECTOR_STATE); + factories.push("function(dispatcher) { return new " + codegen.typeName + "(dispatcher); }"); + sourcePart = codegen.generateSource(); + } + index++; + return sourcePart; + }); + return new source_module_1.SourceExpressions(sourceParts, factories); + }; + ChangeDetectionCompiler = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [change_detection_1.ChangeDetectorGenConfig])], ChangeDetectionCompiler); + return ChangeDetectionCompiler; + })(); + exports.ChangeDetectionCompiler = ChangeDetectionCompiler; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/html_parser", ["angular2/src/facade/lang", "angular2/src/facade/collection", "angular2/src/compiler/html_ast", "angular2/src/core/di", "angular2/src/compiler/html_lexer", "angular2/src/compiler/parse_util", "angular2/src/compiler/html_tags"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var collection_1 = require("angular2/src/facade/collection"); + var html_ast_1 = require("angular2/src/compiler/html_ast"); + var di_1 = require("angular2/src/core/di"); + var html_lexer_1 = require("angular2/src/compiler/html_lexer"); + var parse_util_1 = require("angular2/src/compiler/parse_util"); + var html_tags_1 = require("angular2/src/compiler/html_tags"); + var HtmlTreeError = (function(_super) { + __extends(HtmlTreeError, _super); + function HtmlTreeError(elementName, location, msg) { + _super.call(this, location, msg); + this.elementName = elementName; + } + HtmlTreeError.create = function(elementName, location, msg) { + return new HtmlTreeError(elementName, location, msg); + }; + return HtmlTreeError; + })(parse_util_1.ParseError); + exports.HtmlTreeError = HtmlTreeError; + var HtmlParseTreeResult = (function() { + function HtmlParseTreeResult(rootNodes, errors) { + this.rootNodes = rootNodes; + this.errors = errors; + } + return HtmlParseTreeResult; + })(); + exports.HtmlParseTreeResult = HtmlParseTreeResult; + var HtmlParser = (function() { + function HtmlParser() {} + HtmlParser.prototype.parse = function(sourceContent, sourceUrl) { + var tokensAndErrors = html_lexer_1.tokenizeHtml(sourceContent, sourceUrl); + var treeAndErrors = new TreeBuilder(tokensAndErrors.tokens).build(); + return new HtmlParseTreeResult(treeAndErrors.rootNodes, tokensAndErrors.errors.concat(treeAndErrors.errors)); + }; + HtmlParser = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], HtmlParser); + return HtmlParser; + })(); + exports.HtmlParser = HtmlParser; + var TreeBuilder = (function() { + function TreeBuilder(tokens) { + this.tokens = tokens; + this.index = -1; + this.rootNodes = []; + this.errors = []; + this.elementStack = []; + this._advance(); + } + TreeBuilder.prototype.build = function() { + while (this.peek.type !== html_lexer_1.HtmlTokenType.EOF) { + if (this.peek.type === html_lexer_1.HtmlTokenType.TAG_OPEN_START) { + this._consumeStartTag(this._advance()); + } else if (this.peek.type === html_lexer_1.HtmlTokenType.TAG_CLOSE) { + this._consumeEndTag(this._advance()); + } else if (this.peek.type === html_lexer_1.HtmlTokenType.CDATA_START) { + this._closeVoidElement(); + this._consumeCdata(this._advance()); + } else if (this.peek.type === html_lexer_1.HtmlTokenType.COMMENT_START) { + this._closeVoidElement(); + this._consumeComment(this._advance()); + } else if (this.peek.type === html_lexer_1.HtmlTokenType.TEXT || this.peek.type === html_lexer_1.HtmlTokenType.RAW_TEXT || this.peek.type === html_lexer_1.HtmlTokenType.ESCAPABLE_RAW_TEXT) { + this._closeVoidElement(); + this._consumeText(this._advance()); + } else { + this._advance(); + } + } + return new HtmlParseTreeResult(this.rootNodes, this.errors); + }; + TreeBuilder.prototype._advance = function() { + var prev = this.peek; + if (this.index < this.tokens.length - 1) { + this.index++; + } + this.peek = this.tokens[this.index]; + return prev; + }; + TreeBuilder.prototype._advanceIf = function(type) { + if (this.peek.type === type) { + return this._advance(); + } + return null; + }; + TreeBuilder.prototype._consumeCdata = function(startToken) { + this._consumeText(this._advance()); + this._advanceIf(html_lexer_1.HtmlTokenType.CDATA_END); + }; + TreeBuilder.prototype._consumeComment = function(startToken) { + this._advanceIf(html_lexer_1.HtmlTokenType.RAW_TEXT); + this._advanceIf(html_lexer_1.HtmlTokenType.COMMENT_END); + }; + TreeBuilder.prototype._consumeText = function(token) { + var text = token.parts[0]; + if (text.length > 0 && text[0] == '\n') { + var parent_1 = this._getParentElement(); + if (lang_1.isPresent(parent_1) && parent_1.children.length == 0 && html_tags_1.getHtmlTagDefinition(parent_1.name).ignoreFirstLf) { + text = text.substring(1); + } + } + if (text.length > 0) { + this._addToParent(new html_ast_1.HtmlTextAst(text, token.sourceSpan)); + } + }; + TreeBuilder.prototype._closeVoidElement = function() { + if (this.elementStack.length > 0) { + var el = collection_1.ListWrapper.last(this.elementStack); + if (html_tags_1.getHtmlTagDefinition(el.name).isVoid) { + this.elementStack.pop(); + } + } + }; + TreeBuilder.prototype._consumeStartTag = function(startTagToken) { + var prefix = startTagToken.parts[0]; + var name = startTagToken.parts[1]; + var attrs = []; + while (this.peek.type === html_lexer_1.HtmlTokenType.ATTR_NAME) { + attrs.push(this._consumeAttr(this._advance())); + } + var fullName = getElementFullName(prefix, name, this._getParentElement()); + var selfClosing = false; + if (this.peek.type === html_lexer_1.HtmlTokenType.TAG_OPEN_END_VOID) { + this._advance(); + selfClosing = true; + if (html_tags_1.getNsPrefix(fullName) == null && !html_tags_1.getHtmlTagDefinition(fullName).isVoid) { + this.errors.push(HtmlTreeError.create(fullName, startTagToken.sourceSpan.start, "Only void and foreign elements can be self closed \"" + startTagToken.parts[1] + "\"")); + } + } else if (this.peek.type === html_lexer_1.HtmlTokenType.TAG_OPEN_END) { + this._advance(); + selfClosing = false; + } + var end = this.peek.sourceSpan.start; + var el = new html_ast_1.HtmlElementAst(fullName, attrs, [], new parse_util_1.ParseSourceSpan(startTagToken.sourceSpan.start, end)); + this._pushElement(el); + if (selfClosing) { + this._popElement(fullName); + } + }; + TreeBuilder.prototype._pushElement = function(el) { + if (this.elementStack.length > 0) { + var parentEl = collection_1.ListWrapper.last(this.elementStack); + if (html_tags_1.getHtmlTagDefinition(parentEl.name).isClosedByChild(el.name)) { + this.elementStack.pop(); + } + } + var tagDef = html_tags_1.getHtmlTagDefinition(el.name); + var parentEl = this._getParentElement(); + if (tagDef.requireExtraParent(lang_1.isPresent(parentEl) ? parentEl.name : null)) { + var newParent = new html_ast_1.HtmlElementAst(tagDef.parentToAdd, [], [el], el.sourceSpan); + this._addToParent(newParent); + this.elementStack.push(newParent); + this.elementStack.push(el); + } else { + this._addToParent(el); + this.elementStack.push(el); + } + }; + TreeBuilder.prototype._consumeEndTag = function(endTagToken) { + var fullName = getElementFullName(endTagToken.parts[0], endTagToken.parts[1], this._getParentElement()); + if (html_tags_1.getHtmlTagDefinition(fullName).isVoid) { + this.errors.push(HtmlTreeError.create(fullName, endTagToken.sourceSpan.start, "Void elements do not have end tags \"" + endTagToken.parts[1] + "\"")); + } else if (!this._popElement(fullName)) { + this.errors.push(HtmlTreeError.create(fullName, endTagToken.sourceSpan.start, "Unexpected closing tag \"" + endTagToken.parts[1] + "\"")); + } + }; + TreeBuilder.prototype._popElement = function(fullName) { + for (var stackIndex = this.elementStack.length - 1; stackIndex >= 0; stackIndex--) { + var el = this.elementStack[stackIndex]; + if (el.name == fullName) { + collection_1.ListWrapper.splice(this.elementStack, stackIndex, this.elementStack.length - stackIndex); + return true; + } + if (!html_tags_1.getHtmlTagDefinition(el.name).closedByParent) { + return false; + } + } + return false; + }; + TreeBuilder.prototype._consumeAttr = function(attrName) { + var fullName = mergeNsAndName(attrName.parts[0], attrName.parts[1]); + var end = attrName.sourceSpan.end; + var value = ''; + if (this.peek.type === html_lexer_1.HtmlTokenType.ATTR_VALUE) { + var valueToken = this._advance(); + value = valueToken.parts[0]; + end = valueToken.sourceSpan.end; + } + return new html_ast_1.HtmlAttrAst(fullName, value, new parse_util_1.ParseSourceSpan(attrName.sourceSpan.start, end)); + }; + TreeBuilder.prototype._getParentElement = function() { + return this.elementStack.length > 0 ? collection_1.ListWrapper.last(this.elementStack) : null; + }; + TreeBuilder.prototype._addToParent = function(node) { + var parent = this._getParentElement(); + if (lang_1.isPresent(parent)) { + parent.children.push(node); + } else { + this.rootNodes.push(node); + } + }; + return TreeBuilder; + })(); + function mergeNsAndName(prefix, localName) { + return lang_1.isPresent(prefix) ? "@" + prefix + ":" + localName : localName; + } + function getElementFullName(prefix, localName, parentElement) { + if (lang_1.isBlank(prefix)) { + prefix = html_tags_1.getHtmlTagDefinition(localName).implicitNamespacePrefix; + if (lang_1.isBlank(prefix) && lang_1.isPresent(parentElement)) { + prefix = html_tags_1.getNsPrefix(parentElement.name); + } + } + return mergeNsAndName(prefix, localName); + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/forms", ["angular2/src/common/forms/model", "angular2/src/common/forms/directives/abstract_control_directive", "angular2/src/common/forms/directives/control_container", "angular2/src/common/forms/directives/ng_control_name", "angular2/src/common/forms/directives/ng_form_control", "angular2/src/common/forms/directives/ng_model", "angular2/src/common/forms/directives/ng_control", "angular2/src/common/forms/directives/ng_control_group", "angular2/src/common/forms/directives/ng_form_model", "angular2/src/common/forms/directives/ng_form", "angular2/src/common/forms/directives/control_value_accessor", "angular2/src/common/forms/directives/default_value_accessor", "angular2/src/common/forms/directives/ng_control_status", "angular2/src/common/forms/directives/checkbox_value_accessor", "angular2/src/common/forms/directives/select_control_value_accessor", "angular2/src/common/forms/directives", "angular2/src/common/forms/validators", "angular2/src/common/forms/directives/validators", "angular2/src/common/forms/form_builder"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var model_1 = require("angular2/src/common/forms/model"); + exports.AbstractControl = model_1.AbstractControl; + exports.Control = model_1.Control; + exports.ControlGroup = model_1.ControlGroup; + exports.ControlArray = model_1.ControlArray; + var abstract_control_directive_1 = require("angular2/src/common/forms/directives/abstract_control_directive"); + exports.AbstractControlDirective = abstract_control_directive_1.AbstractControlDirective; + var control_container_1 = require("angular2/src/common/forms/directives/control_container"); + exports.ControlContainer = control_container_1.ControlContainer; + var ng_control_name_1 = require("angular2/src/common/forms/directives/ng_control_name"); + exports.NgControlName = ng_control_name_1.NgControlName; + var ng_form_control_1 = require("angular2/src/common/forms/directives/ng_form_control"); + exports.NgFormControl = ng_form_control_1.NgFormControl; + var ng_model_1 = require("angular2/src/common/forms/directives/ng_model"); + exports.NgModel = ng_model_1.NgModel; + var ng_control_1 = require("angular2/src/common/forms/directives/ng_control"); + exports.NgControl = ng_control_1.NgControl; + var ng_control_group_1 = require("angular2/src/common/forms/directives/ng_control_group"); + exports.NgControlGroup = ng_control_group_1.NgControlGroup; + var ng_form_model_1 = require("angular2/src/common/forms/directives/ng_form_model"); + exports.NgFormModel = ng_form_model_1.NgFormModel; + var ng_form_1 = require("angular2/src/common/forms/directives/ng_form"); + exports.NgForm = ng_form_1.NgForm; + var control_value_accessor_1 = require("angular2/src/common/forms/directives/control_value_accessor"); + exports.NG_VALUE_ACCESSOR = control_value_accessor_1.NG_VALUE_ACCESSOR; + var default_value_accessor_1 = require("angular2/src/common/forms/directives/default_value_accessor"); + exports.DefaultValueAccessor = default_value_accessor_1.DefaultValueAccessor; + var ng_control_status_1 = require("angular2/src/common/forms/directives/ng_control_status"); + exports.NgControlStatus = ng_control_status_1.NgControlStatus; + var checkbox_value_accessor_1 = require("angular2/src/common/forms/directives/checkbox_value_accessor"); + exports.CheckboxControlValueAccessor = checkbox_value_accessor_1.CheckboxControlValueAccessor; + var select_control_value_accessor_1 = require("angular2/src/common/forms/directives/select_control_value_accessor"); + exports.NgSelectOption = select_control_value_accessor_1.NgSelectOption; + exports.SelectControlValueAccessor = select_control_value_accessor_1.SelectControlValueAccessor; + var directives_1 = require("angular2/src/common/forms/directives"); + exports.FORM_DIRECTIVES = directives_1.FORM_DIRECTIVES; + var validators_1 = require("angular2/src/common/forms/validators"); + exports.NG_VALIDATORS = validators_1.NG_VALIDATORS; + exports.NG_ASYNC_VALIDATORS = validators_1.NG_ASYNC_VALIDATORS; + exports.Validators = validators_1.Validators; + var validators_2 = require("angular2/src/common/forms/directives/validators"); + exports.RequiredValidator = validators_2.RequiredValidator; + exports.MinLengthValidator = validators_2.MinLengthValidator; + exports.MaxLengthValidator = validators_2.MaxLengthValidator; + var form_builder_1 = require("angular2/src/common/forms/form_builder"); + exports.FormBuilder = form_builder_1.FormBuilder; + exports.FORM_PROVIDERS = form_builder_1.FORM_PROVIDERS; + exports.FORM_BINDINGS = form_builder_1.FORM_BINDINGS; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/browser/browser_adapter", ["angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/platform/dom/dom_adapter", "angular2/src/platform/browser/generic_browser_adapter"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); + var generic_browser_adapter_1 = require("angular2/src/platform/browser/generic_browser_adapter"); + var _attrToPropMap = { + 'class': 'className', + 'innerHtml': 'innerHTML', + 'readonly': 'readOnly', + 'tabindex': 'tabIndex' + }; + var DOM_KEY_LOCATION_NUMPAD = 3; + var _keyMap = { + '\b': 'Backspace', + '\t': 'Tab', + '\x7F': 'Delete', + '\x1B': 'Escape', + 'Del': 'Delete', + 'Esc': 'Escape', + 'Left': 'ArrowLeft', + 'Right': 'ArrowRight', + 'Up': 'ArrowUp', + 'Down': 'ArrowDown', + 'Menu': 'ContextMenu', + 'Scroll': 'ScrollLock', + 'Win': 'OS' + }; + var _chromeNumKeyPadMap = { + 'A': '1', + 'B': '2', + 'C': '3', + 'D': '4', + 'E': '5', + 'F': '6', + 'G': '7', + 'H': '8', + 'I': '9', + 'J': '*', + 'K': '+', + 'M': '-', + 'N': '.', + 'O': '/', + '\x60': '0', + '\x90': 'NumLock' + }; + var BrowserDomAdapter = (function(_super) { + __extends(BrowserDomAdapter, _super); + function BrowserDomAdapter() { + _super.apply(this, arguments); + } + BrowserDomAdapter.prototype.parse = function(templateHtml) { + throw new Error("parse not implemented"); + }; + BrowserDomAdapter.makeCurrent = function() { + dom_adapter_1.setRootDomAdapter(new BrowserDomAdapter()); + }; + BrowserDomAdapter.prototype.hasProperty = function(element, name) { + return name in element; + }; + BrowserDomAdapter.prototype.setProperty = function(el, name, value) { + el[name] = value; + }; + BrowserDomAdapter.prototype.getProperty = function(el, name) { + return el[name]; + }; + BrowserDomAdapter.prototype.invoke = function(el, methodName, args) { + el[methodName].apply(el, args); + }; + BrowserDomAdapter.prototype.logError = function(error) { + if (window.console.error) { + window.console.error(error); + } else { + window.console.log(error); + } + }; + BrowserDomAdapter.prototype.log = function(error) { + window.console.log(error); + }; + BrowserDomAdapter.prototype.logGroup = function(error) { + if (window.console.group) { + window.console.group(error); + this.logError(error); + } else { + window.console.log(error); + } + }; + BrowserDomAdapter.prototype.logGroupEnd = function() { + if (window.console.groupEnd) { + window.console.groupEnd(); + } + }; + Object.defineProperty(BrowserDomAdapter.prototype, "attrToPropMap", { + get: function() { + return _attrToPropMap; + }, + enumerable: true, + configurable: true + }); + BrowserDomAdapter.prototype.query = function(selector) { + return document.querySelector(selector); + }; + BrowserDomAdapter.prototype.querySelector = function(el, selector) { + return el.querySelector(selector); + }; + BrowserDomAdapter.prototype.querySelectorAll = function(el, selector) { + return el.querySelectorAll(selector); + }; + BrowserDomAdapter.prototype.on = function(el, evt, listener) { + el.addEventListener(evt, listener, false); + }; + BrowserDomAdapter.prototype.onAndCancel = function(el, evt, listener) { + el.addEventListener(evt, listener, false); + return function() { + el.removeEventListener(evt, listener, false); + }; + }; + BrowserDomAdapter.prototype.dispatchEvent = function(el, evt) { + el.dispatchEvent(evt); + }; + BrowserDomAdapter.prototype.createMouseEvent = function(eventType) { + var evt = document.createEvent('MouseEvent'); + evt.initEvent(eventType, true, true); + return evt; + }; + BrowserDomAdapter.prototype.createEvent = function(eventType) { + var evt = document.createEvent('Event'); + evt.initEvent(eventType, true, true); + return evt; + }; + BrowserDomAdapter.prototype.preventDefault = function(evt) { + evt.preventDefault(); + evt.returnValue = false; + }; + BrowserDomAdapter.prototype.isPrevented = function(evt) { + return evt.defaultPrevented || lang_1.isPresent(evt.returnValue) && !evt.returnValue; + }; + BrowserDomAdapter.prototype.getInnerHTML = function(el) { + return el.innerHTML; + }; + BrowserDomAdapter.prototype.getOuterHTML = function(el) { + return el.outerHTML; + }; + BrowserDomAdapter.prototype.nodeName = function(node) { + return node.nodeName; + }; + BrowserDomAdapter.prototype.nodeValue = function(node) { + return node.nodeValue; + }; + BrowserDomAdapter.prototype.type = function(node) { + return node.type; + }; + BrowserDomAdapter.prototype.content = function(node) { + if (this.hasProperty(node, "content")) { + return node.content; + } else { + return node; + } + }; + BrowserDomAdapter.prototype.firstChild = function(el) { + return el.firstChild; + }; + BrowserDomAdapter.prototype.nextSibling = function(el) { + return el.nextSibling; + }; + BrowserDomAdapter.prototype.parentElement = function(el) { + return el.parentNode; + }; + BrowserDomAdapter.prototype.childNodes = function(el) { + return el.childNodes; + }; + BrowserDomAdapter.prototype.childNodesAsList = function(el) { + var childNodes = el.childNodes; + var res = collection_1.ListWrapper.createFixedSize(childNodes.length); + for (var i = 0; i < childNodes.length; i++) { + res[i] = childNodes[i]; + } + return res; + }; + BrowserDomAdapter.prototype.clearNodes = function(el) { + while (el.firstChild) { + el.removeChild(el.firstChild); + } + }; + BrowserDomAdapter.prototype.appendChild = function(el, node) { + el.appendChild(node); + }; + BrowserDomAdapter.prototype.removeChild = function(el, node) { + el.removeChild(node); + }; + BrowserDomAdapter.prototype.replaceChild = function(el, newChild, oldChild) { + el.replaceChild(newChild, oldChild); + }; + BrowserDomAdapter.prototype.remove = function(node) { + if (node.parentNode) { + node.parentNode.removeChild(node); + } + return node; + }; + BrowserDomAdapter.prototype.insertBefore = function(el, node) { + el.parentNode.insertBefore(node, el); + }; + BrowserDomAdapter.prototype.insertAllBefore = function(el, nodes) { + nodes.forEach(function(n) { + return el.parentNode.insertBefore(n, el); + }); + }; + BrowserDomAdapter.prototype.insertAfter = function(el, node) { + el.parentNode.insertBefore(node, el.nextSibling); + }; + BrowserDomAdapter.prototype.setInnerHTML = function(el, value) { + el.innerHTML = value; + }; + BrowserDomAdapter.prototype.getText = function(el) { + return el.textContent; + }; + BrowserDomAdapter.prototype.setText = function(el, value) { + el.textContent = value; + }; + BrowserDomAdapter.prototype.getValue = function(el) { + return el.value; + }; + BrowserDomAdapter.prototype.setValue = function(el, value) { + el.value = value; + }; + BrowserDomAdapter.prototype.getChecked = function(el) { + return el.checked; + }; + BrowserDomAdapter.prototype.setChecked = function(el, value) { + el.checked = value; + }; + BrowserDomAdapter.prototype.createComment = function(text) { + return document.createComment(text); + }; + BrowserDomAdapter.prototype.createTemplate = function(html) { + var t = document.createElement('template'); + t.innerHTML = html; + return t; + }; + BrowserDomAdapter.prototype.createElement = function(tagName, doc) { + if (doc === void 0) { + doc = document; + } + return doc.createElement(tagName); + }; + BrowserDomAdapter.prototype.createElementNS = function(ns, tagName, doc) { + if (doc === void 0) { + doc = document; + } + return doc.createElementNS(ns, tagName); + }; + BrowserDomAdapter.prototype.createTextNode = function(text, doc) { + if (doc === void 0) { + doc = document; + } + return doc.createTextNode(text); + }; + BrowserDomAdapter.prototype.createScriptTag = function(attrName, attrValue, doc) { + if (doc === void 0) { + doc = document; + } + var el = doc.createElement('SCRIPT'); + el.setAttribute(attrName, attrValue); + return el; + }; + BrowserDomAdapter.prototype.createStyleElement = function(css, doc) { + if (doc === void 0) { + doc = document; + } + var style = doc.createElement('style'); + this.appendChild(style, this.createTextNode(css)); + return style; + }; + BrowserDomAdapter.prototype.createShadowRoot = function(el) { + return el.createShadowRoot(); + }; + BrowserDomAdapter.prototype.getShadowRoot = function(el) { + return el.shadowRoot; + }; + BrowserDomAdapter.prototype.getHost = function(el) { + return el.host; + }; + BrowserDomAdapter.prototype.clone = function(node) { + return node.cloneNode(true); + }; + BrowserDomAdapter.prototype.getElementsByClassName = function(element, name) { + return element.getElementsByClassName(name); + }; + BrowserDomAdapter.prototype.getElementsByTagName = function(element, name) { + return element.getElementsByTagName(name); + }; + BrowserDomAdapter.prototype.classList = function(element) { + return Array.prototype.slice.call(element.classList, 0); + }; + BrowserDomAdapter.prototype.addClass = function(element, className) { + element.classList.add(className); + }; + BrowserDomAdapter.prototype.removeClass = function(element, className) { + element.classList.remove(className); + }; + BrowserDomAdapter.prototype.hasClass = function(element, className) { + return element.classList.contains(className); + }; + BrowserDomAdapter.prototype.setStyle = function(element, styleName, styleValue) { + element.style[styleName] = styleValue; + }; + BrowserDomAdapter.prototype.removeStyle = function(element, stylename) { + element.style[stylename] = null; + }; + BrowserDomAdapter.prototype.getStyle = function(element, stylename) { + return element.style[stylename]; + }; + BrowserDomAdapter.prototype.hasStyle = function(element, styleName, styleValue) { + if (styleValue === void 0) { + styleValue = null; + } + var value = this.getStyle(element, styleName) || ''; + return styleValue ? value == styleValue : value.length > 0; + }; + BrowserDomAdapter.prototype.tagName = function(element) { + return element.tagName; + }; + BrowserDomAdapter.prototype.attributeMap = function(element) { + var res = new Map(); + var elAttrs = element.attributes; + for (var i = 0; i < elAttrs.length; i++) { + var attrib = elAttrs[i]; + res.set(attrib.name, attrib.value); + } + return res; + }; + BrowserDomAdapter.prototype.hasAttribute = function(element, attribute) { + return element.hasAttribute(attribute); + }; + BrowserDomAdapter.prototype.getAttribute = function(element, attribute) { + return element.getAttribute(attribute); + }; + BrowserDomAdapter.prototype.setAttribute = function(element, name, value) { + element.setAttribute(name, value); + }; + BrowserDomAdapter.prototype.setAttributeNS = function(element, ns, name, value) { + element.setAttributeNS(ns, name, value); + }; + BrowserDomAdapter.prototype.removeAttribute = function(element, attribute) { + element.removeAttribute(attribute); + }; + BrowserDomAdapter.prototype.templateAwareRoot = function(el) { + return this.isTemplateElement(el) ? this.content(el) : el; + }; + BrowserDomAdapter.prototype.createHtmlDocument = function() { + return document.implementation.createHTMLDocument('fakeTitle'); + }; + BrowserDomAdapter.prototype.defaultDoc = function() { + return document; + }; + BrowserDomAdapter.prototype.getBoundingClientRect = function(el) { + try { + return el.getBoundingClientRect(); + } catch (e) { + return { + top: 0, + bottom: 0, + left: 0, + right: 0, + width: 0, + height: 0 + }; + } + }; + BrowserDomAdapter.prototype.getTitle = function() { + return document.title; + }; + BrowserDomAdapter.prototype.setTitle = function(newTitle) { + document.title = newTitle || ''; + }; + BrowserDomAdapter.prototype.elementMatches = function(n, selector) { + var matches = false; + if (n instanceof HTMLElement) { + if (n.matches) { + matches = n.matches(selector); + } else if (n.msMatchesSelector) { + matches = n.msMatchesSelector(selector); + } else if (n.webkitMatchesSelector) { + matches = n.webkitMatchesSelector(selector); + } + } + return matches; + }; + BrowserDomAdapter.prototype.isTemplateElement = function(el) { + return el instanceof HTMLElement && el.nodeName == "TEMPLATE"; + }; + BrowserDomAdapter.prototype.isTextNode = function(node) { + return node.nodeType === Node.TEXT_NODE; + }; + BrowserDomAdapter.prototype.isCommentNode = function(node) { + return node.nodeType === Node.COMMENT_NODE; + }; + BrowserDomAdapter.prototype.isElementNode = function(node) { + return node.nodeType === Node.ELEMENT_NODE; + }; + BrowserDomAdapter.prototype.hasShadowRoot = function(node) { + return node instanceof HTMLElement && lang_1.isPresent(node.shadowRoot); + }; + BrowserDomAdapter.prototype.isShadowRoot = function(node) { + return node instanceof DocumentFragment; + }; + BrowserDomAdapter.prototype.importIntoDoc = function(node) { + var toImport = node; + if (this.isTemplateElement(node)) { + toImport = this.content(node); + } + return document.importNode(toImport, true); + }; + BrowserDomAdapter.prototype.adoptNode = function(node) { + return document.adoptNode(node); + }; + BrowserDomAdapter.prototype.getHref = function(el) { + return el.href; + }; + BrowserDomAdapter.prototype.getEventKey = function(event) { + var key = event.key; + if (lang_1.isBlank(key)) { + key = event.keyIdentifier; + if (lang_1.isBlank(key)) { + return 'Unidentified'; + } + if (key.startsWith('U+')) { + key = String.fromCharCode(parseInt(key.substring(2), 16)); + if (event.location === DOM_KEY_LOCATION_NUMPAD && _chromeNumKeyPadMap.hasOwnProperty(key)) { + key = _chromeNumKeyPadMap[key]; + } + } + } + if (_keyMap.hasOwnProperty(key)) { + key = _keyMap[key]; + } + return key; + }; + BrowserDomAdapter.prototype.getGlobalEventTarget = function(target) { + if (target == "window") { + return window; + } else if (target == "document") { + return document; + } else if (target == "body") { + return document.body; + } + }; + BrowserDomAdapter.prototype.getHistory = function() { + return window.history; + }; + BrowserDomAdapter.prototype.getLocation = function() { + return window.location; + }; + BrowserDomAdapter.prototype.getBaseHref = function() { + var href = getBaseElementHref(); + if (lang_1.isBlank(href)) { + return null; + } + return relativePath(href); + }; + BrowserDomAdapter.prototype.resetBaseElement = function() { + baseElement = null; + }; + BrowserDomAdapter.prototype.getUserAgent = function() { + return window.navigator.userAgent; + }; + BrowserDomAdapter.prototype.setData = function(element, name, value) { + this.setAttribute(element, 'data-' + name, value); + }; + BrowserDomAdapter.prototype.getData = function(element, name) { + return this.getAttribute(element, 'data-' + name); + }; + BrowserDomAdapter.prototype.getComputedStyle = function(element) { + return getComputedStyle(element); + }; + BrowserDomAdapter.prototype.setGlobalVar = function(path, value) { + lang_1.setValueOnPath(lang_1.global, path, value); + }; + BrowserDomAdapter.prototype.requestAnimationFrame = function(callback) { + return window.requestAnimationFrame(callback); + }; + BrowserDomAdapter.prototype.cancelAnimationFrame = function(id) { + window.cancelAnimationFrame(id); + }; + BrowserDomAdapter.prototype.performanceNow = function() { + if (lang_1.isPresent(window.performance) && lang_1.isPresent(window.performance.now)) { + return window.performance.now(); + } else { + return lang_1.DateWrapper.toMillis(lang_1.DateWrapper.now()); + } + }; + return BrowserDomAdapter; + })(generic_browser_adapter_1.GenericBrowserDomAdapter); + exports.BrowserDomAdapter = BrowserDomAdapter; + var baseElement = null; + function getBaseElementHref() { + if (lang_1.isBlank(baseElement)) { + baseElement = document.querySelector('base'); + if (lang_1.isBlank(baseElement)) { + return null; + } + } + return baseElement.getAttribute('href'); + } + var urlParsingNode = null; + function relativePath(url) { + if (lang_1.isBlank(urlParsingNode)) { + urlParsingNode = document.createElement("a"); + } + urlParsingNode.setAttribute('href', url); + return (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : '/' + urlParsingNode.pathname; + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/template_parser", ["angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/core", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/core/change_detection/change_detection", "angular2/src/compiler/html_parser", "angular2/src/compiler/html_tags", "angular2/src/compiler/parse_util", "angular2/src/compiler/template_ast", "angular2/src/compiler/selector", "angular2/src/compiler/schema/element_schema_registry", "angular2/src/compiler/template_preparser", "angular2/src/compiler/style_url_resolver", "angular2/src/compiler/html_ast", "angular2/src/compiler/util"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var core_1 = require("angular2/core"); + var lang_2 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var change_detection_1 = require("angular2/src/core/change_detection/change_detection"); + var html_parser_1 = require("angular2/src/compiler/html_parser"); + var html_tags_1 = require("angular2/src/compiler/html_tags"); + var parse_util_1 = require("angular2/src/compiler/parse_util"); + var template_ast_1 = require("angular2/src/compiler/template_ast"); + var selector_1 = require("angular2/src/compiler/selector"); + var element_schema_registry_1 = require("angular2/src/compiler/schema/element_schema_registry"); + var template_preparser_1 = require("angular2/src/compiler/template_preparser"); + var style_url_resolver_1 = require("angular2/src/compiler/style_url_resolver"); + var html_ast_1 = require("angular2/src/compiler/html_ast"); + var util_1 = require("angular2/src/compiler/util"); + var BIND_NAME_REGEXP = /^(?:(?:(?:(bind-)|(var-|#)|(on-)|(bindon-))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/g; + var TEMPLATE_ELEMENT = 'template'; + var TEMPLATE_ATTR = 'template'; + var TEMPLATE_ATTR_PREFIX = '*'; + var CLASS_ATTR = 'class'; + var PROPERTY_PARTS_SEPARATOR = '.'; + var ATTRIBUTE_PREFIX = 'attr'; + var CLASS_PREFIX = 'class'; + var STYLE_PREFIX = 'style'; + var TEXT_CSS_SELECTOR = selector_1.CssSelector.parse('*')[0]; + exports.TEMPLATE_TRANSFORMS = lang_2.CONST_EXPR(new core_1.OpaqueToken('TemplateTransforms')); + var TemplateParseError = (function(_super) { + __extends(TemplateParseError, _super); + function TemplateParseError(message, location) { + _super.call(this, location, message); + } + return TemplateParseError; + })(parse_util_1.ParseError); + exports.TemplateParseError = TemplateParseError; + var TemplateParser = (function() { + function TemplateParser(_exprParser, _schemaRegistry, _htmlParser, transforms) { + this._exprParser = _exprParser; + this._schemaRegistry = _schemaRegistry; + this._htmlParser = _htmlParser; + this.transforms = transforms; + } + TemplateParser.prototype.parse = function(template, directives, templateUrl) { + var parseVisitor = new TemplateParseVisitor(directives, this._exprParser, this._schemaRegistry); + var htmlAstWithErrors = this._htmlParser.parse(template, templateUrl); + var result = html_ast_1.htmlVisitAll(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_COMPONENT); + var errors = htmlAstWithErrors.errors.concat(parseVisitor.errors); + if (errors.length > 0) { + var errorString = errors.join('\n'); + throw new exceptions_1.BaseException("Template parse errors:\n" + errorString); + } + if (lang_1.isPresent(this.transforms)) { + this.transforms.forEach(function(transform) { + result = template_ast_1.templateVisitAll(transform, result); + }); + } + return result; + }; + TemplateParser = __decorate([core_1.Injectable(), __param(3, core_1.Optional()), __param(3, core_1.Inject(exports.TEMPLATE_TRANSFORMS)), __metadata('design:paramtypes', [change_detection_1.Parser, element_schema_registry_1.ElementSchemaRegistry, html_parser_1.HtmlParser, Array])], TemplateParser); + return TemplateParser; + })(); + exports.TemplateParser = TemplateParser; + var TemplateParseVisitor = (function() { + function TemplateParseVisitor(directives, _exprParser, _schemaRegistry) { + var _this = this; + this._exprParser = _exprParser; + this._schemaRegistry = _schemaRegistry; + this.errors = []; + this.directivesIndex = new Map(); + this.ngContentCount = 0; + this.selectorMatcher = new selector_1.SelectorMatcher(); + collection_1.ListWrapper.forEachWithIndex(directives, function(directive, index) { + var selector = selector_1.CssSelector.parse(directive.selector); + _this.selectorMatcher.addSelectables(selector, directive); + _this.directivesIndex.set(directive, index); + }); + } + TemplateParseVisitor.prototype._reportError = function(message, sourceSpan) { + this.errors.push(new TemplateParseError(message, sourceSpan.start)); + }; + TemplateParseVisitor.prototype._parseInterpolation = function(value, sourceSpan) { + var sourceInfo = sourceSpan.start.toString(); + try { + return this._exprParser.parseInterpolation(value, sourceInfo); + } catch (e) { + this._reportError("" + e, sourceSpan); + return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); + } + }; + TemplateParseVisitor.prototype._parseAction = function(value, sourceSpan) { + var sourceInfo = sourceSpan.start.toString(); + try { + return this._exprParser.parseAction(value, sourceInfo); + } catch (e) { + this._reportError("" + e, sourceSpan); + return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); + } + }; + TemplateParseVisitor.prototype._parseBinding = function(value, sourceSpan) { + var sourceInfo = sourceSpan.start.toString(); + try { + return this._exprParser.parseBinding(value, sourceInfo); + } catch (e) { + this._reportError("" + e, sourceSpan); + return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); + } + }; + TemplateParseVisitor.prototype._parseTemplateBindings = function(value, sourceSpan) { + var sourceInfo = sourceSpan.start.toString(); + try { + return this._exprParser.parseTemplateBindings(value, sourceInfo); + } catch (e) { + this._reportError("" + e, sourceSpan); + return []; + } + }; + TemplateParseVisitor.prototype.visitText = function(ast, component) { + var ngContentIndex = component.findNgContentIndex(TEXT_CSS_SELECTOR); + var expr = this._parseInterpolation(ast.value, ast.sourceSpan); + if (lang_1.isPresent(expr)) { + return new template_ast_1.BoundTextAst(expr, ngContentIndex, ast.sourceSpan); + } else { + return new template_ast_1.TextAst(ast.value, ngContentIndex, ast.sourceSpan); + } + }; + TemplateParseVisitor.prototype.visitAttr = function(ast, contex) { + return new template_ast_1.AttrAst(ast.name, ast.value, ast.sourceSpan); + }; + TemplateParseVisitor.prototype.visitElement = function(element, component) { + var _this = this; + var nodeName = element.name; + var preparsedElement = template_preparser_1.preparseElement(element); + if (preparsedElement.type === template_preparser_1.PreparsedElementType.SCRIPT || preparsedElement.type === template_preparser_1.PreparsedElementType.STYLE) { + return null; + } + if (preparsedElement.type === template_preparser_1.PreparsedElementType.STYLESHEET && style_url_resolver_1.isStyleUrlResolvable(preparsedElement.hrefAttr)) { + return null; + } + var matchableAttrs = []; + var elementOrDirectiveProps = []; + var vars = []; + var events = []; + var templateElementOrDirectiveProps = []; + var templateVars = []; + var templateMatchableAttrs = []; + var hasInlineTemplates = false; + var attrs = []; + element.attrs.forEach(function(attr) { + matchableAttrs.push([attr.name, attr.value]); + var hasBinding = _this._parseAttr(attr, matchableAttrs, elementOrDirectiveProps, events, vars); + var hasTemplateBinding = _this._parseInlineTemplateBinding(attr, templateMatchableAttrs, templateElementOrDirectiveProps, templateVars); + if (!hasBinding && !hasTemplateBinding) { + attrs.push(_this.visitAttr(attr, null)); + } + if (hasTemplateBinding) { + hasInlineTemplates = true; + } + }); + var lcElName = html_tags_1.splitNsName(nodeName.toLowerCase())[1]; + var isTemplateElement = lcElName == TEMPLATE_ELEMENT; + var elementCssSelector = createElementCssSelector(nodeName, matchableAttrs); + var directives = this._createDirectiveAsts(element.name, this._parseDirectives(this.selectorMatcher, elementCssSelector), elementOrDirectiveProps, isTemplateElement ? [] : vars, element.sourceSpan); + var elementProps = this._createElementPropertyAsts(element.name, elementOrDirectiveProps, directives); + var children = html_ast_1.htmlVisitAll(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this, element.children, Component.create(directives)); + var elementNgContentIndex = hasInlineTemplates ? null : component.findNgContentIndex(elementCssSelector); + var parsedElement; + if (preparsedElement.type === template_preparser_1.PreparsedElementType.NG_CONTENT) { + if (lang_1.isPresent(element.children) && element.children.length > 0) { + this._reportError(" element cannot have content. must be immediately followed by ", element.sourceSpan); + } + parsedElement = new template_ast_1.NgContentAst(this.ngContentCount++, elementNgContentIndex, element.sourceSpan); + } else if (isTemplateElement) { + this._assertAllEventsPublishedByDirectives(directives, events); + this._assertNoComponentsNorElementBindingsOnTemplate(directives, elementProps, element.sourceSpan); + parsedElement = new template_ast_1.EmbeddedTemplateAst(attrs, events, vars, directives, children, elementNgContentIndex, element.sourceSpan); + } else { + this._assertOnlyOneComponent(directives, element.sourceSpan); + var elementExportAsVars = vars.filter(function(varAst) { + return varAst.value.length === 0; + }); + parsedElement = new template_ast_1.ElementAst(nodeName, attrs, elementProps, events, elementExportAsVars, directives, children, elementNgContentIndex, element.sourceSpan); + } + if (hasInlineTemplates) { + var templateCssSelector = createElementCssSelector(TEMPLATE_ELEMENT, templateMatchableAttrs); + var templateDirectives = this._createDirectiveAsts(element.name, this._parseDirectives(this.selectorMatcher, templateCssSelector), templateElementOrDirectiveProps, [], element.sourceSpan); + var templateElementProps = this._createElementPropertyAsts(element.name, templateElementOrDirectiveProps, templateDirectives); + this._assertNoComponentsNorElementBindingsOnTemplate(templateDirectives, templateElementProps, element.sourceSpan); + parsedElement = new template_ast_1.EmbeddedTemplateAst([], [], templateVars, templateDirectives, [parsedElement], component.findNgContentIndex(templateCssSelector), element.sourceSpan); + } + return parsedElement; + }; + TemplateParseVisitor.prototype._parseInlineTemplateBinding = function(attr, targetMatchableAttrs, targetProps, targetVars) { + var templateBindingsSource = null; + if (attr.name == TEMPLATE_ATTR) { + templateBindingsSource = attr.value; + } else if (attr.name.startsWith(TEMPLATE_ATTR_PREFIX)) { + var key = attr.name.substring(TEMPLATE_ATTR_PREFIX.length); + templateBindingsSource = (attr.value.length == 0) ? key : key + ' ' + attr.value; + } + if (lang_1.isPresent(templateBindingsSource)) { + var bindings = this._parseTemplateBindings(templateBindingsSource, attr.sourceSpan); + for (var i = 0; i < bindings.length; i++) { + var binding = bindings[i]; + if (binding.keyIsVar) { + targetVars.push(new template_ast_1.VariableAst(binding.key, binding.name, attr.sourceSpan)); + targetMatchableAttrs.push([binding.key, binding.name]); + } else if (lang_1.isPresent(binding.expression)) { + this._parsePropertyAst(binding.key, binding.expression, attr.sourceSpan, targetMatchableAttrs, targetProps); + } else { + targetMatchableAttrs.push([binding.key, '']); + this._parseLiteralAttr(binding.key, null, attr.sourceSpan, targetProps); + } + } + return true; + } + return false; + }; + TemplateParseVisitor.prototype._parseAttr = function(attr, targetMatchableAttrs, targetProps, targetEvents, targetVars) { + var attrName = this._normalizeAttributeName(attr.name); + var attrValue = attr.value; + var bindParts = lang_1.RegExpWrapper.firstMatch(BIND_NAME_REGEXP, attrName); + var hasBinding = false; + if (lang_1.isPresent(bindParts)) { + hasBinding = true; + if (lang_1.isPresent(bindParts[1])) { + this._parseProperty(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps); + } else if (lang_1.isPresent(bindParts[2])) { + var identifier = bindParts[5]; + this._parseVariable(identifier, attrValue, attr.sourceSpan, targetVars); + } else if (lang_1.isPresent(bindParts[3])) { + this._parseEvent(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); + } else if (lang_1.isPresent(bindParts[4])) { + this._parseProperty(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps); + this._parseAssignmentEvent(bindParts[5], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); + } else if (lang_1.isPresent(bindParts[6])) { + this._parseProperty(bindParts[6], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps); + this._parseAssignmentEvent(bindParts[6], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); + } else if (lang_1.isPresent(bindParts[7])) { + this._parseProperty(bindParts[7], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps); + } else if (lang_1.isPresent(bindParts[8])) { + this._parseEvent(bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); + } + } else { + hasBinding = this._parsePropertyInterpolation(attrName, attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps); + } + if (!hasBinding) { + this._parseLiteralAttr(attrName, attrValue, attr.sourceSpan, targetProps); + } + return hasBinding; + }; + TemplateParseVisitor.prototype._normalizeAttributeName = function(attrName) { + return attrName.toLowerCase().startsWith('data-') ? attrName.substring(5) : attrName; + }; + TemplateParseVisitor.prototype._parseVariable = function(identifier, value, sourceSpan, targetVars) { + if (identifier.indexOf('-') > -1) { + this._reportError("\"-\" is not allowed in variable names", sourceSpan); + } + targetVars.push(new template_ast_1.VariableAst(identifier, value, sourceSpan)); + }; + TemplateParseVisitor.prototype._parseProperty = function(name, expression, sourceSpan, targetMatchableAttrs, targetProps) { + this._parsePropertyAst(name, this._parseBinding(expression, sourceSpan), sourceSpan, targetMatchableAttrs, targetProps); + }; + TemplateParseVisitor.prototype._parsePropertyInterpolation = function(name, value, sourceSpan, targetMatchableAttrs, targetProps) { + var expr = this._parseInterpolation(value, sourceSpan); + if (lang_1.isPresent(expr)) { + this._parsePropertyAst(name, expr, sourceSpan, targetMatchableAttrs, targetProps); + return true; + } + return false; + }; + TemplateParseVisitor.prototype._parsePropertyAst = function(name, ast, sourceSpan, targetMatchableAttrs, targetProps) { + targetMatchableAttrs.push([name, ast.source]); + targetProps.push(new BoundElementOrDirectiveProperty(name, ast, false, sourceSpan)); + }; + TemplateParseVisitor.prototype._parseAssignmentEvent = function(name, expression, sourceSpan, targetMatchableAttrs, targetEvents) { + this._parseEvent(name + "Change", expression + "=$event", sourceSpan, targetMatchableAttrs, targetEvents); + }; + TemplateParseVisitor.prototype._parseEvent = function(name, expression, sourceSpan, targetMatchableAttrs, targetEvents) { + var parts = util_1.splitAtColon(name, [null, name]); + var target = parts[0]; + var eventName = parts[1]; + targetEvents.push(new template_ast_1.BoundEventAst(eventName, target, this._parseAction(expression, sourceSpan), sourceSpan)); + }; + TemplateParseVisitor.prototype._parseLiteralAttr = function(name, value, sourceSpan, targetProps) { + targetProps.push(new BoundElementOrDirectiveProperty(name, this._exprParser.wrapLiteralPrimitive(value, ''), true, sourceSpan)); + }; + TemplateParseVisitor.prototype._parseDirectives = function(selectorMatcher, elementCssSelector) { + var _this = this; + var directives = []; + selectorMatcher.match(elementCssSelector, function(selector, directive) { + directives.push(directive); + }); + collection_1.ListWrapper.sort(directives, function(dir1, dir2) { + var dir1Comp = dir1.isComponent; + var dir2Comp = dir2.isComponent; + if (dir1Comp && !dir2Comp) { + return -1; + } else if (!dir1Comp && dir2Comp) { + return 1; + } else { + return _this.directivesIndex.get(dir1) - _this.directivesIndex.get(dir2); + } + }); + return directives; + }; + TemplateParseVisitor.prototype._createDirectiveAsts = function(elementName, directives, props, possibleExportAsVars, sourceSpan) { + var _this = this; + var matchedVariables = new Set(); + var directiveAsts = directives.map(function(directive) { + var hostProperties = []; + var hostEvents = []; + var directiveProperties = []; + _this._createDirectiveHostPropertyAsts(elementName, directive.hostProperties, sourceSpan, hostProperties); + _this._createDirectiveHostEventAsts(directive.hostListeners, sourceSpan, hostEvents); + _this._createDirectivePropertyAsts(directive.inputs, props, directiveProperties); + var exportAsVars = []; + possibleExportAsVars.forEach(function(varAst) { + if ((varAst.value.length === 0 && directive.isComponent) || (directive.exportAs == varAst.value)) { + exportAsVars.push(varAst); + matchedVariables.add(varAst.name); + } + }); + return new template_ast_1.DirectiveAst(directive, directiveProperties, hostProperties, hostEvents, exportAsVars, sourceSpan); + }); + possibleExportAsVars.forEach(function(varAst) { + if (varAst.value.length > 0 && !collection_1.SetWrapper.has(matchedVariables, varAst.name)) { + _this._reportError("There is no directive with \"exportAs\" set to \"" + varAst.value + "\"", varAst.sourceSpan); + } + }); + return directiveAsts; + }; + TemplateParseVisitor.prototype._createDirectiveHostPropertyAsts = function(elementName, hostProps, sourceSpan, targetPropertyAsts) { + var _this = this; + if (lang_1.isPresent(hostProps)) { + collection_1.StringMapWrapper.forEach(hostProps, function(expression, propName) { + var exprAst = _this._parseBinding(expression, sourceSpan); + targetPropertyAsts.push(_this._createElementPropertyAst(elementName, propName, exprAst, sourceSpan)); + }); + } + }; + TemplateParseVisitor.prototype._createDirectiveHostEventAsts = function(hostListeners, sourceSpan, targetEventAsts) { + var _this = this; + if (lang_1.isPresent(hostListeners)) { + collection_1.StringMapWrapper.forEach(hostListeners, function(expression, propName) { + _this._parseEvent(propName, expression, sourceSpan, [], targetEventAsts); + }); + } + }; + TemplateParseVisitor.prototype._createDirectivePropertyAsts = function(directiveProperties, boundProps, targetBoundDirectiveProps) { + if (lang_1.isPresent(directiveProperties)) { + var boundPropsByName = new Map(); + boundProps.forEach(function(boundProp) { + var prevValue = boundPropsByName.get(boundProp.name); + if (lang_1.isBlank(prevValue) || prevValue.isLiteral) { + boundPropsByName.set(boundProp.name, boundProp); + } + }); + collection_1.StringMapWrapper.forEach(directiveProperties, function(elProp, dirProp) { + var boundProp = boundPropsByName.get(elProp); + if (lang_1.isPresent(boundProp)) { + targetBoundDirectiveProps.push(new template_ast_1.BoundDirectivePropertyAst(dirProp, boundProp.name, boundProp.expression, boundProp.sourceSpan)); + } + }); + } + }; + TemplateParseVisitor.prototype._createElementPropertyAsts = function(elementName, props, directives) { + var _this = this; + var boundElementProps = []; + var boundDirectivePropsIndex = new Map(); + directives.forEach(function(directive) { + directive.inputs.forEach(function(prop) { + boundDirectivePropsIndex.set(prop.templateName, prop); + }); + }); + props.forEach(function(prop) { + if (!prop.isLiteral && lang_1.isBlank(boundDirectivePropsIndex.get(prop.name))) { + boundElementProps.push(_this._createElementPropertyAst(elementName, prop.name, prop.expression, prop.sourceSpan)); + } + }); + return boundElementProps; + }; + TemplateParseVisitor.prototype._createElementPropertyAst = function(elementName, name, ast, sourceSpan) { + var unit = null; + var bindingType; + var boundPropertyName; + var parts = name.split(PROPERTY_PARTS_SEPARATOR); + if (parts.length === 1) { + boundPropertyName = this._schemaRegistry.getMappedPropName(parts[0]); + bindingType = template_ast_1.PropertyBindingType.Property; + if (!this._schemaRegistry.hasProperty(elementName, boundPropertyName)) { + this._reportError("Can't bind to '" + boundPropertyName + "' since it isn't a known native property", sourceSpan); + } + } else { + if (parts[0] == ATTRIBUTE_PREFIX) { + boundPropertyName = parts[1]; + bindingType = template_ast_1.PropertyBindingType.Attribute; + } else if (parts[0] == CLASS_PREFIX) { + boundPropertyName = parts[1]; + bindingType = template_ast_1.PropertyBindingType.Class; + } else if (parts[0] == STYLE_PREFIX) { + unit = parts.length > 2 ? parts[2] : null; + boundPropertyName = parts[1]; + bindingType = template_ast_1.PropertyBindingType.Style; + } else { + this._reportError("Invalid property name '" + name + "'", sourceSpan); + bindingType = null; + } + } + return new template_ast_1.BoundElementPropertyAst(boundPropertyName, bindingType, ast, unit, sourceSpan); + }; + TemplateParseVisitor.prototype._findComponentDirectiveNames = function(directives) { + var componentTypeNames = []; + directives.forEach(function(directive) { + var typeName = directive.directive.type.name; + if (directive.directive.isComponent) { + componentTypeNames.push(typeName); + } + }); + return componentTypeNames; + }; + TemplateParseVisitor.prototype._assertOnlyOneComponent = function(directives, sourceSpan) { + var componentTypeNames = this._findComponentDirectiveNames(directives); + if (componentTypeNames.length > 1) { + this._reportError("More than one component: " + componentTypeNames.join(','), sourceSpan); + } + }; + TemplateParseVisitor.prototype._assertNoComponentsNorElementBindingsOnTemplate = function(directives, elementProps, sourceSpan) { + var _this = this; + var componentTypeNames = this._findComponentDirectiveNames(directives); + if (componentTypeNames.length > 0) { + this._reportError("Components on an embedded template: " + componentTypeNames.join(','), sourceSpan); + } + elementProps.forEach(function(prop) { + _this._reportError("Property binding " + prop.name + " not used by any directive on an embedded template", sourceSpan); + }); + }; + TemplateParseVisitor.prototype._assertAllEventsPublishedByDirectives = function(directives, events) { + var _this = this; + var allDirectiveEvents = new Set(); + directives.forEach(function(directive) { + collection_1.StringMapWrapper.forEach(directive.directive.outputs, function(eventName, _) { + allDirectiveEvents.add(eventName); + }); + }); + events.forEach(function(event) { + if (lang_1.isPresent(event.target) || !collection_1.SetWrapper.has(allDirectiveEvents, event.name)) { + _this._reportError("Event binding " + event.fullName + " not emitted by any directive on an embedded template", event.sourceSpan); + } + }); + }; + return TemplateParseVisitor; + })(); + var NonBindableVisitor = (function() { + function NonBindableVisitor() {} + NonBindableVisitor.prototype.visitElement = function(ast, component) { + var preparsedElement = template_preparser_1.preparseElement(ast); + if (preparsedElement.type === template_preparser_1.PreparsedElementType.SCRIPT || preparsedElement.type === template_preparser_1.PreparsedElementType.STYLE || preparsedElement.type === template_preparser_1.PreparsedElementType.STYLESHEET) { + return null; + } + var attrNameAndValues = ast.attrs.map(function(attrAst) { + return [attrAst.name, attrAst.value]; + }); + var selector = createElementCssSelector(ast.name, attrNameAndValues); + var ngContentIndex = component.findNgContentIndex(selector); + var children = html_ast_1.htmlVisitAll(this, ast.children, EMPTY_COMPONENT); + return new template_ast_1.ElementAst(ast.name, html_ast_1.htmlVisitAll(this, ast.attrs), [], [], [], [], children, ngContentIndex, ast.sourceSpan); + }; + NonBindableVisitor.prototype.visitAttr = function(ast, context) { + return new template_ast_1.AttrAst(ast.name, ast.value, ast.sourceSpan); + }; + NonBindableVisitor.prototype.visitText = function(ast, component) { + var ngContentIndex = component.findNgContentIndex(TEXT_CSS_SELECTOR); + return new template_ast_1.TextAst(ast.value, ngContentIndex, ast.sourceSpan); + }; + return NonBindableVisitor; + })(); + var BoundElementOrDirectiveProperty = (function() { + function BoundElementOrDirectiveProperty(name, expression, isLiteral, sourceSpan) { + this.name = name; + this.expression = expression; + this.isLiteral = isLiteral; + this.sourceSpan = sourceSpan; + } + return BoundElementOrDirectiveProperty; + })(); + function splitClasses(classAttrValue) { + return lang_1.StringWrapper.split(classAttrValue.trim(), /\s+/g); + } + exports.splitClasses = splitClasses; + var Component = (function() { + function Component(ngContentIndexMatcher, wildcardNgContentIndex) { + this.ngContentIndexMatcher = ngContentIndexMatcher; + this.wildcardNgContentIndex = wildcardNgContentIndex; + } + Component.create = function(directives) { + if (directives.length === 0 || !directives[0].directive.isComponent) { + return EMPTY_COMPONENT; + } + var matcher = new selector_1.SelectorMatcher(); + var ngContentSelectors = directives[0].directive.template.ngContentSelectors; + var wildcardNgContentIndex = null; + for (var i = 0; i < ngContentSelectors.length; i++) { + var selector = ngContentSelectors[i]; + if (lang_1.StringWrapper.equals(selector, '*')) { + wildcardNgContentIndex = i; + } else { + matcher.addSelectables(selector_1.CssSelector.parse(ngContentSelectors[i]), i); + } + } + return new Component(matcher, wildcardNgContentIndex); + }; + Component.prototype.findNgContentIndex = function(selector) { + var ngContentIndices = []; + this.ngContentIndexMatcher.match(selector, function(selector, ngContentIndex) { + ngContentIndices.push(ngContentIndex); + }); + collection_1.ListWrapper.sort(ngContentIndices); + if (lang_1.isPresent(this.wildcardNgContentIndex)) { + ngContentIndices.push(this.wildcardNgContentIndex); + } + return ngContentIndices.length > 0 ? ngContentIndices[0] : null; + }; + return Component; + })(); + function createElementCssSelector(elementName, matchableAttrs) { + var cssSelector = new selector_1.CssSelector(); + var elNameNoNs = html_tags_1.splitNsName(elementName)[1]; + cssSelector.setElement(elNameNoNs); + for (var i = 0; i < matchableAttrs.length; i++) { + var attrName = matchableAttrs[i][0]; + var attrNameNoNs = html_tags_1.splitNsName(attrName)[1]; + var attrValue = matchableAttrs[i][1]; + cssSelector.addAttribute(attrNameNoNs, attrValue); + if (attrName.toLowerCase() == CLASS_ATTR) { + var classes = splitClasses(attrValue); + classes.forEach(function(className) { + return cssSelector.addClassName(className); + }); + } + } + return cssSelector; + } + var EMPTY_COMPONENT = new Component(new selector_1.SelectorMatcher(), null); + var NON_BINDABLE_VISITOR = new NonBindableVisitor(); + global.define = __define; + return module.exports; +}); + +System.register("angular2/common", ["angular2/src/common/pipes", "angular2/src/common/directives", "angular2/src/common/forms", "angular2/src/common/common_directives"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function __export(m) { + for (var p in m) + if (!exports.hasOwnProperty(p)) + exports[p] = m[p]; + } + __export(require("angular2/src/common/pipes")); + __export(require("angular2/src/common/directives")); + __export(require("angular2/src/common/forms")); + __export(require("angular2/src/common/common_directives")); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/template_compiler", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/facade/async", "angular2/src/core/linker/template_commands", "angular2/src/compiler/directive_metadata", "angular2/src/core/di", "angular2/src/compiler/source_module", "angular2/src/compiler/change_detector_compiler", "angular2/src/compiler/style_compiler", "angular2/src/compiler/command_compiler", "angular2/src/compiler/template_parser", "angular2/src/compiler/template_normalizer", "angular2/src/compiler/runtime_metadata", "angular2/src/compiler/command_compiler", "angular2/src/compiler/util"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var async_1 = require("angular2/src/facade/async"); + var template_commands_1 = require("angular2/src/core/linker/template_commands"); + var directive_metadata_1 = require("angular2/src/compiler/directive_metadata"); + var di_1 = require("angular2/src/core/di"); + var source_module_1 = require("angular2/src/compiler/source_module"); + var change_detector_compiler_1 = require("angular2/src/compiler/change_detector_compiler"); + var style_compiler_1 = require("angular2/src/compiler/style_compiler"); + var command_compiler_1 = require("angular2/src/compiler/command_compiler"); + var template_parser_1 = require("angular2/src/compiler/template_parser"); + var template_normalizer_1 = require("angular2/src/compiler/template_normalizer"); + var runtime_metadata_1 = require("angular2/src/compiler/runtime_metadata"); + var command_compiler_2 = require("angular2/src/compiler/command_compiler"); + var util_1 = require("angular2/src/compiler/util"); + var TemplateCompiler = (function() { + function TemplateCompiler(_runtimeMetadataResolver, _templateNormalizer, _templateParser, _styleCompiler, _commandCompiler, _cdCompiler) { + this._runtimeMetadataResolver = _runtimeMetadataResolver; + this._templateNormalizer = _templateNormalizer; + this._templateParser = _templateParser; + this._styleCompiler = _styleCompiler; + this._commandCompiler = _commandCompiler; + this._cdCompiler = _cdCompiler; + this._hostCacheKeys = new Map(); + this._compiledTemplateCache = new Map(); + this._compiledTemplateDone = new Map(); + this._nextTemplateId = 0; + } + TemplateCompiler.prototype.normalizeDirectiveMetadata = function(directive) { + if (!directive.isComponent) { + return async_1.PromiseWrapper.resolve(directive); + } + return this._templateNormalizer.normalizeTemplate(directive.type, directive.template).then(function(normalizedTemplate) { + return new directive_metadata_1.CompileDirectiveMetadata({ + type: directive.type, + isComponent: directive.isComponent, + dynamicLoadable: directive.dynamicLoadable, + selector: directive.selector, + exportAs: directive.exportAs, + changeDetection: directive.changeDetection, + inputs: directive.inputs, + outputs: directive.outputs, + hostListeners: directive.hostListeners, + hostProperties: directive.hostProperties, + hostAttributes: directive.hostAttributes, + lifecycleHooks: directive.lifecycleHooks, + template: normalizedTemplate + }); + }); + }; + TemplateCompiler.prototype.compileHostComponentRuntime = function(type) { + var hostCacheKey = this._hostCacheKeys.get(type); + if (lang_1.isBlank(hostCacheKey)) { + hostCacheKey = new Object(); + this._hostCacheKeys.set(type, hostCacheKey); + var compMeta = this._runtimeMetadataResolver.getMetadata(type); + assertComponent(compMeta); + var hostMeta = directive_metadata_1.createHostComponentMeta(compMeta.type, compMeta.selector); + this._compileComponentRuntime(hostCacheKey, hostMeta, [compMeta], new Set()); + } + return this._compiledTemplateDone.get(hostCacheKey).then(function(compiledTemplate) { + return new template_commands_1.CompiledHostTemplate(compiledTemplate); + }); + }; + TemplateCompiler.prototype.clearCache = function() { + this._hostCacheKeys.clear(); + this._styleCompiler.clearCache(); + this._compiledTemplateCache.clear(); + this._compiledTemplateDone.clear(); + }; + TemplateCompiler.prototype._compileComponentRuntime = function(cacheKey, compMeta, viewDirectives, compilingComponentCacheKeys) { + var _this = this; + var uniqViewDirectives = removeDuplicates(viewDirectives); + var compiledTemplate = this._compiledTemplateCache.get(cacheKey); + var done = this._compiledTemplateDone.get(cacheKey); + if (lang_1.isBlank(compiledTemplate)) { + var styles = []; + var changeDetectorFactory; + var commands = []; + var templateId = lang_1.stringify(compMeta.type.runtime) + "Template" + this._nextTemplateId++; + compiledTemplate = new template_commands_1.CompiledComponentTemplate(templateId, function(dispatcher) { + return changeDetectorFactory(dispatcher); + }, commands, styles); + this._compiledTemplateCache.set(cacheKey, compiledTemplate); + compilingComponentCacheKeys.add(cacheKey); + done = async_1.PromiseWrapper.all([this._styleCompiler.compileComponentRuntime(compMeta.template)].concat(uniqViewDirectives.map(function(dirMeta) { + return _this.normalizeDirectiveMetadata(dirMeta); + }))).then(function(stylesAndNormalizedViewDirMetas) { + var childPromises = []; + var normalizedViewDirMetas = stylesAndNormalizedViewDirMetas.slice(1); + var parsedTemplate = _this._templateParser.parse(compMeta.template.template, normalizedViewDirMetas, compMeta.type.name); + var changeDetectorFactories = _this._cdCompiler.compileComponentRuntime(compMeta.type, compMeta.changeDetection, parsedTemplate); + changeDetectorFactory = changeDetectorFactories[0]; + var tmpStyles = stylesAndNormalizedViewDirMetas[0]; + tmpStyles.forEach(function(style) { + return styles.push(style); + }); + var tmpCommands = _this._compileCommandsRuntime(compMeta, parsedTemplate, changeDetectorFactories, compilingComponentCacheKeys, childPromises); + tmpCommands.forEach(function(cmd) { + return commands.push(cmd); + }); + return async_1.PromiseWrapper.all(childPromises); + }).then(function(_) { + collection_1.SetWrapper.delete(compilingComponentCacheKeys, cacheKey); + return compiledTemplate; + }); + this._compiledTemplateDone.set(cacheKey, done); + } + return compiledTemplate; + }; + TemplateCompiler.prototype._compileCommandsRuntime = function(compMeta, parsedTemplate, changeDetectorFactories, compilingComponentCacheKeys, childPromises) { + var _this = this; + var cmds = this._commandCompiler.compileComponentRuntime(compMeta, parsedTemplate, changeDetectorFactories, function(childComponentDir) { + var childCacheKey = childComponentDir.type.runtime; + var childViewDirectives = _this._runtimeMetadataResolver.getViewDirectivesMetadata(childComponentDir.type.runtime); + var childIsRecursive = collection_1.SetWrapper.has(compilingComponentCacheKeys, childCacheKey); + var childTemplate = _this._compileComponentRuntime(childCacheKey, childComponentDir, childViewDirectives, compilingComponentCacheKeys); + if (!childIsRecursive) { + childPromises.push(_this._compiledTemplateDone.get(childCacheKey)); + } + return function() { + return childTemplate; + }; + }); + cmds.forEach(function(cmd) { + if (cmd instanceof template_commands_1.BeginComponentCmd) { + cmd.templateGetter(); + } + }); + return cmds; + }; + TemplateCompiler.prototype.compileTemplatesCodeGen = function(components) { + var _this = this; + if (components.length === 0) { + throw new exceptions_1.BaseException('No components given'); + } + var declarations = []; + var templateArguments = []; + var componentMetas = []; + components.forEach(function(componentWithDirs) { + var compMeta = componentWithDirs.component; + assertComponent(compMeta); + componentMetas.push(compMeta); + _this._processTemplateCodeGen(compMeta, componentWithDirs.directives, declarations, templateArguments); + if (compMeta.dynamicLoadable) { + var hostMeta = directive_metadata_1.createHostComponentMeta(compMeta.type, compMeta.selector); + componentMetas.push(hostMeta); + _this._processTemplateCodeGen(hostMeta, [compMeta], declarations, templateArguments); + } + }); + collection_1.ListWrapper.forEachWithIndex(componentMetas, function(compMeta, index) { + var templateId = compMeta.type.moduleUrl + "|" + compMeta.type.name; + var constructionKeyword = lang_1.IS_DART ? 'const' : 'new'; + var compiledTemplateExpr = constructionKeyword + " " + command_compiler_2.TEMPLATE_COMMANDS_MODULE_REF + "CompiledComponentTemplate('" + templateId + "'," + templateArguments[index].join(',') + ")"; + var variableValueExpr; + if (compMeta.type.isHost) { + variableValueExpr = constructionKeyword + " " + command_compiler_2.TEMPLATE_COMMANDS_MODULE_REF + "CompiledHostTemplate(" + compiledTemplateExpr + ")"; + } else { + variableValueExpr = compiledTemplateExpr; + } + var varName = templateVariableName(compMeta.type); + declarations.push("" + util_1.codeGenExportVariable(varName) + variableValueExpr + ";"); + declarations.push(util_1.codeGenValueFn([], varName, templateGetterName(compMeta.type)) + ";"); + }); + var moduleUrl = components[0].component.type.moduleUrl; + return new source_module_1.SourceModule("" + templateModuleUrl(moduleUrl), declarations.join('\n')); + }; + TemplateCompiler.prototype.compileStylesheetCodeGen = function(stylesheetUrl, cssText) { + return this._styleCompiler.compileStylesheetCodeGen(stylesheetUrl, cssText); + }; + TemplateCompiler.prototype._processTemplateCodeGen = function(compMeta, directives, targetDeclarations, targetTemplateArguments) { + var uniqueDirectives = removeDuplicates(directives); + var styleExpr = this._styleCompiler.compileComponentCodeGen(compMeta.template); + var parsedTemplate = this._templateParser.parse(compMeta.template.template, uniqueDirectives, compMeta.type.name); + var changeDetectorsExprs = this._cdCompiler.compileComponentCodeGen(compMeta.type, compMeta.changeDetection, parsedTemplate); + var commandsExpr = this._commandCompiler.compileComponentCodeGen(compMeta, parsedTemplate, changeDetectorsExprs.expressions, codeGenComponentTemplateFactory); + addAll(styleExpr.declarations, targetDeclarations); + addAll(changeDetectorsExprs.declarations, targetDeclarations); + addAll(commandsExpr.declarations, targetDeclarations); + targetTemplateArguments.push([changeDetectorsExprs.expressions[0], commandsExpr.expression, styleExpr.expression]); + }; + TemplateCompiler = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [runtime_metadata_1.RuntimeMetadataResolver, template_normalizer_1.TemplateNormalizer, template_parser_1.TemplateParser, style_compiler_1.StyleCompiler, command_compiler_1.CommandCompiler, change_detector_compiler_1.ChangeDetectionCompiler])], TemplateCompiler); + return TemplateCompiler; + })(); + exports.TemplateCompiler = TemplateCompiler; + var NormalizedComponentWithViewDirectives = (function() { + function NormalizedComponentWithViewDirectives(component, directives) { + this.component = component; + this.directives = directives; + } + return NormalizedComponentWithViewDirectives; + })(); + exports.NormalizedComponentWithViewDirectives = NormalizedComponentWithViewDirectives; + function assertComponent(meta) { + if (!meta.isComponent) { + throw new exceptions_1.BaseException("Could not compile '" + meta.type.name + "' because it is not a component."); + } + } + function templateVariableName(type) { + return type.name + "Template"; + } + function templateGetterName(type) { + return templateVariableName(type) + "Getter"; + } + function templateModuleUrl(moduleUrl) { + var urlWithoutSuffix = moduleUrl.substring(0, moduleUrl.length - util_1.MODULE_SUFFIX.length); + return urlWithoutSuffix + ".template" + util_1.MODULE_SUFFIX; + } + function addAll(source, target) { + for (var i = 0; i < source.length; i++) { + target.push(source[i]); + } + } + function codeGenComponentTemplateFactory(nestedCompType) { + return "" + source_module_1.moduleRef(templateModuleUrl(nestedCompType.type.moduleUrl)) + templateGetterName(nestedCompType.type); + } + function removeDuplicates(items) { + var res = []; + items.forEach(function(item) { + var hasMatch = res.filter(function(r) { + return r.type.name == item.type.name && r.type.moduleUrl == item.type.moduleUrl && r.type.runtime == item.type.runtime; + }).length > 0; + if (!hasMatch) { + res.push(item); + } + }); + return res; + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/runtime_compiler", ["angular2/src/core/linker/compiler", "angular2/src/core/linker/proto_view_factory", "angular2/src/compiler/template_compiler", "angular2/src/core/di"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var compiler_1 = require("angular2/src/core/linker/compiler"); + var proto_view_factory_1 = require("angular2/src/core/linker/proto_view_factory"); + var template_compiler_1 = require("angular2/src/compiler/template_compiler"); + var di_1 = require("angular2/src/core/di"); + var RuntimeCompiler = (function(_super) { + __extends(RuntimeCompiler, _super); + function RuntimeCompiler() { + _super.apply(this, arguments); + } + return RuntimeCompiler; + })(compiler_1.Compiler); + exports.RuntimeCompiler = RuntimeCompiler; + var RuntimeCompiler_ = (function(_super) { + __extends(RuntimeCompiler_, _super); + function RuntimeCompiler_(_protoViewFactory, _templateCompiler) { + _super.call(this, _protoViewFactory); + this._templateCompiler = _templateCompiler; + } + RuntimeCompiler_.prototype.compileInHost = function(componentType) { + var _this = this; + return this._templateCompiler.compileHostComponentRuntime(componentType).then(function(compiledHostTemplate) { + return compiler_1.internalCreateProtoView(_this, compiledHostTemplate); + }); + }; + RuntimeCompiler_.prototype.clearCache = function() { + _super.prototype.clearCache.call(this); + this._templateCompiler.clearCache(); + }; + RuntimeCompiler_ = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [proto_view_factory_1.ProtoViewFactory, template_compiler_1.TemplateCompiler])], RuntimeCompiler_); + return RuntimeCompiler_; + })(compiler_1.Compiler_); + exports.RuntimeCompiler_ = RuntimeCompiler_; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/compiler", ["angular2/src/compiler/runtime_compiler", "angular2/src/compiler/template_compiler", "angular2/src/compiler/directive_metadata", "angular2/src/compiler/source_module", "angular2/src/core/platform_directives_and_pipes", "angular2/src/compiler/template_ast", "angular2/src/compiler/template_parser", "angular2/src/facade/lang", "angular2/src/core/di", "angular2/src/compiler/template_parser", "angular2/src/compiler/html_parser", "angular2/src/compiler/template_normalizer", "angular2/src/compiler/runtime_metadata", "angular2/src/compiler/change_detector_compiler", "angular2/src/compiler/style_compiler", "angular2/src/compiler/command_compiler", "angular2/src/compiler/template_compiler", "angular2/src/core/change_detection/change_detection", "angular2/src/core/linker/compiler", "angular2/src/compiler/runtime_compiler", "angular2/src/compiler/schema/element_schema_registry", "angular2/src/compiler/schema/dom_element_schema_registry", "angular2/src/compiler/url_resolver", "angular2/src/core/change_detection/change_detection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function __export(m) { + for (var p in m) + if (!exports.hasOwnProperty(p)) + exports[p] = m[p]; + } + var runtime_compiler_1 = require("angular2/src/compiler/runtime_compiler"); + var template_compiler_1 = require("angular2/src/compiler/template_compiler"); + exports.TemplateCompiler = template_compiler_1.TemplateCompiler; + var directive_metadata_1 = require("angular2/src/compiler/directive_metadata"); + exports.CompileDirectiveMetadata = directive_metadata_1.CompileDirectiveMetadata; + exports.CompileTypeMetadata = directive_metadata_1.CompileTypeMetadata; + exports.CompileTemplateMetadata = directive_metadata_1.CompileTemplateMetadata; + var source_module_1 = require("angular2/src/compiler/source_module"); + exports.SourceModule = source_module_1.SourceModule; + exports.SourceWithImports = source_module_1.SourceWithImports; + var platform_directives_and_pipes_1 = require("angular2/src/core/platform_directives_and_pipes"); + exports.PLATFORM_DIRECTIVES = platform_directives_and_pipes_1.PLATFORM_DIRECTIVES; + exports.PLATFORM_PIPES = platform_directives_and_pipes_1.PLATFORM_PIPES; + __export(require("angular2/src/compiler/template_ast")); + var template_parser_1 = require("angular2/src/compiler/template_parser"); + exports.TEMPLATE_TRANSFORMS = template_parser_1.TEMPLATE_TRANSFORMS; + var lang_1 = require("angular2/src/facade/lang"); + var di_1 = require("angular2/src/core/di"); + var template_parser_2 = require("angular2/src/compiler/template_parser"); + var html_parser_1 = require("angular2/src/compiler/html_parser"); + var template_normalizer_1 = require("angular2/src/compiler/template_normalizer"); + var runtime_metadata_1 = require("angular2/src/compiler/runtime_metadata"); + var change_detector_compiler_1 = require("angular2/src/compiler/change_detector_compiler"); + var style_compiler_1 = require("angular2/src/compiler/style_compiler"); + var command_compiler_1 = require("angular2/src/compiler/command_compiler"); + var template_compiler_2 = require("angular2/src/compiler/template_compiler"); + var change_detection_1 = require("angular2/src/core/change_detection/change_detection"); + var compiler_1 = require("angular2/src/core/linker/compiler"); + var runtime_compiler_2 = require("angular2/src/compiler/runtime_compiler"); + var element_schema_registry_1 = require("angular2/src/compiler/schema/element_schema_registry"); + var dom_element_schema_registry_1 = require("angular2/src/compiler/schema/dom_element_schema_registry"); + var url_resolver_1 = require("angular2/src/compiler/url_resolver"); + var change_detection_2 = require("angular2/src/core/change_detection/change_detection"); + function _createChangeDetectorGenConfig() { + return new change_detection_1.ChangeDetectorGenConfig(lang_1.assertionsEnabled(), false, true); + } + exports.COMPILER_PROVIDERS = lang_1.CONST_EXPR([change_detection_2.Lexer, change_detection_2.Parser, html_parser_1.HtmlParser, template_parser_2.TemplateParser, template_normalizer_1.TemplateNormalizer, runtime_metadata_1.RuntimeMetadataResolver, url_resolver_1.DEFAULT_PACKAGE_URL_PROVIDER, style_compiler_1.StyleCompiler, command_compiler_1.CommandCompiler, change_detector_compiler_1.ChangeDetectionCompiler, new di_1.Provider(change_detection_1.ChangeDetectorGenConfig, { + useFactory: _createChangeDetectorGenConfig, + deps: [] + }), template_compiler_2.TemplateCompiler, new di_1.Provider(runtime_compiler_2.RuntimeCompiler, {useClass: runtime_compiler_1.RuntimeCompiler_}), new di_1.Provider(compiler_1.Compiler, {useExisting: runtime_compiler_2.RuntimeCompiler}), dom_element_schema_registry_1.DomElementSchemaRegistry, new di_1.Provider(element_schema_registry_1.ElementSchemaRegistry, {useExisting: dom_element_schema_registry_1.DomElementSchemaRegistry}), url_resolver_1.UrlResolver]); + global.define = __define; + return module.exports; +}); + +System.register("angular2/compiler", ["angular2/src/compiler/url_resolver", "angular2/src/compiler/xhr", "angular2/src/compiler/compiler"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function __export(m) { + for (var p in m) + if (!exports.hasOwnProperty(p)) + exports[p] = m[p]; + } + __export(require("angular2/src/compiler/url_resolver")); + __export(require("angular2/src/compiler/xhr")); + __export(require("angular2/src/compiler/compiler")); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/browser_common", ["angular2/src/facade/lang", "angular2/src/core/di", "angular2/core", "angular2/common", "angular2/src/core/testability/testability", "angular2/src/platform/dom/dom_adapter", "angular2/src/platform/dom/events/dom_events", "angular2/src/platform/dom/events/key_events", "angular2/src/platform/dom/events/hammer_gestures", "angular2/src/platform/dom/dom_tokens", "angular2/src/platform/dom/dom_renderer", "angular2/src/platform/dom/shared_styles_host", "angular2/src/platform/dom/shared_styles_host", "angular2/src/animate/browser_details", "angular2/src/animate/animation_builder", "angular2/src/platform/browser/browser_adapter", "angular2/src/platform/browser/testability", "angular2/src/core/profile/wtf_init", "angular2/src/platform/dom/events/event_manager", "angular2/src/platform/dom/dom_tokens", "angular2/src/platform/browser/title", "angular2/platform/common_dom", "angular2/src/platform/browser/browser_adapter", "angular2/src/platform/browser/tools/tools"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var di_1 = require("angular2/src/core/di"); + var core_1 = require("angular2/core"); + var common_1 = require("angular2/common"); + var testability_1 = require("angular2/src/core/testability/testability"); + var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); + var dom_events_1 = require("angular2/src/platform/dom/events/dom_events"); + var key_events_1 = require("angular2/src/platform/dom/events/key_events"); + var hammer_gestures_1 = require("angular2/src/platform/dom/events/hammer_gestures"); + var dom_tokens_1 = require("angular2/src/platform/dom/dom_tokens"); + var dom_renderer_1 = require("angular2/src/platform/dom/dom_renderer"); + var shared_styles_host_1 = require("angular2/src/platform/dom/shared_styles_host"); + var shared_styles_host_2 = require("angular2/src/platform/dom/shared_styles_host"); + var browser_details_1 = require("angular2/src/animate/browser_details"); + var animation_builder_1 = require("angular2/src/animate/animation_builder"); + var browser_adapter_1 = require("angular2/src/platform/browser/browser_adapter"); + var testability_2 = require("angular2/src/platform/browser/testability"); + var wtf_init_1 = require("angular2/src/core/profile/wtf_init"); + var event_manager_1 = require("angular2/src/platform/dom/events/event_manager"); + var dom_tokens_2 = require("angular2/src/platform/dom/dom_tokens"); + exports.DOCUMENT = dom_tokens_2.DOCUMENT; + var title_1 = require("angular2/src/platform/browser/title"); + exports.Title = title_1.Title; + var common_dom_1 = require("angular2/platform/common_dom"); + exports.DebugElementViewListener = common_dom_1.DebugElementViewListener; + exports.ELEMENT_PROBE_PROVIDERS = common_dom_1.ELEMENT_PROBE_PROVIDERS; + exports.ELEMENT_PROBE_BINDINGS = common_dom_1.ELEMENT_PROBE_BINDINGS; + exports.inspectNativeElement = common_dom_1.inspectNativeElement; + exports.By = common_dom_1.By; + var browser_adapter_2 = require("angular2/src/platform/browser/browser_adapter"); + exports.BrowserDomAdapter = browser_adapter_2.BrowserDomAdapter; + var tools_1 = require("angular2/src/platform/browser/tools/tools"); + exports.enableDebugTools = tools_1.enableDebugTools; + exports.disableDebugTools = tools_1.disableDebugTools; + exports.BROWSER_PROVIDERS = lang_1.CONST_EXPR([core_1.PLATFORM_COMMON_PROVIDERS, new di_1.Provider(core_1.PLATFORM_INITIALIZER, { + useValue: initDomAdapter, + multi: true + })]); + function _exceptionHandler() { + return new core_1.ExceptionHandler(dom_adapter_1.DOM, !lang_1.IS_DART); + } + function _document() { + return dom_adapter_1.DOM.defaultDoc(); + } + exports.BROWSER_APP_COMMON_PROVIDERS = lang_1.CONST_EXPR([core_1.APPLICATION_COMMON_PROVIDERS, common_1.FORM_PROVIDERS, new di_1.Provider(core_1.PLATFORM_PIPES, { + useValue: common_1.COMMON_PIPES, + multi: true + }), new di_1.Provider(core_1.PLATFORM_DIRECTIVES, { + useValue: common_1.COMMON_DIRECTIVES, + multi: true + }), new di_1.Provider(core_1.ExceptionHandler, { + useFactory: _exceptionHandler, + deps: [] + }), new di_1.Provider(dom_tokens_1.DOCUMENT, { + useFactory: _document, + deps: [] + }), new di_1.Provider(event_manager_1.EVENT_MANAGER_PLUGINS, { + useClass: dom_events_1.DomEventsPlugin, + multi: true + }), new di_1.Provider(event_manager_1.EVENT_MANAGER_PLUGINS, { + useClass: key_events_1.KeyEventsPlugin, + multi: true + }), new di_1.Provider(event_manager_1.EVENT_MANAGER_PLUGINS, { + useClass: hammer_gestures_1.HammerGesturesPlugin, + multi: true + }), new di_1.Provider(dom_renderer_1.DomRenderer, {useClass: dom_renderer_1.DomRenderer_}), new di_1.Provider(core_1.Renderer, {useExisting: dom_renderer_1.DomRenderer}), new di_1.Provider(shared_styles_host_2.SharedStylesHost, {useExisting: shared_styles_host_1.DomSharedStylesHost}), shared_styles_host_1.DomSharedStylesHost, testability_1.Testability, browser_details_1.BrowserDetails, animation_builder_1.AnimationBuilder, event_manager_1.EventManager]); + function initDomAdapter() { + browser_adapter_1.BrowserDomAdapter.makeCurrent(); + wtf_init_1.wtfInit(); + testability_2.BrowserGetTestability.init(); + } + exports.initDomAdapter = initDomAdapter; + global.define = __define; + return module.exports; +}); + +System.register("angular2/platform/browser", ["angular2/src/core/angular_entrypoint", "angular2/src/platform/browser_common", "angular2/src/facade/lang", "angular2/src/platform/browser_common", "angular2/compiler", "angular2/core", "angular2/src/core/reflection/reflection_capabilities", "angular2/src/platform/browser/xhr_impl", "angular2/compiler", "angular2/src/core/di"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var angular_entrypoint_1 = require("angular2/src/core/angular_entrypoint"); + exports.AngularEntrypoint = angular_entrypoint_1.AngularEntrypoint; + var browser_common_1 = require("angular2/src/platform/browser_common"); + exports.BROWSER_PROVIDERS = browser_common_1.BROWSER_PROVIDERS; + exports.ELEMENT_PROBE_BINDINGS = browser_common_1.ELEMENT_PROBE_BINDINGS; + exports.ELEMENT_PROBE_PROVIDERS = browser_common_1.ELEMENT_PROBE_PROVIDERS; + exports.inspectNativeElement = browser_common_1.inspectNativeElement; + exports.BrowserDomAdapter = browser_common_1.BrowserDomAdapter; + exports.By = browser_common_1.By; + exports.Title = browser_common_1.Title; + exports.DOCUMENT = browser_common_1.DOCUMENT; + exports.enableDebugTools = browser_common_1.enableDebugTools; + exports.disableDebugTools = browser_common_1.disableDebugTools; + var lang_1 = require("angular2/src/facade/lang"); + var browser_common_2 = require("angular2/src/platform/browser_common"); + var compiler_1 = require("angular2/compiler"); + var core_1 = require("angular2/core"); + var reflection_capabilities_1 = require("angular2/src/core/reflection/reflection_capabilities"); + var xhr_impl_1 = require("angular2/src/platform/browser/xhr_impl"); + var compiler_2 = require("angular2/compiler"); + var di_1 = require("angular2/src/core/di"); + exports.BROWSER_APP_PROVIDERS = lang_1.CONST_EXPR([browser_common_2.BROWSER_APP_COMMON_PROVIDERS, compiler_1.COMPILER_PROVIDERS, new di_1.Provider(compiler_2.XHR, {useClass: xhr_impl_1.XHRImpl})]); + function bootstrap(appComponentType, customProviders) { + core_1.reflector.reflectionCapabilities = new reflection_capabilities_1.ReflectionCapabilities(); + var appProviders = lang_1.isPresent(customProviders) ? [exports.BROWSER_APP_PROVIDERS, customProviders] : exports.BROWSER_APP_PROVIDERS; + return core_1.platform(browser_common_2.BROWSER_PROVIDERS).application(appProviders).bootstrap(appComponentType); + } + exports.bootstrap = bootstrap; + global.define = __define; + return module.exports; +}); + +System.register("angular2/instrumentation", ["angular2/src/core/profile/profile"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var profile_1 = require("angular2/src/core/profile/profile"); + exports.wtfCreateScope = profile_1.wtfCreateScope; + exports.wtfLeave = profile_1.wtfLeave; + exports.wtfStartTimeRange = profile_1.wtfStartTimeRange; + exports.wtfEndTimeRange = profile_1.wtfEndTimeRange; + global.define = __define; + return module.exports; +}); + +//# sourceMappingURLDisabled=angular2.dev.js.map \ No newline at end of file diff --git a/testapp/ng2/lib/angular2.0.0-beta.0/bundles/router.js b/testapp/ng2/lib/angular2.0.0-beta.0/bundles/router.js new file mode 100644 index 000000000..36a98998e --- /dev/null +++ b/testapp/ng2/lib/angular2.0.0-beta.0/bundles/router.js @@ -0,0 +1,2972 @@ +"format register"; +System.register("angular2/src/router/router_link_transform", ["angular2/compiler", "angular2/src/core/change_detection/parser/ast", "angular2/src/facade/exceptions", "angular2/core", "angular2/src/core/change_detection/parser/parser"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var compiler_1 = require("angular2/compiler"); + var ast_1 = require("angular2/src/core/change_detection/parser/ast"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var core_1 = require("angular2/core"); + var parser_1 = require("angular2/src/core/change_detection/parser/parser"); + var FixedPart = (function() { + function FixedPart(value) { + this.value = value; + } + return FixedPart; + })(); + var AuxiliaryStart = (function() { + function AuxiliaryStart() {} + return AuxiliaryStart; + })(); + var AuxiliaryEnd = (function() { + function AuxiliaryEnd() {} + return AuxiliaryEnd; + })(); + var Params = (function() { + function Params(ast) { + this.ast = ast; + } + return Params; + })(); + var RouterLinkLexer = (function() { + function RouterLinkLexer(parser, exp) { + this.parser = parser; + this.exp = exp; + this.index = 0; + } + RouterLinkLexer.prototype.tokenize = function() { + var tokens = []; + while (this.index < this.exp.length) { + tokens.push(this._parseToken()); + } + return tokens; + }; + RouterLinkLexer.prototype._parseToken = function() { + var c = this.exp[this.index]; + if (c == '[') { + this.index++; + return new AuxiliaryStart(); + } else if (c == ']') { + this.index++; + return new AuxiliaryEnd(); + } else if (c == '(') { + return this._parseParams(); + } else if (c == '/' && this.index !== 0) { + this.index++; + return this._parseFixedPart(); + } else { + return this._parseFixedPart(); + } + }; + RouterLinkLexer.prototype._parseParams = function() { + var start = this.index; + for (; this.index < this.exp.length; ++this.index) { + var c = this.exp[this.index]; + if (c == ')') { + var paramsContent = this.exp.substring(start + 1, this.index); + this.index++; + return new Params(this.parser.parseBinding("{" + paramsContent + "}", null).ast); + } + } + throw new exceptions_1.BaseException("Cannot find ')'"); + }; + RouterLinkLexer.prototype._parseFixedPart = function() { + var start = this.index; + var sawNonSlash = false; + for (; this.index < this.exp.length; ++this.index) { + var c = this.exp[this.index]; + if (c == '(' || c == '[' || c == ']' || (c == '/' && sawNonSlash)) { + break; + } + if (c != '.' && c != '/') { + sawNonSlash = true; + } + } + var fixed = this.exp.substring(start, this.index); + if (start === this.index || !sawNonSlash || fixed.startsWith('//')) { + throw new exceptions_1.BaseException("Invalid router link"); + } + return new FixedPart(fixed); + }; + return RouterLinkLexer; + })(); + var RouterLinkAstGenerator = (function() { + function RouterLinkAstGenerator(tokens) { + this.tokens = tokens; + this.index = 0; + } + RouterLinkAstGenerator.prototype.generate = function() { + return this._genAuxiliary(); + }; + RouterLinkAstGenerator.prototype._genAuxiliary = function() { + var arr = []; + for (; this.index < this.tokens.length; this.index++) { + var r = this.tokens[this.index]; + if (r instanceof FixedPart) { + arr.push(new ast_1.LiteralPrimitive(r.value)); + } else if (r instanceof Params) { + arr.push(r.ast); + } else if (r instanceof AuxiliaryEnd) { + break; + } else if (r instanceof AuxiliaryStart) { + this.index++; + arr.push(this._genAuxiliary()); + } + } + return new ast_1.LiteralArray(arr); + }; + return RouterLinkAstGenerator; + })(); + var RouterLinkAstTransformer = (function(_super) { + __extends(RouterLinkAstTransformer, _super); + function RouterLinkAstTransformer(parser) { + _super.call(this); + this.parser = parser; + } + RouterLinkAstTransformer.prototype.visitQuote = function(ast) { + if (ast.prefix == "route") { + return parseRouterLinkExpression(this.parser, ast.uninterpretedExpression); + } else { + return _super.prototype.visitQuote.call(this, ast); + } + }; + return RouterLinkAstTransformer; + })(ast_1.AstTransformer); + function parseRouterLinkExpression(parser, exp) { + var tokens = new RouterLinkLexer(parser, exp.trim()).tokenize(); + return new RouterLinkAstGenerator(tokens).generate(); + } + exports.parseRouterLinkExpression = parseRouterLinkExpression; + var RouterLinkTransform = (function() { + function RouterLinkTransform(parser) { + this.astTransformer = new RouterLinkAstTransformer(parser); + } + RouterLinkTransform.prototype.visitNgContent = function(ast, context) { + return ast; + }; + RouterLinkTransform.prototype.visitEmbeddedTemplate = function(ast, context) { + return ast; + }; + RouterLinkTransform.prototype.visitElement = function(ast, context) { + var _this = this; + var updatedChildren = ast.children.map(function(c) { + return c.visit(_this, context); + }); + var updatedInputs = ast.inputs.map(function(c) { + return c.visit(_this, context); + }); + var updatedDirectives = ast.directives.map(function(c) { + return c.visit(_this, context); + }); + return new compiler_1.ElementAst(ast.name, ast.attrs, updatedInputs, ast.outputs, ast.exportAsVars, updatedDirectives, updatedChildren, ast.ngContentIndex, ast.sourceSpan); + }; + RouterLinkTransform.prototype.visitVariable = function(ast, context) { + return ast; + }; + RouterLinkTransform.prototype.visitEvent = function(ast, context) { + return ast; + }; + RouterLinkTransform.prototype.visitElementProperty = function(ast, context) { + return ast; + }; + RouterLinkTransform.prototype.visitAttr = function(ast, context) { + return ast; + }; + RouterLinkTransform.prototype.visitBoundText = function(ast, context) { + return ast; + }; + RouterLinkTransform.prototype.visitText = function(ast, context) { + return ast; + }; + RouterLinkTransform.prototype.visitDirective = function(ast, context) { + var _this = this; + var updatedInputs = ast.inputs.map(function(c) { + return c.visit(_this, context); + }); + return new compiler_1.DirectiveAst(ast.directive, updatedInputs, ast.hostProperties, ast.hostEvents, ast.exportAsVars, ast.sourceSpan); + }; + RouterLinkTransform.prototype.visitDirectiveProperty = function(ast, context) { + var transformedValue = ast.value.visit(this.astTransformer); + return new compiler_1.BoundDirectivePropertyAst(ast.directiveName, ast.templateName, transformedValue, ast.sourceSpan); + }; + RouterLinkTransform = __decorate([core_1.Injectable(), __metadata('design:paramtypes', [parser_1.Parser])], RouterLinkTransform); + return RouterLinkTransform; + })(); + exports.RouterLinkTransform = RouterLinkTransform; + global.define = __define; + return module.exports; +}); + +System.register("angular2/router/router_link_dsl", ["angular2/compiler", "angular2/core", "angular2/src/router/router_link_transform", "angular2/src/facade/lang", "angular2/src/router/router_link_transform"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var compiler_1 = require("angular2/compiler"); + var core_1 = require("angular2/core"); + var router_link_transform_1 = require("angular2/src/router/router_link_transform"); + var lang_1 = require("angular2/src/facade/lang"); + var router_link_transform_2 = require("angular2/src/router/router_link_transform"); + exports.RouterLinkTransform = router_link_transform_2.RouterLinkTransform; + exports.ROUTER_LINK_DSL_PROVIDER = lang_1.CONST_EXPR(new core_1.Provider(compiler_1.TEMPLATE_TRANSFORMS, { + useClass: router_link_transform_1.RouterLinkTransform, + multi: true + })); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/route_config_impl", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var RouteConfig = (function() { + function RouteConfig(configs) { + this.configs = configs; + } + RouteConfig = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Array])], RouteConfig); + return RouteConfig; + })(); + exports.RouteConfig = RouteConfig; + var Route = (function() { + function Route(_a) { + var path = _a.path, + component = _a.component, + name = _a.name, + data = _a.data, + useAsDefault = _a.useAsDefault; + this.aux = null; + this.loader = null; + this.redirectTo = null; + this.path = path; + this.component = component; + this.name = name; + this.data = data; + this.useAsDefault = useAsDefault; + } + Route = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object])], Route); + return Route; + })(); + exports.Route = Route; + var AuxRoute = (function() { + function AuxRoute(_a) { + var path = _a.path, + component = _a.component, + name = _a.name; + this.data = null; + this.aux = null; + this.loader = null; + this.redirectTo = null; + this.useAsDefault = false; + this.path = path; + this.component = component; + this.name = name; + } + AuxRoute = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object])], AuxRoute); + return AuxRoute; + })(); + exports.AuxRoute = AuxRoute; + var AsyncRoute = (function() { + function AsyncRoute(_a) { + var path = _a.path, + loader = _a.loader, + name = _a.name, + data = _a.data, + useAsDefault = _a.useAsDefault; + this.aux = null; + this.path = path; + this.loader = loader; + this.name = name; + this.data = data; + this.useAsDefault = useAsDefault; + } + AsyncRoute = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object])], AsyncRoute); + return AsyncRoute; + })(); + exports.AsyncRoute = AsyncRoute; + var Redirect = (function() { + function Redirect(_a) { + var path = _a.path, + redirectTo = _a.redirectTo; + this.name = null; + this.loader = null; + this.data = null; + this.aux = null; + this.useAsDefault = false; + this.path = path; + this.redirectTo = redirectTo; + } + Redirect = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object])], Redirect); + return Redirect; + })(); + exports.Redirect = Redirect; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/instruction", ["angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/facade/async"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var async_1 = require("angular2/src/facade/async"); + var RouteParams = (function() { + function RouteParams(params) { + this.params = params; + } + RouteParams.prototype.get = function(param) { + return lang_1.normalizeBlank(collection_1.StringMapWrapper.get(this.params, param)); + }; + return RouteParams; + })(); + exports.RouteParams = RouteParams; + var RouteData = (function() { + function RouteData(data) { + if (data === void 0) { + data = lang_1.CONST_EXPR({}); + } + this.data = data; + } + RouteData.prototype.get = function(key) { + return lang_1.normalizeBlank(collection_1.StringMapWrapper.get(this.data, key)); + }; + return RouteData; + })(); + exports.RouteData = RouteData; + exports.BLANK_ROUTE_DATA = new RouteData(); + var Instruction = (function() { + function Instruction() { + this.auxInstruction = {}; + } + Object.defineProperty(Instruction.prototype, "urlPath", { + get: function() { + return this.component.urlPath; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Instruction.prototype, "urlParams", { + get: function() { + return this.component.urlParams; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Instruction.prototype, "specificity", { + get: function() { + var total = 0; + if (lang_1.isPresent(this.component)) { + total += this.component.specificity; + } + if (lang_1.isPresent(this.child)) { + total += this.child.specificity; + } + return total; + }, + enumerable: true, + configurable: true + }); + Instruction.prototype.toRootUrl = function() { + return this.toUrlPath() + this.toUrlQuery(); + }; + Instruction.prototype._toNonRootUrl = function() { + return this._stringifyPathMatrixAuxPrefixed() + (lang_1.isPresent(this.child) ? this.child._toNonRootUrl() : ''); + }; + Instruction.prototype.toUrlQuery = function() { + return this.urlParams.length > 0 ? ('?' + this.urlParams.join('&')) : ''; + }; + Instruction.prototype.replaceChild = function(child) { + return new ResolvedInstruction(this.component, child, this.auxInstruction); + }; + Instruction.prototype.toUrlPath = function() { + return this.urlPath + this._stringifyAux() + (lang_1.isPresent(this.child) ? this.child._toNonRootUrl() : ''); + }; + Instruction.prototype.toLinkUrl = function() { + return this.urlPath + this._stringifyAux() + (lang_1.isPresent(this.child) ? this.child._toLinkUrl() : ''); + }; + Instruction.prototype._toLinkUrl = function() { + return this._stringifyPathMatrixAuxPrefixed() + (lang_1.isPresent(this.child) ? this.child._toLinkUrl() : ''); + }; + Instruction.prototype._stringifyPathMatrixAuxPrefixed = function() { + var primary = this._stringifyPathMatrixAux(); + if (primary.length > 0) { + primary = '/' + primary; + } + return primary; + }; + Instruction.prototype._stringifyMatrixParams = function() { + return this.urlParams.length > 0 ? (';' + this.component.urlParams.join(';')) : ''; + }; + Instruction.prototype._stringifyPathMatrixAux = function() { + if (lang_1.isBlank(this.component)) { + return ''; + } + return this.urlPath + this._stringifyMatrixParams() + this._stringifyAux(); + }; + Instruction.prototype._stringifyAux = function() { + var routes = []; + collection_1.StringMapWrapper.forEach(this.auxInstruction, function(auxInstruction, _) { + routes.push(auxInstruction._stringifyPathMatrixAux()); + }); + if (routes.length > 0) { + return '(' + routes.join('//') + ')'; + } + return ''; + }; + return Instruction; + })(); + exports.Instruction = Instruction; + var ResolvedInstruction = (function(_super) { + __extends(ResolvedInstruction, _super); + function ResolvedInstruction(component, child, auxInstruction) { + _super.call(this); + this.component = component; + this.child = child; + this.auxInstruction = auxInstruction; + } + ResolvedInstruction.prototype.resolveComponent = function() { + return async_1.PromiseWrapper.resolve(this.component); + }; + return ResolvedInstruction; + })(Instruction); + exports.ResolvedInstruction = ResolvedInstruction; + var DefaultInstruction = (function(_super) { + __extends(DefaultInstruction, _super); + function DefaultInstruction(component, child) { + _super.call(this); + this.component = component; + this.child = child; + } + DefaultInstruction.prototype.resolveComponent = function() { + return async_1.PromiseWrapper.resolve(this.component); + }; + DefaultInstruction.prototype.toLinkUrl = function() { + return ''; + }; + DefaultInstruction.prototype._toLinkUrl = function() { + return ''; + }; + return DefaultInstruction; + })(Instruction); + exports.DefaultInstruction = DefaultInstruction; + var UnresolvedInstruction = (function(_super) { + __extends(UnresolvedInstruction, _super); + function UnresolvedInstruction(_resolver, _urlPath, _urlParams) { + if (_urlPath === void 0) { + _urlPath = ''; + } + if (_urlParams === void 0) { + _urlParams = lang_1.CONST_EXPR([]); + } + _super.call(this); + this._resolver = _resolver; + this._urlPath = _urlPath; + this._urlParams = _urlParams; + } + Object.defineProperty(UnresolvedInstruction.prototype, "urlPath", { + get: function() { + if (lang_1.isPresent(this.component)) { + return this.component.urlPath; + } + if (lang_1.isPresent(this._urlPath)) { + return this._urlPath; + } + return ''; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UnresolvedInstruction.prototype, "urlParams", { + get: function() { + if (lang_1.isPresent(this.component)) { + return this.component.urlParams; + } + if (lang_1.isPresent(this._urlParams)) { + return this._urlParams; + } + return []; + }, + enumerable: true, + configurable: true + }); + UnresolvedInstruction.prototype.resolveComponent = function() { + var _this = this; + if (lang_1.isPresent(this.component)) { + return async_1.PromiseWrapper.resolve(this.component); + } + return this._resolver().then(function(resolution) { + _this.child = resolution.child; + return _this.component = resolution.component; + }); + }; + return UnresolvedInstruction; + })(Instruction); + exports.UnresolvedInstruction = UnresolvedInstruction; + var RedirectInstruction = (function(_super) { + __extends(RedirectInstruction, _super); + function RedirectInstruction(component, child, auxInstruction) { + _super.call(this, component, child, auxInstruction); + } + return RedirectInstruction; + })(ResolvedInstruction); + exports.RedirectInstruction = RedirectInstruction; + var ComponentInstruction = (function() { + function ComponentInstruction(urlPath, urlParams, data, componentType, terminal, specificity, params) { + if (params === void 0) { + params = null; + } + this.urlPath = urlPath; + this.urlParams = urlParams; + this.componentType = componentType; + this.terminal = terminal; + this.specificity = specificity; + this.params = params; + this.reuse = false; + this.routeData = lang_1.isPresent(data) ? data : exports.BLANK_ROUTE_DATA; + } + return ComponentInstruction; + })(); + exports.ComponentInstruction = ComponentInstruction; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/url_parser", ["angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/facade/exceptions"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var Url = (function() { + function Url(path, child, auxiliary, params) { + if (child === void 0) { + child = null; + } + if (auxiliary === void 0) { + auxiliary = lang_1.CONST_EXPR([]); + } + if (params === void 0) { + params = null; + } + this.path = path; + this.child = child; + this.auxiliary = auxiliary; + this.params = params; + } + Url.prototype.toString = function() { + return this.path + this._matrixParamsToString() + this._auxToString() + this._childString(); + }; + Url.prototype.segmentToString = function() { + return this.path + this._matrixParamsToString(); + }; + Url.prototype._auxToString = function() { + return this.auxiliary.length > 0 ? ('(' + this.auxiliary.map(function(sibling) { + return sibling.toString(); + }).join('//') + ')') : ''; + }; + Url.prototype._matrixParamsToString = function() { + if (lang_1.isBlank(this.params)) { + return ''; + } + return ';' + serializeParams(this.params).join(';'); + }; + Url.prototype._childString = function() { + return lang_1.isPresent(this.child) ? ('/' + this.child.toString()) : ''; + }; + return Url; + })(); + exports.Url = Url; + var RootUrl = (function(_super) { + __extends(RootUrl, _super); + function RootUrl(path, child, auxiliary, params) { + if (child === void 0) { + child = null; + } + if (auxiliary === void 0) { + auxiliary = lang_1.CONST_EXPR([]); + } + if (params === void 0) { + params = null; + } + _super.call(this, path, child, auxiliary, params); + } + RootUrl.prototype.toString = function() { + return this.path + this._auxToString() + this._childString() + this._queryParamsToString(); + }; + RootUrl.prototype.segmentToString = function() { + return this.path + this._queryParamsToString(); + }; + RootUrl.prototype._queryParamsToString = function() { + if (lang_1.isBlank(this.params)) { + return ''; + } + return '?' + serializeParams(this.params).join('&'); + }; + return RootUrl; + })(Url); + exports.RootUrl = RootUrl; + function pathSegmentsToUrl(pathSegments) { + var url = new Url(pathSegments[pathSegments.length - 1]); + for (var i = pathSegments.length - 2; i >= 0; i -= 1) { + url = new Url(pathSegments[i], url); + } + return url; + } + exports.pathSegmentsToUrl = pathSegmentsToUrl; + var SEGMENT_RE = lang_1.RegExpWrapper.create('^[^\\/\\(\\)\\?;=&#]+'); + function matchUrlSegment(str) { + var match = lang_1.RegExpWrapper.firstMatch(SEGMENT_RE, str); + return lang_1.isPresent(match) ? match[0] : ''; + } + var UrlParser = (function() { + function UrlParser() {} + UrlParser.prototype.peekStartsWith = function(str) { + return this._remaining.startsWith(str); + }; + UrlParser.prototype.capture = function(str) { + if (!this._remaining.startsWith(str)) { + throw new exceptions_1.BaseException("Expected \"" + str + "\"."); + } + this._remaining = this._remaining.substring(str.length); + }; + UrlParser.prototype.parse = function(url) { + this._remaining = url; + if (url == '' || url == '/') { + return new Url(''); + } + return this.parseRoot(); + }; + UrlParser.prototype.parseRoot = function() { + if (this.peekStartsWith('/')) { + this.capture('/'); + } + var path = matchUrlSegment(this._remaining); + this.capture(path); + var aux = []; + if (this.peekStartsWith('(')) { + aux = this.parseAuxiliaryRoutes(); + } + if (this.peekStartsWith(';')) { + this.parseMatrixParams(); + } + var child = null; + if (this.peekStartsWith('/') && !this.peekStartsWith('//')) { + this.capture('/'); + child = this.parseSegment(); + } + var queryParams = null; + if (this.peekStartsWith('?')) { + queryParams = this.parseQueryParams(); + } + return new RootUrl(path, child, aux, queryParams); + }; + UrlParser.prototype.parseSegment = function() { + if (this._remaining.length == 0) { + return null; + } + if (this.peekStartsWith('/')) { + this.capture('/'); + } + var path = matchUrlSegment(this._remaining); + this.capture(path); + var matrixParams = null; + if (this.peekStartsWith(';')) { + matrixParams = this.parseMatrixParams(); + } + var aux = []; + if (this.peekStartsWith('(')) { + aux = this.parseAuxiliaryRoutes(); + } + var child = null; + if (this.peekStartsWith('/') && !this.peekStartsWith('//')) { + this.capture('/'); + child = this.parseSegment(); + } + return new Url(path, child, aux, matrixParams); + }; + UrlParser.prototype.parseQueryParams = function() { + var params = {}; + this.capture('?'); + this.parseParam(params); + while (this._remaining.length > 0 && this.peekStartsWith('&')) { + this.capture('&'); + this.parseParam(params); + } + return params; + }; + UrlParser.prototype.parseMatrixParams = function() { + var params = {}; + while (this._remaining.length > 0 && this.peekStartsWith(';')) { + this.capture(';'); + this.parseParam(params); + } + return params; + }; + UrlParser.prototype.parseParam = function(params) { + var key = matchUrlSegment(this._remaining); + if (lang_1.isBlank(key)) { + return ; + } + this.capture(key); + var value = true; + if (this.peekStartsWith('=')) { + this.capture('='); + var valueMatch = matchUrlSegment(this._remaining); + if (lang_1.isPresent(valueMatch)) { + value = valueMatch; + this.capture(value); + } + } + params[key] = value; + }; + UrlParser.prototype.parseAuxiliaryRoutes = function() { + var routes = []; + this.capture('('); + while (!this.peekStartsWith(')') && this._remaining.length > 0) { + routes.push(this.parseSegment()); + if (this.peekStartsWith('//')) { + this.capture('//'); + } + } + this.capture(')'); + return routes; + }; + return UrlParser; + })(); + exports.UrlParser = UrlParser; + exports.parser = new UrlParser(); + function serializeParams(paramMap) { + var params = []; + if (lang_1.isPresent(paramMap)) { + collection_1.StringMapWrapper.forEach(paramMap, function(value, key) { + if (value == true) { + params.push(key); + } else { + params.push(key + '=' + value); + } + }); + } + return params; + } + exports.serializeParams = serializeParams; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/async_route_handler", ["angular2/src/facade/lang", "angular2/src/router/instruction"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var instruction_1 = require("angular2/src/router/instruction"); + var AsyncRouteHandler = (function() { + function AsyncRouteHandler(_loader, data) { + if (data === void 0) { + data = null; + } + this._loader = _loader; + this._resolvedComponent = null; + this.data = lang_1.isPresent(data) ? new instruction_1.RouteData(data) : instruction_1.BLANK_ROUTE_DATA; + } + AsyncRouteHandler.prototype.resolveComponentType = function() { + var _this = this; + if (lang_1.isPresent(this._resolvedComponent)) { + return this._resolvedComponent; + } + return this._resolvedComponent = this._loader().then(function(componentType) { + _this.componentType = componentType; + return componentType; + }); + }; + return AsyncRouteHandler; + })(); + exports.AsyncRouteHandler = AsyncRouteHandler; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/sync_route_handler", ["angular2/src/facade/async", "angular2/src/facade/lang", "angular2/src/router/instruction"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var async_1 = require("angular2/src/facade/async"); + var lang_1 = require("angular2/src/facade/lang"); + var instruction_1 = require("angular2/src/router/instruction"); + var SyncRouteHandler = (function() { + function SyncRouteHandler(componentType, data) { + this.componentType = componentType; + this._resolvedComponent = null; + this._resolvedComponent = async_1.PromiseWrapper.resolve(componentType); + this.data = lang_1.isPresent(data) ? new instruction_1.RouteData(data) : instruction_1.BLANK_ROUTE_DATA; + } + SyncRouteHandler.prototype.resolveComponentType = function() { + return this._resolvedComponent; + }; + return SyncRouteHandler; + })(); + exports.SyncRouteHandler = SyncRouteHandler; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/route_config_decorator", ["angular2/src/router/route_config_impl", "angular2/src/core/util/decorators", "angular2/src/router/route_config_impl"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var route_config_impl_1 = require("angular2/src/router/route_config_impl"); + var decorators_1 = require("angular2/src/core/util/decorators"); + var route_config_impl_2 = require("angular2/src/router/route_config_impl"); + exports.Route = route_config_impl_2.Route; + exports.Redirect = route_config_impl_2.Redirect; + exports.AuxRoute = route_config_impl_2.AuxRoute; + exports.AsyncRoute = route_config_impl_2.AsyncRoute; + exports.RouteConfig = decorators_1.makeDecorator(route_config_impl_1.RouteConfig); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/location_strategy", ["angular2/src/facade/lang", "angular2/core"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var core_1 = require("angular2/core"); + var LocationStrategy = (function() { + function LocationStrategy() {} + return LocationStrategy; + })(); + exports.LocationStrategy = LocationStrategy; + exports.APP_BASE_HREF = lang_1.CONST_EXPR(new core_1.OpaqueToken('appBaseHref')); + function normalizeQueryParams(params) { + return (params.length > 0 && params.substring(0, 1) != '?') ? ('?' + params) : params; + } + exports.normalizeQueryParams = normalizeQueryParams; + function joinWithSlash(start, end) { + if (start.length == 0) { + return end; + } + if (end.length == 0) { + return start; + } + var slashes = 0; + if (start.endsWith('/')) { + slashes++; + } + if (end.startsWith('/')) { + slashes++; + } + if (slashes == 2) { + return start + end.substring(1); + } + if (slashes == 1) { + return start + end; + } + return start + '/' + end; + } + exports.joinWithSlash = joinWithSlash; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/lifecycle_annotations_impl", ["angular2/src/facade/lang"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var lang_1 = require("angular2/src/facade/lang"); + var RouteLifecycleHook = (function() { + function RouteLifecycleHook(name) { + this.name = name; + } + RouteLifecycleHook = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [String])], RouteLifecycleHook); + return RouteLifecycleHook; + })(); + exports.RouteLifecycleHook = RouteLifecycleHook; + var CanActivate = (function() { + function CanActivate(fn) { + this.fn = fn; + } + CanActivate = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Function])], CanActivate); + return CanActivate; + })(); + exports.CanActivate = CanActivate; + exports.routerCanReuse = lang_1.CONST_EXPR(new RouteLifecycleHook("routerCanReuse")); + exports.routerCanDeactivate = lang_1.CONST_EXPR(new RouteLifecycleHook("routerCanDeactivate")); + exports.routerOnActivate = lang_1.CONST_EXPR(new RouteLifecycleHook("routerOnActivate")); + exports.routerOnReuse = lang_1.CONST_EXPR(new RouteLifecycleHook("routerOnReuse")); + exports.routerOnDeactivate = lang_1.CONST_EXPR(new RouteLifecycleHook("routerOnDeactivate")); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/lifecycle_annotations", ["angular2/src/core/util/decorators", "angular2/src/router/lifecycle_annotations_impl", "angular2/src/router/lifecycle_annotations_impl"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var decorators_1 = require("angular2/src/core/util/decorators"); + var lifecycle_annotations_impl_1 = require("angular2/src/router/lifecycle_annotations_impl"); + var lifecycle_annotations_impl_2 = require("angular2/src/router/lifecycle_annotations_impl"); + exports.routerCanReuse = lifecycle_annotations_impl_2.routerCanReuse; + exports.routerCanDeactivate = lifecycle_annotations_impl_2.routerCanDeactivate; + exports.routerOnActivate = lifecycle_annotations_impl_2.routerOnActivate; + exports.routerOnReuse = lifecycle_annotations_impl_2.routerOnReuse; + exports.routerOnDeactivate = lifecycle_annotations_impl_2.routerOnDeactivate; + exports.CanActivate = decorators_1.makeDecorator(lifecycle_annotations_impl_1.CanActivate); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/router_link", ["angular2/core", "angular2/src/facade/lang", "angular2/src/router/router", "angular2/src/router/location"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var core_1 = require("angular2/core"); + var lang_1 = require("angular2/src/facade/lang"); + var router_1 = require("angular2/src/router/router"); + var location_1 = require("angular2/src/router/location"); + var RouterLink = (function() { + function RouterLink(_router, _location) { + this._router = _router; + this._location = _location; + } + Object.defineProperty(RouterLink.prototype, "isRouteActive", { + get: function() { + return this._router.isRouteActive(this._navigationInstruction); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RouterLink.prototype, "routeParams", { + set: function(changes) { + this._routeParams = changes; + this._navigationInstruction = this._router.generate(this._routeParams); + var navigationHref = this._navigationInstruction.toLinkUrl(); + this.visibleHref = this._location.prepareExternalUrl(navigationHref); + }, + enumerable: true, + configurable: true + }); + RouterLink.prototype.onClick = function() { + if (!lang_1.isString(this.target) || this.target == '_self') { + this._router.navigateByInstruction(this._navigationInstruction); + return false; + } + return true; + }; + RouterLink = __decorate([core_1.Directive({ + selector: '[routerLink]', + inputs: ['routeParams: routerLink', 'target: target'], + host: { + '(click)': 'onClick()', + '[attr.href]': 'visibleHref', + '[class.router-link-active]': 'isRouteActive' + } + }), __metadata('design:paramtypes', [router_1.Router, location_1.Location])], RouterLink); + return RouterLink; + })(); + exports.RouterLink = RouterLink; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/hash_location_strategy", ["angular2/core", "angular2/src/router/location_strategy", "angular2/src/facade/lang", "angular2/src/router/platform_location"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var core_1 = require("angular2/core"); + var location_strategy_1 = require("angular2/src/router/location_strategy"); + var lang_1 = require("angular2/src/facade/lang"); + var platform_location_1 = require("angular2/src/router/platform_location"); + var HashLocationStrategy = (function(_super) { + __extends(HashLocationStrategy, _super); + function HashLocationStrategy(_platformLocation, _baseHref) { + _super.call(this); + this._platformLocation = _platformLocation; + this._baseHref = ''; + if (lang_1.isPresent(_baseHref)) { + this._baseHref = _baseHref; + } + } + HashLocationStrategy.prototype.onPopState = function(fn) { + this._platformLocation.onPopState(fn); + this._platformLocation.onHashChange(fn); + }; + HashLocationStrategy.prototype.getBaseHref = function() { + return this._baseHref; + }; + HashLocationStrategy.prototype.path = function() { + var path = this._platformLocation.hash; + return (path.length > 0 ? path.substring(1) : path) + location_strategy_1.normalizeQueryParams(this._platformLocation.search); + }; + HashLocationStrategy.prototype.prepareExternalUrl = function(internal) { + var url = location_strategy_1.joinWithSlash(this._baseHref, internal); + return url.length > 0 ? ('#' + url) : url; + }; + HashLocationStrategy.prototype.pushState = function(state, title, path, queryParams) { + var url = this.prepareExternalUrl(path + location_strategy_1.normalizeQueryParams(queryParams)); + if (url.length == 0) { + url = this._platformLocation.pathname; + } + this._platformLocation.pushState(state, title, url); + }; + HashLocationStrategy.prototype.replaceState = function(state, title, path, queryParams) { + var url = this.prepareExternalUrl(path + location_strategy_1.normalizeQueryParams(queryParams)); + if (url.length == 0) { + url = this._platformLocation.pathname; + } + this._platformLocation.replaceState(state, title, url); + }; + HashLocationStrategy.prototype.forward = function() { + this._platformLocation.forward(); + }; + HashLocationStrategy.prototype.back = function() { + this._platformLocation.back(); + }; + HashLocationStrategy = __decorate([core_1.Injectable(), __param(1, core_1.Optional()), __param(1, core_1.Inject(location_strategy_1.APP_BASE_HREF)), __metadata('design:paramtypes', [platform_location_1.PlatformLocation, String])], HashLocationStrategy); + return HashLocationStrategy; + })(location_strategy_1.LocationStrategy); + exports.HashLocationStrategy = HashLocationStrategy; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/path_location_strategy", ["angular2/core", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/router/location_strategy", "angular2/src/router/platform_location"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var core_1 = require("angular2/core"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var location_strategy_1 = require("angular2/src/router/location_strategy"); + var platform_location_1 = require("angular2/src/router/platform_location"); + var PathLocationStrategy = (function(_super) { + __extends(PathLocationStrategy, _super); + function PathLocationStrategy(_platformLocation, href) { + _super.call(this); + this._platformLocation = _platformLocation; + if (lang_1.isBlank(href)) { + href = this._platformLocation.getBaseHrefFromDOM(); + } + if (lang_1.isBlank(href)) { + throw new exceptions_1.BaseException("No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document."); + } + this._baseHref = href; + } + PathLocationStrategy.prototype.onPopState = function(fn) { + this._platformLocation.onPopState(fn); + this._platformLocation.onHashChange(fn); + }; + PathLocationStrategy.prototype.getBaseHref = function() { + return this._baseHref; + }; + PathLocationStrategy.prototype.prepareExternalUrl = function(internal) { + return location_strategy_1.joinWithSlash(this._baseHref, internal); + }; + PathLocationStrategy.prototype.path = function() { + return this._platformLocation.pathname + location_strategy_1.normalizeQueryParams(this._platformLocation.search); + }; + PathLocationStrategy.prototype.pushState = function(state, title, url, queryParams) { + var externalUrl = this.prepareExternalUrl(url + location_strategy_1.normalizeQueryParams(queryParams)); + this._platformLocation.pushState(state, title, externalUrl); + }; + PathLocationStrategy.prototype.replaceState = function(state, title, url, queryParams) { + var externalUrl = this.prepareExternalUrl(url + location_strategy_1.normalizeQueryParams(queryParams)); + this._platformLocation.replaceState(state, title, externalUrl); + }; + PathLocationStrategy.prototype.forward = function() { + this._platformLocation.forward(); + }; + PathLocationStrategy.prototype.back = function() { + this._platformLocation.back(); + }; + PathLocationStrategy = __decorate([core_1.Injectable(), __param(1, core_1.Optional()), __param(1, core_1.Inject(location_strategy_1.APP_BASE_HREF)), __metadata('design:paramtypes', [platform_location_1.PlatformLocation, String])], PathLocationStrategy); + return PathLocationStrategy; + })(location_strategy_1.LocationStrategy); + exports.PathLocationStrategy = PathLocationStrategy; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/route_definition", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/path_recognizer", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/router/url_parser"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var url_parser_1 = require("angular2/src/router/url_parser"); + var TouchMap = (function() { + function TouchMap(map) { + var _this = this; + this.map = {}; + this.keys = {}; + if (lang_1.isPresent(map)) { + collection_1.StringMapWrapper.forEach(map, function(value, key) { + _this.map[key] = lang_1.isPresent(value) ? value.toString() : null; + _this.keys[key] = true; + }); + } + } + TouchMap.prototype.get = function(key) { + collection_1.StringMapWrapper.delete(this.keys, key); + return this.map[key]; + }; + TouchMap.prototype.getUnused = function() { + var _this = this; + var unused = {}; + var keys = collection_1.StringMapWrapper.keys(this.keys); + keys.forEach(function(key) { + return unused[key] = collection_1.StringMapWrapper.get(_this.map, key); + }); + return unused; + }; + return TouchMap; + })(); + function normalizeString(obj) { + if (lang_1.isBlank(obj)) { + return null; + } else { + return obj.toString(); + } + } + var ContinuationSegment = (function() { + function ContinuationSegment() { + this.name = ''; + } + ContinuationSegment.prototype.generate = function(params) { + return ''; + }; + ContinuationSegment.prototype.match = function(path) { + return true; + }; + return ContinuationSegment; + })(); + var StaticSegment = (function() { + function StaticSegment(path) { + this.path = path; + this.name = ''; + } + StaticSegment.prototype.match = function(path) { + return path == this.path; + }; + StaticSegment.prototype.generate = function(params) { + return this.path; + }; + return StaticSegment; + })(); + var DynamicSegment = (function() { + function DynamicSegment(name) { + this.name = name; + } + DynamicSegment.prototype.match = function(path) { + return path.length > 0; + }; + DynamicSegment.prototype.generate = function(params) { + if (!collection_1.StringMapWrapper.contains(params.map, this.name)) { + throw new exceptions_1.BaseException("Route generator for '" + this.name + "' was not included in parameters passed."); + } + return normalizeString(params.get(this.name)); + }; + return DynamicSegment; + })(); + var StarSegment = (function() { + function StarSegment(name) { + this.name = name; + } + StarSegment.prototype.match = function(path) { + return true; + }; + StarSegment.prototype.generate = function(params) { + return normalizeString(params.get(this.name)); + }; + return StarSegment; + })(); + var paramMatcher = /^:([^\/]+)$/g; + var wildcardMatcher = /^\*([^\/]+)$/g; + function parsePathString(route) { + if (route.startsWith("/")) { + route = route.substring(1); + } + var segments = splitBySlash(route); + var results = []; + var specificity = 0; + if (segments.length > 98) { + throw new exceptions_1.BaseException("'" + route + "' has more than the maximum supported number of segments."); + } + var limit = segments.length - 1; + for (var i = 0; i <= limit; i++) { + var segment = segments[i], + match; + if (lang_1.isPresent(match = lang_1.RegExpWrapper.firstMatch(paramMatcher, segment))) { + results.push(new DynamicSegment(match[1])); + specificity += (100 - i); + } else if (lang_1.isPresent(match = lang_1.RegExpWrapper.firstMatch(wildcardMatcher, segment))) { + results.push(new StarSegment(match[1])); + } else if (segment == '...') { + if (i < limit) { + throw new exceptions_1.BaseException("Unexpected \"...\" before the end of the path for \"" + route + "\"."); + } + results.push(new ContinuationSegment()); + } else { + results.push(new StaticSegment(segment)); + specificity += 100 * (100 - i); + } + } + var result = collection_1.StringMapWrapper.create(); + collection_1.StringMapWrapper.set(result, 'segments', results); + collection_1.StringMapWrapper.set(result, 'specificity', specificity); + return result; + } + function pathDslHash(segments) { + return segments.map(function(segment) { + if (segment instanceof StarSegment) { + return '*'; + } else if (segment instanceof ContinuationSegment) { + return '...'; + } else if (segment instanceof DynamicSegment) { + return ':'; + } else if (segment instanceof StaticSegment) { + return segment.path; + } + }).join('/'); + } + function splitBySlash(url) { + return url.split('/'); + } + var RESERVED_CHARS = lang_1.RegExpWrapper.create('//|\\(|\\)|;|\\?|='); + function assertPath(path) { + if (lang_1.StringWrapper.contains(path, '#')) { + throw new exceptions_1.BaseException("Path \"" + path + "\" should not include \"#\". Use \"HashLocationStrategy\" instead."); + } + var illegalCharacter = lang_1.RegExpWrapper.firstMatch(RESERVED_CHARS, path); + if (lang_1.isPresent(illegalCharacter)) { + throw new exceptions_1.BaseException("Path \"" + path + "\" contains \"" + illegalCharacter[0] + "\" which is not allowed in a route config."); + } + } + var PathRecognizer = (function() { + function PathRecognizer(path) { + this.path = path; + this.terminal = true; + assertPath(path); + var parsed = parsePathString(path); + this._segments = parsed['segments']; + this.specificity = parsed['specificity']; + this.hash = pathDslHash(this._segments); + var lastSegment = this._segments[this._segments.length - 1]; + this.terminal = !(lastSegment instanceof ContinuationSegment); + } + PathRecognizer.prototype.recognize = function(beginningSegment) { + var nextSegment = beginningSegment; + var currentSegment; + var positionalParams = {}; + var captured = []; + for (var i = 0; i < this._segments.length; i += 1) { + var segment = this._segments[i]; + currentSegment = nextSegment; + if (segment instanceof ContinuationSegment) { + break; + } + if (lang_1.isPresent(currentSegment)) { + captured.push(currentSegment.path); + if (segment instanceof StarSegment) { + positionalParams[segment.name] = currentSegment.toString(); + nextSegment = null; + break; + } + if (segment instanceof DynamicSegment) { + positionalParams[segment.name] = currentSegment.path; + } else if (!segment.match(currentSegment.path)) { + return null; + } + nextSegment = currentSegment.child; + } else if (!segment.match('')) { + return null; + } + } + if (this.terminal && lang_1.isPresent(nextSegment)) { + return null; + } + var urlPath = captured.join('/'); + var auxiliary; + var urlParams; + var allParams; + if (lang_1.isPresent(currentSegment)) { + var paramsSegment = beginningSegment instanceof url_parser_1.RootUrl ? beginningSegment : currentSegment; + allParams = lang_1.isPresent(paramsSegment.params) ? collection_1.StringMapWrapper.merge(paramsSegment.params, positionalParams) : positionalParams; + urlParams = url_parser_1.serializeParams(paramsSegment.params); + auxiliary = currentSegment.auxiliary; + } else { + allParams = positionalParams; + auxiliary = []; + urlParams = []; + } + return { + urlPath: urlPath, + urlParams: urlParams, + allParams: allParams, + auxiliary: auxiliary, + nextSegment: nextSegment + }; + }; + PathRecognizer.prototype.generate = function(params) { + var paramTokens = new TouchMap(params); + var path = []; + for (var i = 0; i < this._segments.length; i++) { + var segment = this._segments[i]; + if (!(segment instanceof ContinuationSegment)) { + path.push(segment.generate(paramTokens)); + } + } + var urlPath = path.join('/'); + var nonPositionalParams = paramTokens.getUnused(); + var urlParams = url_parser_1.serializeParams(nonPositionalParams); + return { + urlPath: urlPath, + urlParams: urlParams + }; + }; + return PathRecognizer; + })(); + exports.PathRecognizer = PathRecognizer; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/component_recognizer", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/facade/async", "angular2/src/router/route_recognizer", "angular2/src/router/route_config_impl", "angular2/src/router/async_route_handler", "angular2/src/router/sync_route_handler"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var collection_1 = require("angular2/src/facade/collection"); + var async_1 = require("angular2/src/facade/async"); + var route_recognizer_1 = require("angular2/src/router/route_recognizer"); + var route_config_impl_1 = require("angular2/src/router/route_config_impl"); + var async_route_handler_1 = require("angular2/src/router/async_route_handler"); + var sync_route_handler_1 = require("angular2/src/router/sync_route_handler"); + var ComponentRecognizer = (function() { + function ComponentRecognizer() { + this.names = new collection_1.Map(); + this.auxNames = new collection_1.Map(); + this.auxRoutes = new collection_1.Map(); + this.matchers = []; + this.defaultRoute = null; + } + ComponentRecognizer.prototype.config = function(config) { + var handler; + if (lang_1.isPresent(config.name) && config.name[0].toUpperCase() != config.name[0]) { + var suggestedName = config.name[0].toUpperCase() + config.name.substring(1); + throw new exceptions_1.BaseException("Route \"" + config.path + "\" with name \"" + config.name + "\" does not begin with an uppercase letter. Route names should be CamelCase like \"" + suggestedName + "\"."); + } + if (config instanceof route_config_impl_1.AuxRoute) { + handler = new sync_route_handler_1.SyncRouteHandler(config.component, config.data); + var path = config.path.startsWith('/') ? config.path.substring(1) : config.path; + var recognizer = new route_recognizer_1.RouteRecognizer(config.path, handler); + this.auxRoutes.set(path, recognizer); + if (lang_1.isPresent(config.name)) { + this.auxNames.set(config.name, recognizer); + } + return recognizer.terminal; + } + var useAsDefault = false; + if (config instanceof route_config_impl_1.Redirect) { + var redirector = new route_recognizer_1.RedirectRecognizer(config.path, config.redirectTo); + this._assertNoHashCollision(redirector.hash, config.path); + this.matchers.push(redirector); + return true; + } + if (config instanceof route_config_impl_1.Route) { + handler = new sync_route_handler_1.SyncRouteHandler(config.component, config.data); + useAsDefault = lang_1.isPresent(config.useAsDefault) && config.useAsDefault; + } else if (config instanceof route_config_impl_1.AsyncRoute) { + handler = new async_route_handler_1.AsyncRouteHandler(config.loader, config.data); + useAsDefault = lang_1.isPresent(config.useAsDefault) && config.useAsDefault; + } + var recognizer = new route_recognizer_1.RouteRecognizer(config.path, handler); + this._assertNoHashCollision(recognizer.hash, config.path); + if (useAsDefault) { + if (lang_1.isPresent(this.defaultRoute)) { + throw new exceptions_1.BaseException("Only one route can be default"); + } + this.defaultRoute = recognizer; + } + this.matchers.push(recognizer); + if (lang_1.isPresent(config.name)) { + this.names.set(config.name, recognizer); + } + return recognizer.terminal; + }; + ComponentRecognizer.prototype._assertNoHashCollision = function(hash, path) { + this.matchers.forEach(function(matcher) { + if (hash == matcher.hash) { + throw new exceptions_1.BaseException("Configuration '" + path + "' conflicts with existing route '" + matcher.path + "'"); + } + }); + }; + ComponentRecognizer.prototype.recognize = function(urlParse) { + var solutions = []; + this.matchers.forEach(function(routeRecognizer) { + var pathMatch = routeRecognizer.recognize(urlParse); + if (lang_1.isPresent(pathMatch)) { + solutions.push(pathMatch); + } + }); + return solutions; + }; + ComponentRecognizer.prototype.recognizeAuxiliary = function(urlParse) { + var routeRecognizer = this.auxRoutes.get(urlParse.path); + if (lang_1.isPresent(routeRecognizer)) { + return [routeRecognizer.recognize(urlParse)]; + } + return [async_1.PromiseWrapper.resolve(null)]; + }; + ComponentRecognizer.prototype.hasRoute = function(name) { + return this.names.has(name); + }; + ComponentRecognizer.prototype.componentLoaded = function(name) { + return this.hasRoute(name) && lang_1.isPresent(this.names.get(name).handler.componentType); + }; + ComponentRecognizer.prototype.loadComponent = function(name) { + return this.names.get(name).handler.resolveComponentType(); + }; + ComponentRecognizer.prototype.generate = function(name, params) { + var pathRecognizer = this.names.get(name); + if (lang_1.isBlank(pathRecognizer)) { + return null; + } + return pathRecognizer.generate(params); + }; + ComponentRecognizer.prototype.generateAuxiliary = function(name, params) { + var pathRecognizer = this.auxNames.get(name); + if (lang_1.isBlank(pathRecognizer)) { + return null; + } + return pathRecognizer.generate(params); + }; + return ComponentRecognizer; + })(); + exports.ComponentRecognizer = ComponentRecognizer; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/route_config_nomalizer", ["angular2/src/router/route_config_decorator", "angular2/src/facade/lang", "angular2/src/facade/exceptions"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var route_config_decorator_1 = require("angular2/src/router/route_config_decorator"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + function normalizeRouteConfig(config, registry) { + if (config instanceof route_config_decorator_1.AsyncRoute) { + var wrappedLoader = wrapLoaderToReconfigureRegistry(config.loader, registry); + return new route_config_decorator_1.AsyncRoute({ + path: config.path, + loader: wrappedLoader, + name: config.name, + data: config.data, + useAsDefault: config.useAsDefault + }); + } + if (config instanceof route_config_decorator_1.Route || config instanceof route_config_decorator_1.Redirect || config instanceof route_config_decorator_1.AuxRoute) { + return config; + } + if ((+!!config.component) + (+!!config.redirectTo) + (+!!config.loader) != 1) { + throw new exceptions_1.BaseException("Route config should contain exactly one \"component\", \"loader\", or \"redirectTo\" property."); + } + if (config.as && config.name) { + throw new exceptions_1.BaseException("Route config should contain exactly one \"as\" or \"name\" property."); + } + if (config.as) { + config.name = config.as; + } + if (config.loader) { + var wrappedLoader = wrapLoaderToReconfigureRegistry(config.loader, registry); + return new route_config_decorator_1.AsyncRoute({ + path: config.path, + loader: wrappedLoader, + name: config.name, + useAsDefault: config.useAsDefault + }); + } + if (config.aux) { + return new route_config_decorator_1.AuxRoute({ + path: config.aux, + component: config.component, + name: config.name + }); + } + if (config.component) { + if (typeof config.component == 'object') { + var componentDefinitionObject = config.component; + if (componentDefinitionObject.type == 'constructor') { + return new route_config_decorator_1.Route({ + path: config.path, + component: componentDefinitionObject.constructor, + name: config.name, + data: config.data, + useAsDefault: config.useAsDefault + }); + } else if (componentDefinitionObject.type == 'loader') { + return new route_config_decorator_1.AsyncRoute({ + path: config.path, + loader: componentDefinitionObject.loader, + name: config.name, + useAsDefault: config.useAsDefault + }); + } else { + throw new exceptions_1.BaseException("Invalid component type \"" + componentDefinitionObject.type + "\". Valid types are \"constructor\" and \"loader\"."); + } + } + return new route_config_decorator_1.Route(config); + } + if (config.redirectTo) { + return new route_config_decorator_1.Redirect({ + path: config.path, + redirectTo: config.redirectTo + }); + } + return config; + } + exports.normalizeRouteConfig = normalizeRouteConfig; + function wrapLoaderToReconfigureRegistry(loader, registry) { + return function() { + return loader().then(function(componentType) { + registry.configFromComponent(componentType); + return componentType; + }); + }; + } + function assertComponentExists(component, path) { + if (!lang_1.isType(component)) { + throw new exceptions_1.BaseException("Component for route \"" + path + "\" is not defined, or is not a class."); + } + } + exports.assertComponentExists = assertComponentExists; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/location", ["angular2/src/router/location_strategy", "angular2/src/facade/async", "angular2/core"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var location_strategy_1 = require("angular2/src/router/location_strategy"); + var async_1 = require("angular2/src/facade/async"); + var core_1 = require("angular2/core"); + var Location = (function() { + function Location(platformStrategy) { + var _this = this; + this.platformStrategy = platformStrategy; + this._subject = new async_1.EventEmitter(); + var browserBaseHref = this.platformStrategy.getBaseHref(); + this._baseHref = stripTrailingSlash(stripIndexHtml(browserBaseHref)); + this.platformStrategy.onPopState(function(ev) { + async_1.ObservableWrapper.callEmit(_this._subject, { + 'url': _this.path(), + 'pop': true, + 'type': ev.type + }); + }); + } + Location.prototype.path = function() { + return this.normalize(this.platformStrategy.path()); + }; + Location.prototype.normalize = function(url) { + return stripTrailingSlash(_stripBaseHref(this._baseHref, stripIndexHtml(url))); + }; + Location.prototype.prepareExternalUrl = function(url) { + if (url.length > 0 && !url.startsWith('/')) { + url = '/' + url; + } + return this.platformStrategy.prepareExternalUrl(url); + }; + Location.prototype.go = function(path, query) { + if (query === void 0) { + query = ''; + } + this.platformStrategy.pushState(null, '', path, query); + }; + Location.prototype.replaceState = function(path, query) { + if (query === void 0) { + query = ''; + } + this.platformStrategy.replaceState(null, '', path, query); + }; + Location.prototype.forward = function() { + this.platformStrategy.forward(); + }; + Location.prototype.back = function() { + this.platformStrategy.back(); + }; + Location.prototype.subscribe = function(onNext, onThrow, onReturn) { + if (onThrow === void 0) { + onThrow = null; + } + if (onReturn === void 0) { + onReturn = null; + } + return async_1.ObservableWrapper.subscribe(this._subject, onNext, onThrow, onReturn); + }; + Location = __decorate([core_1.Injectable(), __metadata('design:paramtypes', [location_strategy_1.LocationStrategy])], Location); + return Location; + })(); + exports.Location = Location; + function _stripBaseHref(baseHref, url) { + if (baseHref.length > 0 && url.startsWith(baseHref)) { + return url.substring(baseHref.length); + } + return url; + } + function stripIndexHtml(url) { + if (/\/index.html$/g.test(url)) { + return url.substring(0, url.length - 11); + } + return url; + } + function stripTrailingSlash(url) { + if (/\/$/g.test(url)) { + url = url.substring(0, url.length - 1); + } + return url; + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/route_lifecycle_reflector", ["angular2/src/facade/lang", "angular2/src/router/lifecycle_annotations_impl", "angular2/src/core/reflection/reflection"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var lifecycle_annotations_impl_1 = require("angular2/src/router/lifecycle_annotations_impl"); + var reflection_1 = require("angular2/src/core/reflection/reflection"); + function hasLifecycleHook(e, type) { + if (!(type instanceof lang_1.Type)) + return false; + return e.name in type.prototype; + } + exports.hasLifecycleHook = hasLifecycleHook; + function getCanActivateHook(type) { + var annotations = reflection_1.reflector.annotations(type); + for (var i = 0; i < annotations.length; i += 1) { + var annotation = annotations[i]; + if (annotation instanceof lifecycle_annotations_impl_1.CanActivate) { + return annotation.fn; + } + } + return null; + } + exports.getCanActivateHook = getCanActivateHook; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/router_outlet", ["angular2/src/facade/async", "angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/core", "angular2/src/router/router", "angular2/src/router/instruction", "angular2/src/router/lifecycle_annotations", "angular2/src/router/route_lifecycle_reflector"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var async_1 = require("angular2/src/facade/async"); + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var core_1 = require("angular2/core"); + var routerMod = require("angular2/src/router/router"); + var instruction_1 = require("angular2/src/router/instruction"); + var hookMod = require("angular2/src/router/lifecycle_annotations"); + var route_lifecycle_reflector_1 = require("angular2/src/router/route_lifecycle_reflector"); + var _resolveToTrue = async_1.PromiseWrapper.resolve(true); + var RouterOutlet = (function() { + function RouterOutlet(_elementRef, _loader, _parentRouter, nameAttr) { + this._elementRef = _elementRef; + this._loader = _loader; + this._parentRouter = _parentRouter; + this.name = null; + this._componentRef = null; + this._currentInstruction = null; + if (lang_1.isPresent(nameAttr)) { + this.name = nameAttr; + this._parentRouter.registerAuxOutlet(this); + } else { + this._parentRouter.registerPrimaryOutlet(this); + } + } + RouterOutlet.prototype.activate = function(nextInstruction) { + var _this = this; + var previousInstruction = this._currentInstruction; + this._currentInstruction = nextInstruction; + var componentType = nextInstruction.componentType; + var childRouter = this._parentRouter.childRouter(componentType); + var providers = core_1.Injector.resolve([core_1.provide(instruction_1.RouteData, {useValue: nextInstruction.routeData}), core_1.provide(instruction_1.RouteParams, {useValue: new instruction_1.RouteParams(nextInstruction.params)}), core_1.provide(routerMod.Router, {useValue: childRouter})]); + return this._loader.loadNextToLocation(componentType, this._elementRef, providers).then(function(componentRef) { + _this._componentRef = componentRef; + if (route_lifecycle_reflector_1.hasLifecycleHook(hookMod.routerOnActivate, componentType)) { + return _this._componentRef.instance.routerOnActivate(nextInstruction, previousInstruction); + } + }); + }; + RouterOutlet.prototype.reuse = function(nextInstruction) { + var previousInstruction = this._currentInstruction; + this._currentInstruction = nextInstruction; + if (lang_1.isBlank(this._componentRef)) { + throw new exceptions_1.BaseException("Cannot reuse an outlet that does not contain a component."); + } + return async_1.PromiseWrapper.resolve(route_lifecycle_reflector_1.hasLifecycleHook(hookMod.routerOnReuse, this._currentInstruction.componentType) ? this._componentRef.instance.routerOnReuse(nextInstruction, previousInstruction) : true); + }; + RouterOutlet.prototype.deactivate = function(nextInstruction) { + var _this = this; + var next = _resolveToTrue; + if (lang_1.isPresent(this._componentRef) && lang_1.isPresent(this._currentInstruction) && route_lifecycle_reflector_1.hasLifecycleHook(hookMod.routerOnDeactivate, this._currentInstruction.componentType)) { + next = async_1.PromiseWrapper.resolve(this._componentRef.instance.routerOnDeactivate(nextInstruction, this._currentInstruction)); + } + return next.then(function(_) { + if (lang_1.isPresent(_this._componentRef)) { + _this._componentRef.dispose(); + _this._componentRef = null; + } + }); + }; + RouterOutlet.prototype.routerCanDeactivate = function(nextInstruction) { + if (lang_1.isBlank(this._currentInstruction)) { + return _resolveToTrue; + } + if (route_lifecycle_reflector_1.hasLifecycleHook(hookMod.routerCanDeactivate, this._currentInstruction.componentType)) { + return async_1.PromiseWrapper.resolve(this._componentRef.instance.routerCanDeactivate(nextInstruction, this._currentInstruction)); + } + return _resolveToTrue; + }; + RouterOutlet.prototype.routerCanReuse = function(nextInstruction) { + var result; + if (lang_1.isBlank(this._currentInstruction) || this._currentInstruction.componentType != nextInstruction.componentType) { + result = false; + } else if (route_lifecycle_reflector_1.hasLifecycleHook(hookMod.routerCanReuse, this._currentInstruction.componentType)) { + result = this._componentRef.instance.routerCanReuse(nextInstruction, this._currentInstruction); + } else { + result = nextInstruction == this._currentInstruction || (lang_1.isPresent(nextInstruction.params) && lang_1.isPresent(this._currentInstruction.params) && collection_1.StringMapWrapper.equals(nextInstruction.params, this._currentInstruction.params)); + } + return async_1.PromiseWrapper.resolve(result); + }; + RouterOutlet = __decorate([core_1.Directive({selector: 'router-outlet'}), __param(3, core_1.Attribute('name')), __metadata('design:paramtypes', [core_1.ElementRef, core_1.DynamicComponentLoader, routerMod.Router, String])], RouterOutlet); + return RouterOutlet; + })(); + exports.RouterOutlet = RouterOutlet; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/platform_location", ["angular2/src/platform/dom/dom_adapter", "angular2/core"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); + var core_1 = require("angular2/core"); + var PlatformLocation = (function() { + function PlatformLocation() { + this._init(); + } + PlatformLocation.prototype._init = function() { + this._location = dom_adapter_1.DOM.getLocation(); + this._history = dom_adapter_1.DOM.getHistory(); + }; + PlatformLocation.prototype.getBaseHrefFromDOM = function() { + return dom_adapter_1.DOM.getBaseHref(); + }; + PlatformLocation.prototype.onPopState = function(fn) { + dom_adapter_1.DOM.getGlobalEventTarget('window').addEventListener('popstate', fn, false); + }; + PlatformLocation.prototype.onHashChange = function(fn) { + dom_adapter_1.DOM.getGlobalEventTarget('window').addEventListener('hashchange', fn, false); + }; + Object.defineProperty(PlatformLocation.prototype, "pathname", { + get: function() { + return this._location.pathname; + }, + set: function(newPath) { + this._location.pathname = newPath; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PlatformLocation.prototype, "search", { + get: function() { + return this._location.search; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PlatformLocation.prototype, "hash", { + get: function() { + return this._location.hash; + }, + enumerable: true, + configurable: true + }); + PlatformLocation.prototype.pushState = function(state, title, url) { + this._history.pushState(state, title, url); + }; + PlatformLocation.prototype.replaceState = function(state, title, url) { + this._history.replaceState(state, title, url); + }; + PlatformLocation.prototype.forward = function() { + this._history.forward(); + }; + PlatformLocation.prototype.back = function() { + this._history.back(); + }; + PlatformLocation = __decorate([core_1.Injectable(), __metadata('design:paramtypes', [])], PlatformLocation); + return PlatformLocation; + })(); + exports.PlatformLocation = PlatformLocation; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/route_recognizer", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/promise", "angular2/src/facade/collection", "angular2/src/router/instruction", "angular2/src/router/path_recognizer"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var promise_1 = require("angular2/src/facade/promise"); + var collection_1 = require("angular2/src/facade/collection"); + var instruction_1 = require("angular2/src/router/instruction"); + var path_recognizer_1 = require("angular2/src/router/path_recognizer"); + var RouteMatch = (function() { + function RouteMatch() {} + return RouteMatch; + })(); + exports.RouteMatch = RouteMatch; + var PathMatch = (function(_super) { + __extends(PathMatch, _super); + function PathMatch(instruction, remaining, remainingAux) { + _super.call(this); + this.instruction = instruction; + this.remaining = remaining; + this.remainingAux = remainingAux; + } + return PathMatch; + })(RouteMatch); + exports.PathMatch = PathMatch; + var RedirectMatch = (function(_super) { + __extends(RedirectMatch, _super); + function RedirectMatch(redirectTo, specificity) { + _super.call(this); + this.redirectTo = redirectTo; + this.specificity = specificity; + } + return RedirectMatch; + })(RouteMatch); + exports.RedirectMatch = RedirectMatch; + var RedirectRecognizer = (function() { + function RedirectRecognizer(path, redirectTo) { + this.path = path; + this.redirectTo = redirectTo; + this._pathRecognizer = new path_recognizer_1.PathRecognizer(path); + this.hash = this._pathRecognizer.hash; + } + RedirectRecognizer.prototype.recognize = function(beginningSegment) { + var match = null; + if (lang_1.isPresent(this._pathRecognizer.recognize(beginningSegment))) { + match = new RedirectMatch(this.redirectTo, this._pathRecognizer.specificity); + } + return promise_1.PromiseWrapper.resolve(match); + }; + RedirectRecognizer.prototype.generate = function(params) { + throw new exceptions_1.BaseException("Tried to generate a redirect."); + }; + return RedirectRecognizer; + })(); + exports.RedirectRecognizer = RedirectRecognizer; + var RouteRecognizer = (function() { + function RouteRecognizer(path, handler) { + this.path = path; + this.handler = handler; + this.terminal = true; + this._cache = new collection_1.Map(); + this._pathRecognizer = new path_recognizer_1.PathRecognizer(path); + this.specificity = this._pathRecognizer.specificity; + this.hash = this._pathRecognizer.hash; + this.terminal = this._pathRecognizer.terminal; + } + RouteRecognizer.prototype.recognize = function(beginningSegment) { + var _this = this; + var res = this._pathRecognizer.recognize(beginningSegment); + if (lang_1.isBlank(res)) { + return null; + } + return this.handler.resolveComponentType().then(function(_) { + var componentInstruction = _this._getInstruction(res['urlPath'], res['urlParams'], res['allParams']); + return new PathMatch(componentInstruction, res['nextSegment'], res['auxiliary']); + }); + }; + RouteRecognizer.prototype.generate = function(params) { + var generated = this._pathRecognizer.generate(params); + var urlPath = generated['urlPath']; + var urlParams = generated['urlParams']; + return this._getInstruction(urlPath, urlParams, params); + }; + RouteRecognizer.prototype.generateComponentPathValues = function(params) { + return this._pathRecognizer.generate(params); + }; + RouteRecognizer.prototype._getInstruction = function(urlPath, urlParams, params) { + if (lang_1.isBlank(this.handler.componentType)) { + throw new exceptions_1.BaseException("Tried to get instruction before the type was loaded."); + } + var hashKey = urlPath + '?' + urlParams.join('?'); + if (this._cache.has(hashKey)) { + return this._cache.get(hashKey); + } + var instruction = new instruction_1.ComponentInstruction(urlPath, urlParams, this.handler.data, this.handler.componentType, this.terminal, this.specificity, params); + this._cache.set(hashKey, instruction); + return instruction; + }; + return RouteRecognizer; + })(); + exports.RouteRecognizer = RouteRecognizer; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/route_registry", ["angular2/src/facade/collection", "angular2/src/facade/async", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/core/reflection/reflection", "angular2/core", "angular2/src/router/route_config_impl", "angular2/src/router/route_recognizer", "angular2/src/router/component_recognizer", "angular2/src/router/instruction", "angular2/src/router/route_config_nomalizer", "angular2/src/router/url_parser"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var collection_1 = require("angular2/src/facade/collection"); + var async_1 = require("angular2/src/facade/async"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var reflection_1 = require("angular2/src/core/reflection/reflection"); + var core_1 = require("angular2/core"); + var route_config_impl_1 = require("angular2/src/router/route_config_impl"); + var route_recognizer_1 = require("angular2/src/router/route_recognizer"); + var component_recognizer_1 = require("angular2/src/router/component_recognizer"); + var instruction_1 = require("angular2/src/router/instruction"); + var route_config_nomalizer_1 = require("angular2/src/router/route_config_nomalizer"); + var url_parser_1 = require("angular2/src/router/url_parser"); + var _resolveToNull = async_1.PromiseWrapper.resolve(null); + exports.ROUTER_PRIMARY_COMPONENT = lang_1.CONST_EXPR(new core_1.OpaqueToken('RouterPrimaryComponent')); + var RouteRegistry = (function() { + function RouteRegistry(_rootComponent) { + this._rootComponent = _rootComponent; + this._rules = new collection_1.Map(); + } + RouteRegistry.prototype.config = function(parentComponent, config) { + config = route_config_nomalizer_1.normalizeRouteConfig(config, this); + if (config instanceof route_config_impl_1.Route) { + route_config_nomalizer_1.assertComponentExists(config.component, config.path); + } else if (config instanceof route_config_impl_1.AuxRoute) { + route_config_nomalizer_1.assertComponentExists(config.component, config.path); + } + var recognizer = this._rules.get(parentComponent); + if (lang_1.isBlank(recognizer)) { + recognizer = new component_recognizer_1.ComponentRecognizer(); + this._rules.set(parentComponent, recognizer); + } + var terminal = recognizer.config(config); + if (config instanceof route_config_impl_1.Route) { + if (terminal) { + assertTerminalComponent(config.component, config.path); + } else { + this.configFromComponent(config.component); + } + } + }; + RouteRegistry.prototype.configFromComponent = function(component) { + var _this = this; + if (!lang_1.isType(component)) { + return ; + } + if (this._rules.has(component)) { + return ; + } + var annotations = reflection_1.reflector.annotations(component); + if (lang_1.isPresent(annotations)) { + for (var i = 0; i < annotations.length; i++) { + var annotation = annotations[i]; + if (annotation instanceof route_config_impl_1.RouteConfig) { + var routeCfgs = annotation.configs; + routeCfgs.forEach(function(config) { + return _this.config(component, config); + }); + } + } + } + }; + RouteRegistry.prototype.recognize = function(url, ancestorInstructions) { + var parsedUrl = url_parser_1.parser.parse(url); + return this._recognize(parsedUrl, ancestorInstructions); + }; + RouteRegistry.prototype._recognize = function(parsedUrl, ancestorInstructions, _aux) { + var _this = this; + if (_aux === void 0) { + _aux = false; + } + var parentComponent = ancestorInstructions.length > 0 ? ancestorInstructions[ancestorInstructions.length - 1].component.componentType : this._rootComponent; + var componentRecognizer = this._rules.get(parentComponent); + if (lang_1.isBlank(componentRecognizer)) { + return _resolveToNull; + } + var possibleMatches = _aux ? componentRecognizer.recognizeAuxiliary(parsedUrl) : componentRecognizer.recognize(parsedUrl); + var matchPromises = possibleMatches.map(function(candidate) { + return candidate.then(function(candidate) { + if (candidate instanceof route_recognizer_1.PathMatch) { + var auxParentInstructions = ancestorInstructions.length > 0 ? [ancestorInstructions[ancestorInstructions.length - 1]] : []; + var auxInstructions = _this._auxRoutesToUnresolved(candidate.remainingAux, auxParentInstructions); + var instruction = new instruction_1.ResolvedInstruction(candidate.instruction, null, auxInstructions); + if (candidate.instruction.terminal) { + return instruction; + } + var newAncestorComponents = ancestorInstructions.concat([instruction]); + return _this._recognize(candidate.remaining, newAncestorComponents).then(function(childInstruction) { + if (lang_1.isBlank(childInstruction)) { + return null; + } + if (childInstruction instanceof instruction_1.RedirectInstruction) { + return childInstruction; + } + instruction.child = childInstruction; + return instruction; + }); + } + if (candidate instanceof route_recognizer_1.RedirectMatch) { + var instruction = _this.generate(candidate.redirectTo, ancestorInstructions); + return new instruction_1.RedirectInstruction(instruction.component, instruction.child, instruction.auxInstruction); + } + }); + }); + if ((lang_1.isBlank(parsedUrl) || parsedUrl.path == '') && possibleMatches.length == 0) { + return async_1.PromiseWrapper.resolve(this.generateDefault(parentComponent)); + } + return async_1.PromiseWrapper.all(matchPromises).then(mostSpecific); + }; + RouteRegistry.prototype._auxRoutesToUnresolved = function(auxRoutes, parentInstructions) { + var _this = this; + var unresolvedAuxInstructions = {}; + auxRoutes.forEach(function(auxUrl) { + unresolvedAuxInstructions[auxUrl.path] = new instruction_1.UnresolvedInstruction(function() { + return _this._recognize(auxUrl, parentInstructions, true); + }); + }); + return unresolvedAuxInstructions; + }; + RouteRegistry.prototype.generate = function(linkParams, ancestorInstructions, _aux) { + if (_aux === void 0) { + _aux = false; + } + var normalizedLinkParams = splitAndFlattenLinkParams(linkParams); + var first = collection_1.ListWrapper.first(normalizedLinkParams); + var rest = collection_1.ListWrapper.slice(normalizedLinkParams, 1); + if (first == '') { + ancestorInstructions = []; + } else if (first == '..') { + ancestorInstructions.pop(); + while (collection_1.ListWrapper.first(rest) == '..') { + rest = collection_1.ListWrapper.slice(rest, 1); + ancestorInstructions.pop(); + if (ancestorInstructions.length <= 0) { + throw new exceptions_1.BaseException("Link \"" + collection_1.ListWrapper.toJSON(linkParams) + "\" has too many \"../\" segments."); + } + } + } else if (first != '.') { + var parentComponent = this._rootComponent; + var grandparentComponent = null; + if (ancestorInstructions.length > 1) { + parentComponent = ancestorInstructions[ancestorInstructions.length - 1].component.componentType; + grandparentComponent = ancestorInstructions[ancestorInstructions.length - 2].component.componentType; + } else if (ancestorInstructions.length == 1) { + parentComponent = ancestorInstructions[0].component.componentType; + grandparentComponent = this._rootComponent; + } + var childRouteExists = this.hasRoute(first, parentComponent); + var parentRouteExists = lang_1.isPresent(grandparentComponent) && this.hasRoute(first, grandparentComponent); + if (parentRouteExists && childRouteExists) { + var msg = "Link \"" + collection_1.ListWrapper.toJSON(linkParams) + "\" is ambiguous, use \"./\" or \"../\" to disambiguate."; + throw new exceptions_1.BaseException(msg); + } + if (parentRouteExists) { + ancestorInstructions.pop(); + } + rest = linkParams; + } + if (rest[rest.length - 1] == '') { + rest.pop(); + } + if (rest.length < 1) { + var msg = "Link \"" + collection_1.ListWrapper.toJSON(linkParams) + "\" must include a route name."; + throw new exceptions_1.BaseException(msg); + } + var generatedInstruction = this._generate(rest, ancestorInstructions, _aux); + for (var i = ancestorInstructions.length - 1; i >= 0; i--) { + var ancestorInstruction = ancestorInstructions[i]; + generatedInstruction = ancestorInstruction.replaceChild(generatedInstruction); + } + return generatedInstruction; + }; + RouteRegistry.prototype._generate = function(linkParams, ancestorInstructions, _aux) { + var _this = this; + if (_aux === void 0) { + _aux = false; + } + var parentComponent = ancestorInstructions.length > 0 ? ancestorInstructions[ancestorInstructions.length - 1].component.componentType : this._rootComponent; + if (linkParams.length == 0) { + return this.generateDefault(parentComponent); + } + var linkIndex = 0; + var routeName = linkParams[linkIndex]; + if (!lang_1.isString(routeName)) { + throw new exceptions_1.BaseException("Unexpected segment \"" + routeName + "\" in link DSL. Expected a string."); + } else if (routeName == '' || routeName == '.' || routeName == '..') { + throw new exceptions_1.BaseException("\"" + routeName + "/\" is only allowed at the beginning of a link DSL."); + } + var params = {}; + if (linkIndex + 1 < linkParams.length) { + var nextSegment_1 = linkParams[linkIndex + 1]; + if (lang_1.isStringMap(nextSegment_1) && !lang_1.isArray(nextSegment_1)) { + params = nextSegment_1; + linkIndex += 1; + } + } + var auxInstructions = {}; + var nextSegment; + while (linkIndex + 1 < linkParams.length && lang_1.isArray(nextSegment = linkParams[linkIndex + 1])) { + var auxParentInstruction = ancestorInstructions.length > 0 ? [ancestorInstructions[ancestorInstructions.length - 1]] : []; + var auxInstruction = this._generate(nextSegment, auxParentInstruction, true); + auxInstructions[auxInstruction.component.urlPath] = auxInstruction; + linkIndex += 1; + } + var componentRecognizer = this._rules.get(parentComponent); + if (lang_1.isBlank(componentRecognizer)) { + throw new exceptions_1.BaseException("Component \"" + lang_1.getTypeNameForDebugging(parentComponent) + "\" has no route config."); + } + var routeRecognizer = (_aux ? componentRecognizer.auxNames : componentRecognizer.names).get(routeName); + if (!lang_1.isPresent(routeRecognizer)) { + throw new exceptions_1.BaseException("Component \"" + lang_1.getTypeNameForDebugging(parentComponent) + "\" has no route named \"" + routeName + "\"."); + } + if (!lang_1.isPresent(routeRecognizer.handler.componentType)) { + var compInstruction = routeRecognizer.generateComponentPathValues(params); + return new instruction_1.UnresolvedInstruction(function() { + return routeRecognizer.handler.resolveComponentType().then(function(_) { + return _this._generate(linkParams, ancestorInstructions, _aux); + }); + }, compInstruction['urlPath'], compInstruction['urlParams']); + } + var componentInstruction = _aux ? componentRecognizer.generateAuxiliary(routeName, params) : componentRecognizer.generate(routeName, params); + var remaining = linkParams.slice(linkIndex + 1); + var instruction = new instruction_1.ResolvedInstruction(componentInstruction, null, auxInstructions); + if (lang_1.isPresent(componentInstruction.componentType)) { + var childInstruction = null; + if (linkIndex + 1 < linkParams.length) { + var childAncestorComponents = ancestorInstructions.concat([instruction]); + childInstruction = this._generate(remaining, childAncestorComponents); + } else if (!componentInstruction.terminal) { + childInstruction = this.generateDefault(componentInstruction.componentType); + if (lang_1.isBlank(childInstruction)) { + throw new exceptions_1.BaseException("Link \"" + collection_1.ListWrapper.toJSON(linkParams) + "\" does not resolve to a terminal instruction."); + } + } + instruction.child = childInstruction; + } + return instruction; + }; + RouteRegistry.prototype.hasRoute = function(name, parentComponent) { + var componentRecognizer = this._rules.get(parentComponent); + if (lang_1.isBlank(componentRecognizer)) { + return false; + } + return componentRecognizer.hasRoute(name); + }; + RouteRegistry.prototype.generateDefault = function(componentCursor) { + var _this = this; + if (lang_1.isBlank(componentCursor)) { + return null; + } + var componentRecognizer = this._rules.get(componentCursor); + if (lang_1.isBlank(componentRecognizer) || lang_1.isBlank(componentRecognizer.defaultRoute)) { + return null; + } + var defaultChild = null; + if (lang_1.isPresent(componentRecognizer.defaultRoute.handler.componentType)) { + var componentInstruction = componentRecognizer.defaultRoute.generate({}); + if (!componentRecognizer.defaultRoute.terminal) { + defaultChild = this.generateDefault(componentRecognizer.defaultRoute.handler.componentType); + } + return new instruction_1.DefaultInstruction(componentInstruction, defaultChild); + } + return new instruction_1.UnresolvedInstruction(function() { + return componentRecognizer.defaultRoute.handler.resolveComponentType().then(function(_) { + return _this.generateDefault(componentCursor); + }); + }); + }; + RouteRegistry = __decorate([core_1.Injectable(), __param(0, core_1.Inject(exports.ROUTER_PRIMARY_COMPONENT)), __metadata('design:paramtypes', [lang_1.Type])], RouteRegistry); + return RouteRegistry; + })(); + exports.RouteRegistry = RouteRegistry; + function splitAndFlattenLinkParams(linkParams) { + return linkParams.reduce(function(accumulation, item) { + if (lang_1.isString(item)) { + var strItem = item; + return accumulation.concat(strItem.split('/')); + } + accumulation.push(item); + return accumulation; + }, []); + } + function mostSpecific(instructions) { + return collection_1.ListWrapper.maximum(instructions, function(instruction) { + return instruction.specificity; + }); + } + function assertTerminalComponent(component, path) { + if (!lang_1.isType(component)) { + return ; + } + var annotations = reflection_1.reflector.annotations(component); + if (lang_1.isPresent(annotations)) { + for (var i = 0; i < annotations.length; i++) { + var annotation = annotations[i]; + if (annotation instanceof route_config_impl_1.RouteConfig) { + throw new exceptions_1.BaseException("Child routes are not allowed for \"" + path + "\". Use \"...\" on the parent's route path."); + } + } + } + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/router", ["angular2/src/facade/async", "angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/core", "angular2/src/router/route_registry", "angular2/src/router/location", "angular2/src/router/route_lifecycle_reflector"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var __decorate = (this && this.__decorate) || function(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function(k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(k, v); + }; + var __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + }; + var async_1 = require("angular2/src/facade/async"); + var collection_1 = require("angular2/src/facade/collection"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var core_1 = require("angular2/core"); + var route_registry_1 = require("angular2/src/router/route_registry"); + var location_1 = require("angular2/src/router/location"); + var route_lifecycle_reflector_1 = require("angular2/src/router/route_lifecycle_reflector"); + var _resolveToTrue = async_1.PromiseWrapper.resolve(true); + var _resolveToFalse = async_1.PromiseWrapper.resolve(false); + var Router = (function() { + function Router(registry, parent, hostComponent) { + this.registry = registry; + this.parent = parent; + this.hostComponent = hostComponent; + this.navigating = false; + this._currentInstruction = null; + this._currentNavigation = _resolveToTrue; + this._outlet = null; + this._auxRouters = new collection_1.Map(); + this._subject = new async_1.EventEmitter(); + } + Router.prototype.childRouter = function(hostComponent) { + return this._childRouter = new ChildRouter(this, hostComponent); + }; + Router.prototype.auxRouter = function(hostComponent) { + return new ChildRouter(this, hostComponent); + }; + Router.prototype.registerPrimaryOutlet = function(outlet) { + if (lang_1.isPresent(outlet.name)) { + throw new exceptions_1.BaseException("registerPrimaryOutlet expects to be called with an unnamed outlet."); + } + this._outlet = outlet; + if (lang_1.isPresent(this._currentInstruction)) { + return this.commit(this._currentInstruction, false); + } + return _resolveToTrue; + }; + Router.prototype.registerAuxOutlet = function(outlet) { + var outletName = outlet.name; + if (lang_1.isBlank(outletName)) { + throw new exceptions_1.BaseException("registerAuxOutlet expects to be called with an outlet with a name."); + } + var router = this.auxRouter(this.hostComponent); + this._auxRouters.set(outletName, router); + router._outlet = outlet; + var auxInstruction; + if (lang_1.isPresent(this._currentInstruction) && lang_1.isPresent(auxInstruction = this._currentInstruction.auxInstruction[outletName])) { + return router.commit(auxInstruction); + } + return _resolveToTrue; + }; + Router.prototype.isRouteActive = function(instruction) { + var router = this; + while (lang_1.isPresent(router.parent) && lang_1.isPresent(instruction.child)) { + router = router.parent; + instruction = instruction.child; + } + return lang_1.isPresent(this._currentInstruction) && this._currentInstruction.component == instruction.component; + }; + Router.prototype.config = function(definitions) { + var _this = this; + definitions.forEach(function(routeDefinition) { + _this.registry.config(_this.hostComponent, routeDefinition); + }); + return this.renavigate(); + }; + Router.prototype.navigate = function(linkParams) { + var instruction = this.generate(linkParams); + return this.navigateByInstruction(instruction, false); + }; + Router.prototype.navigateByUrl = function(url, _skipLocationChange) { + var _this = this; + if (_skipLocationChange === void 0) { + _skipLocationChange = false; + } + return this._currentNavigation = this._currentNavigation.then(function(_) { + _this.lastNavigationAttempt = url; + _this._startNavigating(); + return _this._afterPromiseFinishNavigating(_this.recognize(url).then(function(instruction) { + if (lang_1.isBlank(instruction)) { + return false; + } + return _this._navigate(instruction, _skipLocationChange); + })); + }); + }; + Router.prototype.navigateByInstruction = function(instruction, _skipLocationChange) { + var _this = this; + if (_skipLocationChange === void 0) { + _skipLocationChange = false; + } + if (lang_1.isBlank(instruction)) { + return _resolveToFalse; + } + return this._currentNavigation = this._currentNavigation.then(function(_) { + _this._startNavigating(); + return _this._afterPromiseFinishNavigating(_this._navigate(instruction, _skipLocationChange)); + }); + }; + Router.prototype._navigate = function(instruction, _skipLocationChange) { + var _this = this; + return this._settleInstruction(instruction).then(function(_) { + return _this._routerCanReuse(instruction); + }).then(function(_) { + return _this._canActivate(instruction); + }).then(function(result) { + if (!result) { + return false; + } + return _this._routerCanDeactivate(instruction).then(function(result) { + if (result) { + return _this.commit(instruction, _skipLocationChange).then(function(_) { + _this._emitNavigationFinish(instruction.toRootUrl()); + return true; + }); + } + }); + }); + }; + Router.prototype._settleInstruction = function(instruction) { + var _this = this; + return instruction.resolveComponent().then(function(_) { + instruction.component.reuse = false; + var unsettledInstructions = []; + if (lang_1.isPresent(instruction.child)) { + unsettledInstructions.push(_this._settleInstruction(instruction.child)); + } + collection_1.StringMapWrapper.forEach(instruction.auxInstruction, function(instruction, _) { + unsettledInstructions.push(_this._settleInstruction(instruction)); + }); + return async_1.PromiseWrapper.all(unsettledInstructions); + }); + }; + Router.prototype._emitNavigationFinish = function(url) { + async_1.ObservableWrapper.callEmit(this._subject, url); + }; + Router.prototype._afterPromiseFinishNavigating = function(promise) { + var _this = this; + return async_1.PromiseWrapper.catchError(promise.then(function(_) { + return _this._finishNavigating(); + }), function(err) { + _this._finishNavigating(); + throw err; + }); + }; + Router.prototype._routerCanReuse = function(instruction) { + var _this = this; + if (lang_1.isBlank(this._outlet)) { + return _resolveToFalse; + } + return this._outlet.routerCanReuse(instruction.component).then(function(result) { + instruction.component.reuse = result; + if (result && lang_1.isPresent(_this._childRouter) && lang_1.isPresent(instruction.child)) { + return _this._childRouter._routerCanReuse(instruction.child); + } + }); + }; + Router.prototype._canActivate = function(nextInstruction) { + return canActivateOne(nextInstruction, this._currentInstruction); + }; + Router.prototype._routerCanDeactivate = function(instruction) { + var _this = this; + if (lang_1.isBlank(this._outlet)) { + return _resolveToTrue; + } + var next; + var childInstruction = null; + var reuse = false; + var componentInstruction = null; + if (lang_1.isPresent(instruction)) { + childInstruction = instruction.child; + componentInstruction = instruction.component; + reuse = instruction.component.reuse; + } + if (reuse) { + next = _resolveToTrue; + } else { + next = this._outlet.routerCanDeactivate(componentInstruction); + } + return next.then(function(result) { + if (result == false) { + return false; + } + if (lang_1.isPresent(_this._childRouter)) { + return _this._childRouter._routerCanDeactivate(childInstruction); + } + return true; + }); + }; + Router.prototype.commit = function(instruction, _skipLocationChange) { + var _this = this; + if (_skipLocationChange === void 0) { + _skipLocationChange = false; + } + this._currentInstruction = instruction; + var next = _resolveToTrue; + if (lang_1.isPresent(this._outlet)) { + var componentInstruction = instruction.component; + if (componentInstruction.reuse) { + next = this._outlet.reuse(componentInstruction); + } else { + next = this.deactivate(instruction).then(function(_) { + return _this._outlet.activate(componentInstruction); + }); + } + if (lang_1.isPresent(instruction.child)) { + next = next.then(function(_) { + if (lang_1.isPresent(_this._childRouter)) { + return _this._childRouter.commit(instruction.child); + } + }); + } + } + var promises = []; + this._auxRouters.forEach(function(router, name) { + if (lang_1.isPresent(instruction.auxInstruction[name])) { + promises.push(router.commit(instruction.auxInstruction[name])); + } + }); + return next.then(function(_) { + return async_1.PromiseWrapper.all(promises); + }); + }; + Router.prototype._startNavigating = function() { + this.navigating = true; + }; + Router.prototype._finishNavigating = function() { + this.navigating = false; + }; + Router.prototype.subscribe = function(onNext) { + return async_1.ObservableWrapper.subscribe(this._subject, onNext); + }; + Router.prototype.deactivate = function(instruction) { + var _this = this; + var childInstruction = null; + var componentInstruction = null; + if (lang_1.isPresent(instruction)) { + childInstruction = instruction.child; + componentInstruction = instruction.component; + } + var next = _resolveToTrue; + if (lang_1.isPresent(this._childRouter)) { + next = this._childRouter.deactivate(childInstruction); + } + if (lang_1.isPresent(this._outlet)) { + next = next.then(function(_) { + return _this._outlet.deactivate(componentInstruction); + }); + } + return next; + }; + Router.prototype.recognize = function(url) { + var ancestorComponents = this._getAncestorInstructions(); + return this.registry.recognize(url, ancestorComponents); + }; + Router.prototype._getAncestorInstructions = function() { + var ancestorComponents = []; + var ancestorRouter = this; + while (lang_1.isPresent(ancestorRouter.parent) && lang_1.isPresent(ancestorRouter.parent._currentInstruction)) { + ancestorRouter = ancestorRouter.parent; + ancestorComponents.unshift(ancestorRouter._currentInstruction); + } + return ancestorComponents; + }; + Router.prototype.renavigate = function() { + if (lang_1.isBlank(this.lastNavigationAttempt)) { + return this._currentNavigation; + } + return this.navigateByUrl(this.lastNavigationAttempt); + }; + Router.prototype.generate = function(linkParams) { + var ancestorInstructions = this._getAncestorInstructions(); + return this.registry.generate(linkParams, ancestorInstructions); + }; + return Router; + })(); + exports.Router = Router; + var RootRouter = (function(_super) { + __extends(RootRouter, _super); + function RootRouter(registry, location, primaryComponent) { + var _this = this; + _super.call(this, registry, null, primaryComponent); + this._location = location; + this._locationSub = this._location.subscribe(function(change) { + _this.recognize(change['url']).then(function(instruction) { + _this.navigateByInstruction(instruction, lang_1.isPresent(change['pop'])).then(function(_) { + if (lang_1.isPresent(change['pop']) && change['type'] != 'hashchange') { + return ; + } + var emitPath = instruction.toUrlPath(); + var emitQuery = instruction.toUrlQuery(); + if (emitPath.length > 0) { + emitPath = '/' + emitPath; + } + if (change['type'] == 'hashchange') { + if (instruction.toRootUrl() != _this._location.path()) { + _this._location.replaceState(emitPath, emitQuery); + } + } else { + _this._location.go(emitPath, emitQuery); + } + }); + }); + }); + this.registry.configFromComponent(primaryComponent); + this.navigateByUrl(location.path()); + } + RootRouter.prototype.commit = function(instruction, _skipLocationChange) { + var _this = this; + if (_skipLocationChange === void 0) { + _skipLocationChange = false; + } + var emitPath = instruction.toUrlPath(); + var emitQuery = instruction.toUrlQuery(); + if (emitPath.length > 0) { + emitPath = '/' + emitPath; + } + var promise = _super.prototype.commit.call(this, instruction); + if (!_skipLocationChange) { + promise = promise.then(function(_) { + _this._location.go(emitPath, emitQuery); + }); + } + return promise; + }; + RootRouter.prototype.dispose = function() { + if (lang_1.isPresent(this._locationSub)) { + async_1.ObservableWrapper.dispose(this._locationSub); + this._locationSub = null; + } + }; + RootRouter = __decorate([core_1.Injectable(), __param(2, core_1.Inject(route_registry_1.ROUTER_PRIMARY_COMPONENT)), __metadata('design:paramtypes', [route_registry_1.RouteRegistry, location_1.Location, lang_1.Type])], RootRouter); + return RootRouter; + })(Router); + exports.RootRouter = RootRouter; + var ChildRouter = (function(_super) { + __extends(ChildRouter, _super); + function ChildRouter(parent, hostComponent) { + _super.call(this, parent.registry, parent, hostComponent); + this.parent = parent; + } + ChildRouter.prototype.navigateByUrl = function(url, _skipLocationChange) { + if (_skipLocationChange === void 0) { + _skipLocationChange = false; + } + return this.parent.navigateByUrl(url, _skipLocationChange); + }; + ChildRouter.prototype.navigateByInstruction = function(instruction, _skipLocationChange) { + if (_skipLocationChange === void 0) { + _skipLocationChange = false; + } + return this.parent.navigateByInstruction(instruction, _skipLocationChange); + }; + return ChildRouter; + })(Router); + function canActivateOne(nextInstruction, prevInstruction) { + var next = _resolveToTrue; + if (lang_1.isPresent(nextInstruction.child)) { + next = canActivateOne(nextInstruction.child, lang_1.isPresent(prevInstruction) ? prevInstruction.child : null); + } + return next.then(function(result) { + if (result == false) { + return false; + } + if (nextInstruction.component.reuse) { + return true; + } + var hook = route_lifecycle_reflector_1.getCanActivateHook(nextInstruction.component.componentType); + if (lang_1.isPresent(hook)) { + return hook(nextInstruction.component, lang_1.isPresent(prevInstruction) ? prevInstruction.component : null); + } + return true; + }); + } + global.define = __define; + return module.exports; +}); + +System.register("angular2/router", ["angular2/src/router/router", "angular2/src/router/router_outlet", "angular2/src/router/router_link", "angular2/src/router/instruction", "angular2/src/router/platform_location", "angular2/src/router/route_registry", "angular2/src/router/location_strategy", "angular2/src/router/hash_location_strategy", "angular2/src/router/path_location_strategy", "angular2/src/router/location", "angular2/src/router/route_config_decorator", "angular2/src/router/route_definition", "angular2/src/router/lifecycle_annotations", "angular2/src/router/instruction", "angular2/core", "angular2/src/router/platform_location", "angular2/src/router/location_strategy", "angular2/src/router/path_location_strategy", "angular2/src/router/router", "angular2/src/router/router_outlet", "angular2/src/router/router_link", "angular2/src/router/route_registry", "angular2/src/router/location", "angular2/core", "angular2/src/facade/lang", "angular2/src/facade/exceptions"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function __export(m) { + for (var p in m) + if (!exports.hasOwnProperty(p)) + exports[p] = m[p]; + } + var router_1 = require("angular2/src/router/router"); + exports.Router = router_1.Router; + var router_outlet_1 = require("angular2/src/router/router_outlet"); + exports.RouterOutlet = router_outlet_1.RouterOutlet; + var router_link_1 = require("angular2/src/router/router_link"); + exports.RouterLink = router_link_1.RouterLink; + var instruction_1 = require("angular2/src/router/instruction"); + exports.RouteParams = instruction_1.RouteParams; + exports.RouteData = instruction_1.RouteData; + var platform_location_1 = require("angular2/src/router/platform_location"); + exports.PlatformLocation = platform_location_1.PlatformLocation; + var route_registry_1 = require("angular2/src/router/route_registry"); + exports.RouteRegistry = route_registry_1.RouteRegistry; + exports.ROUTER_PRIMARY_COMPONENT = route_registry_1.ROUTER_PRIMARY_COMPONENT; + var location_strategy_1 = require("angular2/src/router/location_strategy"); + exports.LocationStrategy = location_strategy_1.LocationStrategy; + exports.APP_BASE_HREF = location_strategy_1.APP_BASE_HREF; + var hash_location_strategy_1 = require("angular2/src/router/hash_location_strategy"); + exports.HashLocationStrategy = hash_location_strategy_1.HashLocationStrategy; + var path_location_strategy_1 = require("angular2/src/router/path_location_strategy"); + exports.PathLocationStrategy = path_location_strategy_1.PathLocationStrategy; + var location_1 = require("angular2/src/router/location"); + exports.Location = location_1.Location; + __export(require("angular2/src/router/route_config_decorator")); + __export(require("angular2/src/router/route_definition")); + var lifecycle_annotations_1 = require("angular2/src/router/lifecycle_annotations"); + exports.CanActivate = lifecycle_annotations_1.CanActivate; + var instruction_2 = require("angular2/src/router/instruction"); + exports.Instruction = instruction_2.Instruction; + exports.ComponentInstruction = instruction_2.ComponentInstruction; + var core_1 = require("angular2/core"); + exports.OpaqueToken = core_1.OpaqueToken; + var platform_location_2 = require("angular2/src/router/platform_location"); + var location_strategy_2 = require("angular2/src/router/location_strategy"); + var path_location_strategy_2 = require("angular2/src/router/path_location_strategy"); + var router_2 = require("angular2/src/router/router"); + var router_outlet_2 = require("angular2/src/router/router_outlet"); + var router_link_2 = require("angular2/src/router/router_link"); + var route_registry_2 = require("angular2/src/router/route_registry"); + var location_2 = require("angular2/src/router/location"); + var core_2 = require("angular2/core"); + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + exports.ROUTER_DIRECTIVES = lang_1.CONST_EXPR([router_outlet_2.RouterOutlet, router_link_2.RouterLink]); + exports.ROUTER_PROVIDERS = lang_1.CONST_EXPR([route_registry_2.RouteRegistry, lang_1.CONST_EXPR(new core_2.Provider(location_strategy_2.LocationStrategy, {useClass: path_location_strategy_2.PathLocationStrategy})), platform_location_2.PlatformLocation, location_2.Location, lang_1.CONST_EXPR(new core_2.Provider(router_2.Router, { + useFactory: routerFactory, + deps: lang_1.CONST_EXPR([route_registry_2.RouteRegistry, location_2.Location, route_registry_2.ROUTER_PRIMARY_COMPONENT, core_2.ApplicationRef]) + })), lang_1.CONST_EXPR(new core_2.Provider(route_registry_2.ROUTER_PRIMARY_COMPONENT, { + useFactory: routerPrimaryComponentFactory, + deps: lang_1.CONST_EXPR([core_2.ApplicationRef]) + }))]); + exports.ROUTER_BINDINGS = exports.ROUTER_PROVIDERS; + function routerFactory(registry, location, primaryComponent, appRef) { + var rootRouter = new router_2.RootRouter(registry, location, primaryComponent); + appRef.registerDisposeListener(function() { + return rootRouter.dispose(); + }); + return rootRouter; + } + function routerPrimaryComponentFactory(app) { + if (app.componentTypes.length == 0) { + throw new exceptions_1.BaseException("Bootstrap at least one component before injecting Router."); + } + return app.componentTypes[0]; + } + global.define = __define; + return module.exports; +}); + +//# sourceMappingURLDisabled=router.js.map \ No newline at end of file diff --git a/testapp/ng2/lib/es6-shim/es6-shim.min.js b/testapp/ng2/lib/es6-shim/es6-shim.min.js new file mode 100644 index 000000000..17cdbfa76 --- /dev/null +++ b/testapp/ng2/lib/es6-shim/es6-shim.min.js @@ -0,0 +1,12 @@ +/*! + * https://github.com/paulmillr/es6-shim + * @license es6-shim Copyright 2013-2015 by Paul Miller (http://paulmillr.com) + * and contributors, MIT License + * es6-shim: v0.33.13 + * see https://github.com/paulmillr/es6-shim/blob/0.33.13/LICENSE + * Details and documentation: + * https://github.com/paulmillr/es6-shim/ + */ +(function(e,t){if(typeof define==="function"&&define.amd){define(t)}else if(typeof exports==="object"){module.exports=t()}else{e.returnExports=t()}})(this,function(){"use strict";var e=Function.call.bind(Function.apply);var t=Function.call.bind(Function.call);var r=Array.isArray;var n=function notThunker(t){return function notThunk(){return!e(t,this,arguments)}};var o=function(e){try{e();return false}catch(t){return true}};var i=function valueOrFalseIfThrows(e){try{return e()}catch(t){return false}};var a=n(o);var u=function(){return!o(function(){Object.defineProperty({},"x",{get:function(){}})})};var s=!!Object.defineProperty&&u();var f=function foo(){}.name==="foo";var c=Function.call.bind(Array.prototype.forEach);var l=Function.call.bind(Array.prototype.reduce);var p=Function.call.bind(Array.prototype.filter);var v=Function.call.bind(Array.prototype.some);var y=function(e,t,r,n){if(!n&&t in e){return}if(s){Object.defineProperty(e,t,{configurable:true,enumerable:false,writable:true,value:r})}else{e[t]=r}};var h=function(e,t){c(Object.keys(t),function(r){var n=t[r];y(e,r,n,false)})};var g=Object.create||function(e,t){var r=function Prototype(){};r.prototype=e;var n=new r;if(typeof t!=="undefined"){Object.keys(t).forEach(function(e){U.defineByDescriptor(n,e,t[e])})}return n};var b=function(e,t){if(!Object.setPrototypeOf){return false}return i(function(){var r=function Subclass(t){var r=new e(t);Object.setPrototypeOf(r,Subclass.prototype);return r};Object.setPrototypeOf(r,e);r.prototype=g(e.prototype,{constructor:{value:r}});return t(r)})};var d=function(){if(typeof self!=="undefined"){return self}if(typeof window!=="undefined"){return window}if(typeof global!=="undefined"){return global}throw new Error("unable to locate global object")};var m=d();var O=m.isFinite;var w=Function.call.bind(String.prototype.indexOf);var j=Function.call.bind(Object.prototype.toString);var S=Function.call.bind(Array.prototype.concat);var T=Function.call.bind(String.prototype.slice);var I=Function.call.bind(Array.prototype.push);var E=Function.apply.bind(Array.prototype.push);var M=Function.call.bind(Array.prototype.shift);var P=Math.max;var x=Math.min;var N=Math.floor;var C=Math.abs;var A=Math.log;var k=Math.sqrt;var _=Function.call.bind(Object.prototype.hasOwnProperty);var R;var F=function(){};var D=m.Symbol||{};var z=D.species||"@@species";var L=Number.isNaN||function isNaN(e){return e!==e};var q=Number.isFinite||function isFinite(e){return typeof e==="number"&&O(e)};var G=function isArguments(e){return j(e)==="[object Arguments]"};var W=function isArguments(e){return e!==null&&typeof e==="object"&&typeof e.length==="number"&&e.length>=0&&j(e)!=="[object Array]"&&j(e.callee)==="[object Function]"};var H=G(arguments)?G:W;var B={primitive:function(e){return e===null||typeof e!=="function"&&typeof e!=="object"},object:function(e){return e!==null&&typeof e==="object"},string:function(e){return j(e)==="[object String]"},regex:function(e){return j(e)==="[object RegExp]"},symbol:function(e){return typeof m.Symbol==="function"&&typeof e==="symbol"}};var $=B.symbol(D.iterator)?D.iterator:"_es6-shim iterator_";if(m.Set&&typeof(new m.Set)["@@iterator"]==="function"){$="@@iterator"}if(!m.Reflect){y(m,"Reflect",{})}var V=m.Reflect;var J={Call:function Call(t,r){var n=arguments.length>2?arguments[2]:[];if(!J.IsCallable(t)){throw new TypeError(t+" is not a function")}return e(t,r,n)},RequireObjectCoercible:function(e,t){if(e==null){throw new TypeError(t||"Cannot call method on "+e)}},TypeIsObject:function(e){return e!=null&&Object(e)===e},ToObject:function(e,t){J.RequireObjectCoercible(e,t);return Object(e)},IsCallable:function(e){return typeof e==="function"&&j(e)==="[object Function]"},IsConstructor:function(e){return J.IsCallable(e)},ToInt32:function(e){return J.ToNumber(e)>>0},ToUint32:function(e){return J.ToNumber(e)>>>0},ToNumber:function(e){if(j(e)==="[object Symbol]"){throw new TypeError("Cannot convert a Symbol value to a number")}return+e},ToInteger:function(e){var t=J.ToNumber(e);if(L(t)){return 0}if(t===0||!q(t)){return t}return(t>0?1:-1)*N(C(t))},ToLength:function(e){var t=J.ToInteger(e);if(t<=0){return 0}if(t>Number.MAX_SAFE_INTEGER){return Number.MAX_SAFE_INTEGER}return t},SameValue:function(e,t){if(e===t){if(e===0){return 1/e===1/t}return true}return L(e)&&L(t)},SameValueZero:function(e,t){return e===t||L(e)&&L(t)},IsIterable:function(e){return J.TypeIsObject(e)&&(typeof e[$]!=="undefined"||H(e))},GetIterator:function(e){if(H(e)){return new R(e,"value")}var r=J.GetMethod(e,$);if(!J.IsCallable(r)){throw new TypeError("value is not an iterable")}var n=t(r,e);if(!J.TypeIsObject(n)){throw new TypeError("bad iterator")}return n},GetMethod:function(e,t){var r=J.ToObject(e)[t];if(r===void 0||r===null){return void 0}if(!J.IsCallable(r)){throw new TypeError("Method not callable: "+t)}return r},IteratorComplete:function(e){return!!e.done},IteratorClose:function(e,r){var n=J.GetMethod(e,"return");if(n===void 0){return}var o,i;try{o=t(n,e)}catch(a){i=a}if(r){return}if(i){throw i}if(!J.TypeIsObject(o)){throw new TypeError("Iterator's return method returned a non-object.")}},IteratorNext:function(e){var t=arguments.length>1?e.next(arguments[1]):e.next();if(!J.TypeIsObject(t)){throw new TypeError("bad iterator")}return t},IteratorStep:function(e){var t=J.IteratorNext(e);var r=J.IteratorComplete(t);return r?false:t},Construct:function(e,t,r,n){var o=typeof r==="undefined"?e:r;if(!n){return V.construct(e,t,o)}var i=o.prototype;if(!J.TypeIsObject(i)){i=Object.prototype}var a=g(i);var u=J.Call(e,a,t);return J.TypeIsObject(u)?u:a},SpeciesConstructor:function(e,t){var r=e.constructor;if(r===void 0){return t}if(!J.TypeIsObject(r)){throw new TypeError("Bad constructor")}var n=r[z];if(n===void 0||n===null){return t}if(!J.IsConstructor(n)){throw new TypeError("Bad @@species")}return n},CreateHTML:function(e,t,r,n){var o=String(e);var i="<"+t;if(r!==""){var a=String(n);var u=a.replace(/"/g,""");i+=" "+r+'="'+u+'"'}var s=i+">";var f=s+o;return f+""}};var U={getter:function(e,t,r){if(!s){throw new TypeError("getters require true ES5 support")}Object.defineProperty(e,t,{configurable:true,enumerable:false,get:r})},proxy:function(e,t,r){if(!s){throw new TypeError("getters require true ES5 support")}var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,{configurable:n.configurable,enumerable:n.enumerable,get:function getKey(){return e[t]},set:function setKey(r){e[t]=r}})},redefine:function(e,t,r){if(s){var n=Object.getOwnPropertyDescriptor(e,t);n.value=r;Object.defineProperty(e,t,n)}else{e[t]=r}},defineByDescriptor:function(e,t,r){if(s){Object.defineProperty(e,t,r)}else if("value"in r){e[t]=r.value}},preserveToString:function(e,t){if(t&&J.IsCallable(t.toString)){y(e,"toString",t.toString.bind(t),true)}}};var K=function wrapConstructor(e,t,r){U.preserveToString(t,e);if(Object.setPrototypeOf){Object.setPrototypeOf(e,t)}if(s){c(Object.getOwnPropertyNames(e),function(n){if(n in F||r[n]){return}U.proxy(e,n,t)})}else{c(Object.keys(e),function(n){if(n in F||r[n]){return}t[n]=e[n]})}t.prototype=e.prototype;U.redefine(e.prototype,"constructor",t)};var X=function(){return this};var Z=function(e){if(s&&!_(e,z)){U.getter(e,z,X)}};var Q=function overrideNative(e,t,r){var n=e[t];y(e,t,r,true);U.preserveToString(e[t],n)};var Y=function(e,t){var r=t||function iterator(){return this};y(e,$,r);if(!e[$]&&B.symbol($)){e[$]=r}};var ee=function createDataProperty(e,t,r){if(s){Object.defineProperty(e,t,{configurable:true,enumerable:true,writable:true,value:r})}else{e[t]=r}};var te=function createDataPropertyOrThrow(e,t,r){ee(e,t,r);if(!J.SameValue(e[t],r)){throw new TypeError("property is nonconfigurable")}};var re=function(e,t,r,n){if(!J.TypeIsObject(e)){throw new TypeError("Constructor requires `new`: "+t.name)}var o=t.prototype;if(!J.TypeIsObject(o)){o=r}var i=g(o);for(var a in n){if(_(n,a)){var u=n[a];y(i,a,u,true)}}return i};if(String.fromCodePoint&&String.fromCodePoint.length!==1){var ne=String.fromCodePoint;Q(String,"fromCodePoint",function fromCodePoint(t){return e(ne,this,arguments)})}var oe={fromCodePoint:function fromCodePoint(e){var t=[];var r;for(var n=0,o=arguments.length;n1114111){throw new RangeError("Invalid code point "+r)}if(r<65536){I(t,String.fromCharCode(r))}else{r-=65536;I(t,String.fromCharCode((r>>10)+55296));I(t,String.fromCharCode(r%1024+56320))}}return t.join("")},raw:function raw(e){var t=J.ToObject(e,"bad callSite");var r=J.ToObject(t.raw,"bad raw value");var n=r.length;var o=J.ToLength(n);if(o<=0){return""}var i=[];var a=0;var u,s,f,c;while(a=o){break}s=a+1=ae){throw new RangeError("repeat count must be less than infinity and not overflow maximum string size")}return ie(t,r)},startsWith:function startsWith(e){J.RequireObjectCoercible(this);var t=String(this);if(B.regex(e)){throw new TypeError('Cannot call method "startsWith" with a regex')}var r=String(e);var n=arguments.length>1?arguments[1]:void 0;var o=P(J.ToInteger(n),0);return T(t,o,o+r.length)===r},endsWith:function endsWith(e){J.RequireObjectCoercible(this);var t=String(this);if(B.regex(e)){throw new TypeError('Cannot call method "endsWith" with a regex')}var r=String(e);var n=t.length;var o=arguments.length>1?arguments[1]:void 0;var i=typeof o==="undefined"?n:J.ToInteger(o);var a=x(P(i,0),n);return T(t,a-r.length,a)===r},includes:function includes(e){if(B.regex(e)){throw new TypeError('"includes" does not accept a RegExp')}var t;if(arguments.length>1){t=arguments[1]}return w(this,e,t)!==-1},codePointAt:function codePointAt(e){J.RequireObjectCoercible(this);var t=String(this);var r=J.ToInteger(e);var n=t.length;if(r>=0&&r56319||i){return o}var a=t.charCodeAt(r+1);if(a<56320||a>57343){return o}return(o-55296)*1024+(a-56320)+65536}}};if(String.prototype.includes&&"a".includes("a",Infinity)!==false){Q(String.prototype,"includes",ue.includes)}if(String.prototype.startsWith&&String.prototype.endsWith){var se=o(function(){"/a/".startsWith(/a/)});var fe="abc".startsWith("a",Infinity)===false;if(!se||!fe){Q(String.prototype,"startsWith",ue.startsWith);Q(String.prototype,"endsWith",ue.endsWith)}}h(String.prototype,ue);var ce=[" \n\x0B\f\r \xa0\u1680\u180e\u2000\u2001\u2002\u2003","\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028","\u2029\ufeff"].join("");var le=new RegExp("(^["+ce+"]+)|(["+ce+"]+$)","g");var pe=function trim(){if(typeof this==="undefined"||this===null){throw new TypeError("can't convert "+this+" to object")}return String(this).replace(le,"")};var ve=["\x85","\u200b","\ufffe"].join("");var ye=new RegExp("["+ve+"]","g");var he=/^[\-+]0x[0-9a-f]+$/i;var ge=ve.trim().length!==ve.length;y(String.prototype,"trim",pe,ge);var be=function(e){J.RequireObjectCoercible(e);this._s=String(e);this._i=0};be.prototype.next=function(){var e=this._s,t=this._i;if(typeof e==="undefined"||t>=e.length){this._s=void 0;return{value:void 0,done:true}}var r=e.charCodeAt(t),n,o;if(r<55296||r>56319||t+1===e.length){o=1}else{n=e.charCodeAt(t+1);o=n<56320||n>57343?1:2}this._i=t+o;return{value:e.substr(t,o),done:false}};Y(be.prototype);Y(String.prototype,function(){return new be(this)});var de={from:function from(e){var r=this;var n=arguments.length>1?arguments[1]:void 0;var o,i;if(n===void 0){o=false}else{if(!J.IsCallable(n)){throw new TypeError("Array.from: when provided, the second argument must be a function")}i=arguments.length>2?arguments[2]:void 0;o=true}var a=typeof(H(e)||J.GetMethod(e,$))!=="undefined";var u,s,f;if(a){s=J.IsConstructor(r)?Object(new r):[];var c=J.GetIterator(e);var l,p;f=0;while(true){l=J.IteratorStep(c);if(l===false){break}p=l.value;try{if(o){p=i===undefined?n(p,f):t(n,i,p,f)}s[f]=p}catch(v){J.IteratorClose(c,true);throw v}f+=1}u=f}else{var y=J.ToObject(e);u=J.ToLength(y.length);s=J.IsConstructor(r)?Object(new r(u)):new Array(u);var h;for(f=0;f0){e=M(t);if(!(e in this.object)){continue}if(this.kind==="key"){return me(e)}else if(this.kind==="value"){return me(this.object[e])}else{return me([e,this.object[e]])}}return me()}});Y(we.prototype);var je=Array.of===de.of||function(){var e=function Foo(e){this.length=e};e.prototype=[];var t=Array.of.apply(e,[1,2]);return t instanceof e&&t.length===2}();if(!je){Q(Array,"of",de.of)}var Se={copyWithin:function copyWithin(e,t){var r=arguments[2];var n=J.ToObject(this);var o=J.ToLength(n.length);var i=J.ToInteger(e);var a=J.ToInteger(t);var u=i<0?P(o+i,0):x(i,o);var s=a<0?P(o+a,0):x(a,o);r=typeof r==="undefined"?o:J.ToInteger(r);var f=r<0?P(o+r,0):x(r,o);var c=x(f-s,o-u);var l=1;if(s0){if(_(n,s)){n[u]=n[s]}else{delete n[s]}s+=l;u+=l;c-=1}return n},fill:function fill(e){var t=arguments.length>1?arguments[1]:void 0;var r=arguments.length>2?arguments[2]:void 0;var n=J.ToObject(this);var o=J.ToLength(n.length);t=J.ToInteger(typeof t==="undefined"?0:t);r=J.ToInteger(typeof r==="undefined"?o:r);var i=t<0?P(o+t,0):x(t,o);var a=r<0?o+r:r;for(var u=i;u1?arguments[1]:null;for(var i=0,a;i1?arguments[1]:null;for(var i=0;i0&&typeof arguments[1]!=="undefined"){return e(Pe,this,arguments)}else{return t(Pe,this,r)}})}var xe=function(e,r){var n={length:-1};n[r?(-1>>>0)-1:0]=true;return i(function(){t(e,n,function(){throw new RangeError("should not reach here")},[])})};if(!xe(Array.prototype.forEach)){var Ne=Array.prototype.forEach;Q(Array.prototype,"forEach",function forEach(t){return e(Ne,this.length>=0?this:[],arguments)},true)}if(!xe(Array.prototype.map)){var Ce=Array.prototype.map;Q(Array.prototype,"map",function map(t){return e(Ce,this.length>=0?this:[],arguments)},true)}if(!xe(Array.prototype.filter)){var Ae=Array.prototype.filter;Q(Array.prototype,"filter",function filter(t){return e(Ae,this.length>=0?this:[],arguments)},true)}if(!xe(Array.prototype.some)){var ke=Array.prototype.some;Q(Array.prototype,"some",function some(t){return e(ke,this.length>=0?this:[],arguments)},true)}if(!xe(Array.prototype.every)){var _e=Array.prototype.every;Q(Array.prototype,"every",function every(t){return e(_e,this.length>=0?this:[],arguments)},true)}if(!xe(Array.prototype.reduce)){var Re=Array.prototype.reduce;Q(Array.prototype,"reduce",function reduce(t){return e(Re,this.length>=0?this:[],arguments)},true)}if(!xe(Array.prototype.reduceRight,true)){var Fe=Array.prototype.reduceRight;Q(Array.prototype,"reduceRight",function reduceRight(t){return e(Fe,this.length>=0?this:[],arguments)},true)}var De=Number("0o10")!==8;var ze=Number("0b10")!==2;var Le=v(ve,function(e){return Number(e+0+e)===0});if(De||ze||Le){var qe=Number;var Ge=/^0b[01]+$/i;var We=/^0o[0-7]+$/i;var He=Ge.test.bind(Ge);var Be=We.test.bind(We);var $e=function(e){var t;if(typeof e.valueOf==="function"){t=e.valueOf();if(B.primitive(t)){return t}}if(typeof e.toString==="function"){t=e.toString();if(B.primitive(t)){return t}}throw new TypeError("No default value")};var Ve=ye.test.bind(ye);var Je=he.test.bind(he);var Ue=function(){var e=function Number(r){var n;if(arguments.length>0){n=B.primitive(r)?r:$e(r,"number")}else{n=0}if(typeof n==="string"){n=t(pe,n);if(He(n)){n=parseInt(T(n,2),2)}else if(Be(n)){n=parseInt(T(n,2),8)}else if(Ve(n)||Je(n)){n=NaN}}var o=this;var a=i(function(){qe.prototype.valueOf.call(o);return true});if(o instanceof e&&!a){return new qe(n)}return qe(n)};return e}();K(qe,Ue,{});Number=Ue;U.redefine(m,"Number",Ue)}var Ke=Math.pow(2,53)-1;h(Number,{MAX_SAFE_INTEGER:Ke,MIN_SAFE_INTEGER:-Ke,EPSILON:2.220446049250313e-16,parseInt:m.parseInt,parseFloat:m.parseFloat,isFinite:q,isInteger:function isInteger(e){return q(e)&&J.ToInteger(e)===e},isSafeInteger:function isSafeInteger(e){return Number.isInteger(e)&&C(e)<=Number.MAX_SAFE_INTEGER},isNaN:L});y(Number,"parseInt",m.parseInt,Number.parseInt!==m.parseInt);if(![,1].find(function(e,t){return t===0})){Q(Array.prototype,"find",Se.find)}if([,1].findIndex(function(e,t){return t===0})!==0){Q(Array.prototype,"findIndex",Se.findIndex)}var Xe=Function.bind.call(Function.bind,Object.prototype.propertyIsEnumerable);var Ze=function sliceArgs(){var e=Number(this);var t=arguments.length;var r=t-e;var n=new Array(r<0?0:r);for(var o=e;o1){return NaN}if(t===-1){return-Infinity}if(t===1){return Infinity}if(t===0){return t}return.5*A((1+t)/(1-t))},cbrt:function cbrt(e){var t=Number(e);if(t===0){return t}var r=t<0,n;if(r){t=-t}if(t===Infinity){n=Infinity}else{n=Math.exp(A(t)/3);n=(t/(n*n)+2*n)/3}return r?-n:n},clz32:function clz32(e){var r=Number(e);var n=J.ToUint32(r);if(n===0){return 32}return Rt?t(Rt,n):31-N(A(n+.5)*Math.LOG2E)},cosh:function cosh(e){var t=Number(e);if(t===0){return 1}if(Number.isNaN(t)){return NaN}if(!O(t)){return Infinity}if(t<0){t=-t}if(t>21){return Math.exp(t)/2}return(Math.exp(t)+Math.exp(-t))/2},expm1:function expm1(e){var t=Number(e);if(t===-Infinity){return-1}if(!O(t)||t===0){return t}if(C(t)>.5){return Math.exp(t)-1}var r=t;var n=0;var o=1;while(n+r!==n){n+=r;o+=1;r*=t/o}return n},hypot:function hypot(e,t){var r=0;var n=0;for(var o=0;o0?i/n*(i/n):i}}return n===Infinity?Infinity:n*k(r)},log2:function log2(e){return A(e)*Math.LOG2E},log10:function log10(e){return A(e)*Math.LOG10E},log1p:function log1p(e){var t=Number(e);if(t<-1||Number.isNaN(t)){return NaN}if(t===0||t===Infinity){return t}if(t===-1){return-Infinity}return 1+t-1===0?t:t*(A(1+t)/(1+t-1))},sign:function sign(e){var t=Number(e);if(t===0){return t}if(Number.isNaN(t)){return t}return t<0?-1:1},sinh:function sinh(e){var t=Number(e);if(!O(t)||t===0){return t}if(C(t)<1){return(Math.expm1(t)-Math.expm1(-t))/2}return(Math.exp(t-1)-Math.exp(-t-1))*Math.E/2},tanh:function tanh(e){var t=Number(e);if(Number.isNaN(t)||t===0){return t}if(t===Infinity){return 1}if(t===-Infinity){return-1}var r=Math.expm1(t);var n=Math.expm1(-t);if(r===Infinity){return 1}if(n===Infinity){return-1}return(r-n)/(Math.exp(t)+Math.exp(-t))},trunc:function trunc(e){var t=Number(e);return t<0?-N(-t):N(t)},imul:function imul(e,t){var r=J.ToUint32(e);var n=J.ToUint32(t);var o=r>>>16&65535;var i=r&65535;var a=n>>>16&65535;var u=n&65535;return i*u+(o*u+i*a<<16>>>0)|0},fround:function fround(e){var t=Number(e);if(t===0||t===Infinity||t===-Infinity||L(t)){return t}var r=Math.sign(t);var n=C(t);if(n<_t){return r*Ct(n/_t/At)*_t*At}var o=(1+At/Number.EPSILON)*n;var i=o-(o-n);if(i>kt||L(i)){return r*Infinity}return r*i}};h(Math,Ft);y(Math,"log1p",Ft.log1p,Math.log1p(-1e-17)!==-1e-17);y(Math,"asinh",Ft.asinh,Math.asinh(-1e7)!==-Math.asinh(1e7));y(Math,"tanh",Ft.tanh,Math.tanh(-2e-17)!==-2e-17);y(Math,"acosh",Ft.acosh,Math.acosh(Number.MAX_VALUE)===Infinity);y(Math,"cbrt",Ft.cbrt,Math.abs(1-Math.cbrt(1e-300)/1e-100)/Number.EPSILON>8);y(Math,"sinh",Ft.sinh,Math.sinh(-2e-17)!==-2e-17);var Dt=Math.expm1(10);y(Math,"expm1",Ft.expm1,Dt>22025.465794806718||Dt<22025.465794806718);var zt=Math.round;var Lt=Math.round(.5-Number.EPSILON/4)===0&&Math.round(-.5+Number.EPSILON/3.99)===1;var qt=Nt+1;var Gt=2*Nt-1;var Wt=[qt,Gt].every(function(e){return Math.round(e)===e});y(Math,"round",function round(e){var t=N(e);var r=t===-1?-0:t+1;return e-t<.5?t:r},!Lt||!Wt);U.preserveToString(Math.round,zt);var Ht=Math.imul;if(Math.imul(4294967295,5)!==-5){Math.imul=Ft.imul;U.preserveToString(Math.imul,Ht)}if(Math.imul.length!==2){Q(Math,"imul",function imul(t,r){return e(Ht,Math,arguments)})}var Bt=function(){var e=m.setTimeout;if(typeof e!=="function"&&typeof e!=="object"){return}J.IsPromise=function(e){if(!J.TypeIsObject(e)){return false}if(typeof e._promise==="undefined"){return false}return true};var r=function(e){if(!J.IsConstructor(e)){throw new TypeError("Bad promise constructor")}var t=this;var r=function(e,r){if(t.resolve!==void 0||t.reject!==void 0){throw new TypeError("Bad Promise implementation!")}t.resolve=e;t.reject=r};t.promise=new e(r);if(!(J.IsCallable(t.resolve)&&J.IsCallable(t.reject))){throw new TypeError("Bad promise constructor")}};var n;if(typeof window!=="undefined"&&J.IsCallable(window.postMessage)){n=function(){var e=[];var t="zero-timeout-message";var r=function(r){I(e,r);window.postMessage(t,"*")};var n=function(r){if(r.source===window&&r.data===t){r.stopPropagation();if(e.length===0){return}var n=M(e);n()}};window.addEventListener("message",n,true);return r}}var o=function(){var e=m.Promise;return e&&e.resolve&&function(t){return e.resolve().then(t)}};var i=J.IsCallable(m.setImmediate)?m.setImmediate.bind(m):typeof process==="object"&&process.nextTick?process.nextTick:o()||(J.IsCallable(n)?n():function(t){e(t,0)});var a=1;var u=2;var s=3;var f=4;var l=5;var p=function(e,t){var r=e.capabilities;var n=e.handler;var o,i=false,s;if(n===a){o=t}else if(n===u){o=t;i=true}else{try{o=n(t)}catch(f){o=f;i=true}}s=i?r.reject:r.resolve;s(o)};var v=function(e,t){c(e,function(e){i(function(){p(e,t)})})};var y=function(e,t){var r=e._promise;var n=r.fulfillReactions;r.result=t;r.fulfillReactions=void 0;r.rejectReactions=void 0;r.state=f;v(n,t)};var g=function(e,t){var r=e._promise;var n=r.rejectReactions;r.result=t;r.fulfillReactions=void 0;r.rejectReactions=void 0;r.state=l;v(n,t)};var b=function(e){var t=false;var r=function(r){var n;if(t){return}t=true;if(r===e){return g(e,new TypeError("Self resolution"))}if(!J.TypeIsObject(r)){return y(e,r)}try{n=r.then}catch(o){return g(e,o)}if(!J.IsCallable(n)){return y(e,r)}i(function(){d(e,r,n)})};var n=function(r){if(t){return}t=true;return g(e,r)};return{resolve:r,reject:n}};var d=function(e,r,n){var o=b(e);var i=o.resolve;var a=o.reject;try{t(n,r,i,a)}catch(u){a(u)}};var O=function(e){if(!J.TypeIsObject(e)){throw new TypeError("Promise is not object")}var t=e[z];if(t!==void 0&&t!==null){return t}return e};var w;var j=function(){var e=function Promise(t){if(!(this instanceof e)){throw new TypeError('Constructor Promise requires "new"')}if(this&&this._promise){throw new TypeError("Bad construction")}if(!J.IsCallable(t)){throw new TypeError("not a valid resolver")}var r=re(this,e,w,{_promise:{result:void 0,state:s,fulfillReactions:[],rejectReactions:[]}});var n=b(r);var o=n.reject;try{t(n.resolve,o)}catch(i){o(i)}return r};return e}();w=j.prototype;var S=function(e,t,r,n){var o=false;return function(i){if(o){return}o=true;t[e]=i;if(--n.count===0){var a=r.resolve;a(t)}}};var T=function(e,t,r){var n=e.iterator;var o=[],i={count:1},a,u;var s=0;while(true){try{a=J.IteratorStep(n);if(a===false){e.done=true;break}u=a.value}catch(f){e.done=true;throw f}o[s]=void 0;var c=t.resolve(u);var l=S(s,o,r,i);i.count+=1;c.then(l,r.reject);s+=1}if(--i.count===0){var p=r.resolve;p(o)}return r.promise};var E=function(e,t,r){var n=e.iterator,o,i,a;while(true){try{o=J.IteratorStep(n);if(o===false){e.done=true;break}i=o.value}catch(u){e.done=true;throw u}a=t.resolve(i);a.then(r.resolve,r.reject)}return r.promise};h(j,{all:function all(e){var t=O(this);var n=new r(t);var o,i;try{o=J.GetIterator(e);i={iterator:o,done:false};return T(i,t,n)}catch(a){var u=a;if(i&&!i.done){try{J.IteratorClose(o,true)}catch(s){u=s}}var f=n.reject;f(u);return n.promise}},race:function race(e){var t=O(this);var n=new r(t);var o,i;try{o=J.GetIterator(e);i={iterator:o,done:false};return E(i,t,n)}catch(a){var u=a;if(i&&!i.done){try{J.IteratorClose(o,true)}catch(s){u=s}}var f=n.reject;f(u);return n.promise}},reject:function reject(e){ +var t=this;var n=new r(t);var o=n.reject;o(e);return n.promise},resolve:function resolve(e){var t=this;if(J.IsPromise(e)){var n=e.constructor;if(n===t){return e}}var o=new r(t);var i=o.resolve;i(e);return o.promise}});h(w,{"catch":function(e){return this.then(void 0,e)},then:function then(e,t){var n=this;if(!J.IsPromise(n)){throw new TypeError("not a promise")}var o=J.SpeciesConstructor(n,j);var c=new r(o);var v={capabilities:c,handler:J.IsCallable(e)?e:a};var y={capabilities:c,handler:J.IsCallable(t)?t:u};var h=n._promise;var g;if(h.state===s){I(h.fulfillReactions,v);I(h.rejectReactions,y)}else if(h.state===f){g=h.result;i(function(){p(v,g)})}else if(h.state===l){g=h.result;i(function(){p(y,g)})}else{throw new TypeError("unexpected Promise state")}return c.promise}});return j}();if(m.Promise){delete m.Promise.accept;delete m.Promise.defer;delete m.Promise.prototype.chain}if(typeof Bt==="function"){h(m,{Promise:Bt});var $t=b(m.Promise,function(e){return e.resolve(42).then(function(){})instanceof e});var Vt=!o(function(){m.Promise.reject(42).then(null,5).then(null,F)});var Jt=o(function(){m.Promise.call(3,F)});var Ut=function(e){var t=e.resolve(5);t.constructor={};var r=e.resolve(t);return t===r}(m.Promise);if(!$t||!Vt||!Jt||Ut){Promise=Bt;Q(m,"Promise",Bt)}Z(Promise)}var Kt=function(e){var t=Object.keys(l(e,function(e,t){e[t]=true;return e},{}));return e.join(":")===t.join(":")};var Xt=Kt(["z","a","bb"]);var Zt=Kt(["z",1,"a","3",2]);if(s){var Qt=function fastkey(e){if(!Xt){return null}var t=typeof e;if(t==="undefined"||e===null){return"^"+String(e)}else if(t==="string"){return"$"+e}else if(t==="number"){if(!Zt){return"n"+e}return e}else if(t==="boolean"){return"b"+e}return null};var Yt=function emptyObject(){return Object.create?Object.create(null):{}};var er=function addIterableToMap(e,n,o){if(r(o)||B.string(o)){c(o,function(e){n.set(e[0],e[1])})}else if(o instanceof e){t(e.prototype.forEach,o,function(e,t){n.set(t,e)})}else{var i,a;if(o!==null&&typeof o!=="undefined"){a=n.set;if(!J.IsCallable(a)){throw new TypeError("bad map")}i=J.GetIterator(o)}if(typeof i!=="undefined"){while(true){var u=J.IteratorStep(i);if(u===false){break}var s=u.value;try{if(!J.TypeIsObject(s)){throw new TypeError("expected iterable of pairs")}t(a,n,s[0],s[1])}catch(f){J.IteratorClose(i,true);throw f}}}}};var tr=function addIterableToSet(e,n,o){if(r(o)||B.string(o)){c(o,function(e){n.add(e)})}else if(o instanceof e){t(e.prototype.forEach,o,function(e){n.add(e)})}else{var i,a;if(o!==null&&typeof o!=="undefined"){a=n.add;if(!J.IsCallable(a)){throw new TypeError("bad set")}i=J.GetIterator(o)}if(typeof i!=="undefined"){while(true){var u=J.IteratorStep(i);if(u===false){break}var s=u.value;try{t(a,n,s)}catch(f){J.IteratorClose(i,true);throw f}}}}};var rr={Map:function(){var e={};var r=function MapEntry(e,t){this.key=e;this.value=t;this.next=null;this.prev=null};r.prototype.isRemoved=function isRemoved(){return this.key===e};var n=function isMap(e){return!!e._es6map};var o=function requireMapSlot(e,t){if(!J.TypeIsObject(e)||!n(e)){throw new TypeError("Method Map.prototype."+t+" called on incompatible receiver "+String(e))}};var i=function MapIterator(e,t){o(e,"[[MapIterator]]");this.head=e._head;this.i=this.head;this.kind=t};i.prototype={next:function next(){var e=this.i,t=this.kind,r=this.head,n;if(typeof this.i==="undefined"){return{value:void 0,done:true}}while(e.isRemoved()&&e!==r){e=e.prev}while(e.next!==r){e=e.next;if(!e.isRemoved()){if(t==="key"){n=e.key}else if(t==="value"){n=e.value}else{n=[e.key,e.value]}this.i=e;return{value:n,done:false}}}this.i=void 0;return{value:void 0,done:true}}};Y(i.prototype);var a;var u=function Map(){if(!(this instanceof Map)){throw new TypeError('Constructor Map requires "new"')}if(this&&this._es6map){throw new TypeError("Bad construction")}var e=re(this,Map,a,{_es6map:true,_head:null,_storage:Yt(),_size:0});var t=new r(null,null);t.next=t.prev=t;e._head=t;if(arguments.length>0){er(Map,e,arguments[0])}return e};a=u.prototype;U.getter(a,"size",function(){if(typeof this._size==="undefined"){throw new TypeError("size method called on incompatible Map")}return this._size});h(a,{get:function get(e){o(this,"get");var t=Qt(e);if(t!==null){var r=this._storage[t];if(r){return r.value}else{return}}var n=this._head,i=n;while((i=i.next)!==n){if(J.SameValueZero(i.key,e)){return i.value}}},has:function has(e){o(this,"has");var t=Qt(e);if(t!==null){return typeof this._storage[t]!=="undefined"}var r=this._head,n=r;while((n=n.next)!==r){if(J.SameValueZero(n.key,e)){return true}}return false},set:function set(e,t){o(this,"set");var n=this._head,i=n,a;var u=Qt(e);if(u!==null){if(typeof this._storage[u]!=="undefined"){this._storage[u].value=t;return this}else{a=this._storage[u]=new r(e,t);i=n.prev}}while((i=i.next)!==n){if(J.SameValueZero(i.key,e)){i.value=t;return this}}a=a||new r(e,t);if(J.SameValue(-0,e)){a.key=+0}a.next=this._head;a.prev=this._head.prev;a.prev.next=a;a.next.prev=a;this._size+=1;return this},"delete":function(t){o(this,"delete");var r=this._head,n=r;var i=Qt(t);if(i!==null){if(typeof this._storage[i]==="undefined"){return false}n=this._storage[i].prev;delete this._storage[i]}while((n=n.next)!==r){if(J.SameValueZero(n.key,t)){n.key=n.value=e;n.prev.next=n.next;n.next.prev=n.prev;this._size-=1;return true}}return false},clear:function clear(){o(this,"clear");this._size=0;this._storage=Yt();var t=this._head,r=t,n=r.next;while((r=n)!==t){r.key=r.value=e;n=r.next;r.next=r.prev=t}t.next=t.prev=t},keys:function keys(){o(this,"keys");return new i(this,"key")},values:function values(){o(this,"values");return new i(this,"value")},entries:function entries(){o(this,"entries");return new i(this,"key+value")},forEach:function forEach(e){o(this,"forEach");var r=arguments.length>1?arguments[1]:null;var n=this.entries();for(var i=n.next();!i.done;i=n.next()){if(r){t(e,r,i.value[1],i.value[0],this)}else{e(i.value[1],i.value[0],this)}}}});Y(a,a.entries);return u}(),Set:function(){var e=function isSet(e){return e._es6set&&typeof e._storage!=="undefined"};var r=function requireSetSlot(t,r){if(!J.TypeIsObject(t)||!e(t)){throw new TypeError("Set.prototype."+r+" called on incompatible receiver "+String(t))}};var n;var o=function Set(){if(!(this instanceof Set)){throw new TypeError('Constructor Set requires "new"')}if(this&&this._es6set){throw new TypeError("Bad construction")}var e=re(this,Set,n,{_es6set:true,"[[SetData]]":null,_storage:Yt()});if(!e._es6set){throw new TypeError("bad set")}if(arguments.length>0){tr(Set,e,arguments[0])}return e};n=o.prototype;var i=function ensureMap(e){if(!e["[[SetData]]"]){var t=e["[[SetData]]"]=new rr.Map;c(Object.keys(e._storage),function(e){var r=e;if(r==="^null"){r=null}else if(r==="^undefined"){r=void 0}else{var n=r.charAt(0);if(n==="$"){r=T(r,1)}else if(n==="n"){r=+T(r,1)}else if(n==="b"){r=r==="btrue"}else{r=+r}}t.set(r,r)});e._storage=null}};U.getter(o.prototype,"size",function(){r(this,"size");i(this);return this["[[SetData]]"].size});h(o.prototype,{has:function has(e){r(this,"has");var t;if(this._storage&&(t=Qt(e))!==null){return!!this._storage[t]}i(this);return this["[[SetData]]"].has(e)},add:function add(e){r(this,"add");var t;if(this._storage&&(t=Qt(e))!==null){this._storage[t]=true;return this}i(this);this["[[SetData]]"].set(e,e);return this},"delete":function(e){r(this,"delete");var t;if(this._storage&&(t=Qt(e))!==null){var n=_(this._storage,t);return delete this._storage[t]&&n}i(this);return this["[[SetData]]"]["delete"](e)},clear:function clear(){r(this,"clear");if(this._storage){this._storage=Yt()}else{this["[[SetData]]"].clear()}},values:function values(){r(this,"values");i(this);return this["[[SetData]]"].values()},entries:function entries(){r(this,"entries");i(this);return this["[[SetData]]"].entries()},forEach:function forEach(e){r(this,"forEach");var n=arguments.length>1?arguments[1]:null;var o=this;i(o);this["[[SetData]]"].forEach(function(r,i){if(n){t(e,n,i,i,o)}else{e(i,i,o)}})}});y(o.prototype,"keys",o.prototype.values,true);Y(o.prototype,o.prototype.values);return o}()};if(m.Map||m.Set){var nr=i(function(){return new Map([[1,2]]).get(1)===2});if(!nr){var or=m.Map;m.Map=function Map(){if(!(this instanceof Map)){throw new TypeError('Constructor Map requires "new"')}var e=new or;if(arguments.length>0){er(Map,e,arguments[0])}Object.setPrototypeOf(e,m.Map.prototype);y(e,"constructor",Map,true);return e};m.Map.prototype=g(or.prototype);U.preserveToString(m.Map,or)}var ir=new Map;var ar=function(e){e["delete"](0);e["delete"](-0);e.set(0,3);e.get(-0,4);return e.get(0)===3&&e.get(-0)===4}(ir);var ur=ir.set(1,2)===ir;if(!ar||!ur){var sr=Map.prototype.set;Q(Map.prototype,"set",function set(e,r){t(sr,this,e===0?0:e,r);return this})}if(!ar){var fr=Map.prototype.get;var cr=Map.prototype.has;h(Map.prototype,{get:function get(e){return t(fr,this,e===0?0:e)},has:function has(e){return t(cr,this,e===0?0:e)}},true);U.preserveToString(Map.prototype.get,fr);U.preserveToString(Map.prototype.has,cr)}var lr=new Set;var pr=function(e){e["delete"](0);e.add(-0);return!e.has(0)}(lr);var vr=lr.add(1)===lr;if(!pr||!vr){var yr=Set.prototype.add;Set.prototype.add=function add(e){t(yr,this,e===0?0:e);return this};U.preserveToString(Set.prototype.add,yr)}if(!pr){var hr=Set.prototype.has;Set.prototype.has=function has(e){return t(hr,this,e===0?0:e)};U.preserveToString(Set.prototype.has,hr);var gr=Set.prototype["delete"];Set.prototype["delete"]=function SetDelete(e){return t(gr,this,e===0?0:e)};U.preserveToString(Set.prototype["delete"],gr)}var br=b(m.Map,function(e){var t=new e([]);t.set(42,42);return t instanceof e});var dr=Object.setPrototypeOf&&!br;var mr=function(){try{return!(m.Map()instanceof m.Map)}catch(e){return e instanceof TypeError}}();if(m.Map.length!==0||dr||!mr){var Or=m.Map;m.Map=function Map(){if(!(this instanceof Map)){throw new TypeError('Constructor Map requires "new"')}var e=new Or;if(arguments.length>0){er(Map,e,arguments[0])}Object.setPrototypeOf(e,Map.prototype);y(e,"constructor",Map,true);return e};m.Map.prototype=Or.prototype;U.preserveToString(m.Map,Or)}var wr=b(m.Set,function(e){var t=new e([]);t.add(42,42);return t instanceof e});var jr=Object.setPrototypeOf&&!wr;var Sr=function(){try{return!(m.Set()instanceof m.Set)}catch(e){return e instanceof TypeError}}();if(m.Set.length!==0||jr||!Sr){var Tr=m.Set;m.Set=function Set(){if(!(this instanceof Set)){throw new TypeError('Constructor Set requires "new"')}var e=new Tr;if(arguments.length>0){tr(Set,e,arguments[0])}Object.setPrototypeOf(e,Set.prototype);y(e,"constructor",Set,true);return e};m.Set.prototype=Tr.prototype;U.preserveToString(m.Set,Tr)}var Ir=!i(function(){return(new Map).keys().next().done});if(typeof m.Map.prototype.clear!=="function"||(new m.Set).size!==0||(new m.Map).size!==0||typeof m.Map.prototype.keys!=="function"||typeof m.Set.prototype.keys!=="function"||typeof m.Map.prototype.forEach!=="function"||typeof m.Set.prototype.forEach!=="function"||a(m.Map)||a(m.Set)||typeof(new m.Map).keys().next!=="function"||Ir||!br){delete m.Map;delete m.Set;h(m,{Map:rr.Map,Set:rr.Set},true)}if(m.Set.prototype.keys!==m.Set.prototype.values){y(m.Set.prototype,"keys",m.Set.prototype.values,true)}Y(Object.getPrototypeOf((new m.Map).keys()));Y(Object.getPrototypeOf((new m.Set).keys()));if(f&&m.Set.prototype.has.name!=="has"){var Er=m.Set.prototype.has;Q(m.Set.prototype,"has",function has(e){return t(Er,this,e)})}}h(m,rr);Z(m.Map);Z(m.Set)}var Mr=function throwUnlessTargetIsObject(e){if(!J.TypeIsObject(e)){throw new TypeError("target must be an object")}};var Pr={apply:function apply(){return e(J.Call,null,arguments)},construct:function construct(e,t){if(!J.IsConstructor(e)){throw new TypeError("First argument must be a constructor.")}var r=arguments.length<3?e:arguments[2];if(!J.IsConstructor(r)){throw new TypeError("new.target must be a constructor.")}return J.Construct(e,t,r,"internal")},deleteProperty:function deleteProperty(e,t){Mr(e);if(s){var r=Object.getOwnPropertyDescriptor(e,t);if(r&&!r.configurable){return false}}return delete e[t]},enumerate:function enumerate(e){Mr(e);return new we(e,"key")},has:function has(e,t){Mr(e);return t in e}};if(Object.getOwnPropertyNames){Object.assign(Pr,{ownKeys:function ownKeys(e){Mr(e);var t=Object.getOwnPropertyNames(e);if(J.IsCallable(Object.getOwnPropertySymbols)){E(t,Object.getOwnPropertySymbols(e))}return t}})}var xr=function ConvertExceptionToBoolean(e){return!o(e)};if(Object.preventExtensions){Object.assign(Pr,{isExtensible:function isExtensible(e){Mr(e);return Object.isExtensible(e)},preventExtensions:function preventExtensions(e){Mr(e);return xr(function(){Object.preventExtensions(e)})}})}if(s){var Nr=function get(e,r,n){var o=Object.getOwnPropertyDescriptor(e,r);if(!o){var i=Object.getPrototypeOf(e);if(i===null){return undefined}return Nr(i,r,n)}if("value"in o){return o.value}if(o.get){return t(o.get,n)}return undefined};var Cr=function set(e,r,n,o){var i=Object.getOwnPropertyDescriptor(e,r);if(!i){var a=Object.getPrototypeOf(e);if(a!==null){return Cr(a,r,n,o)}i={value:void 0,writable:true,enumerable:true,configurable:true}}if("value"in i){if(!i.writable){return false}if(!J.TypeIsObject(o)){return false}var u=Object.getOwnPropertyDescriptor(o,r);if(u){return V.defineProperty(o,r,{value:n})}else{return V.defineProperty(o,r,{value:n,writable:true,enumerable:true,configurable:true})}}if(i.set){t(i.set,o,n);return true}return false};Object.assign(Pr,{defineProperty:function defineProperty(e,t,r){Mr(e);return xr(function(){Object.defineProperty(e,t,r)})},getOwnPropertyDescriptor:function getOwnPropertyDescriptor(e,t){Mr(e);return Object.getOwnPropertyDescriptor(e,t)},get:function get(e,t){Mr(e);var r=arguments.length>2?arguments[2]:e;return Nr(e,t,r)},set:function set(e,t,r){Mr(e);var n=arguments.length>3?arguments[3]:e;return Cr(e,t,r,n)}})}if(Object.getPrototypeOf){var Ar=Object.getPrototypeOf;Pr.getPrototypeOf=function getPrototypeOf(e){Mr(e);return Ar(e)}}if(Object.setPrototypeOf&&Pr.getPrototypeOf){var kr=function(e,t){var r=t;while(r){if(e===r){return true}r=Pr.getPrototypeOf(r)}return false};Object.assign(Pr,{setPrototypeOf:function setPrototypeOf(e,t){Mr(e);if(t!==null&&!J.TypeIsObject(t)){throw new TypeError("proto must be an object or null")}if(t===V.getPrototypeOf(e)){return true}if(V.isExtensible&&!V.isExtensible(e)){return false}if(kr(e,t)){return false}Object.setPrototypeOf(e,t);return true}})}var _r=function(e,t){if(!J.IsCallable(m.Reflect[e])){y(m.Reflect,e,t)}else{var r=i(function(){m.Reflect[e](1);m.Reflect[e](NaN);m.Reflect[e](true);return true});if(r){Q(m.Reflect,e,t)}}};Object.keys(Pr).forEach(function(e){_r(e,Pr[e])});if(f&&m.Reflect.getPrototypeOf.name!=="getPrototypeOf"){var Rr=m.Reflect.getPrototypeOf;Q(m.Reflect,"getPrototypeOf",function getPrototypeOf(e){return t(Rr,m.Reflect,e)})}if(m.Reflect.setPrototypeOf){if(i(function(){m.Reflect.setPrototypeOf(1,{});return true})){Q(m.Reflect,"setPrototypeOf",Pr.setPrototypeOf)}}if(m.Reflect.defineProperty){if(!i(function(){var e=!m.Reflect.defineProperty(1,"test",{value:1});var t=typeof Object.preventExtensions!=="function"||!m.Reflect.defineProperty(Object.preventExtensions({}),"test",{});return e&&t})){Q(m.Reflect,"defineProperty",Pr.defineProperty)}}if(m.Reflect.construct){if(!i(function(){var e=function F(){};return m.Reflect.construct(function(){},[],e)instanceof e})){Q(m.Reflect,"construct",Pr.construct)}}if(String(new Date(NaN))!=="Invalid Date"){var Fr=Date.prototype.toString;var Dr=function toString(){var e=+this;if(e!==e){return"Invalid Date"}return t(Fr,this)};Q(Date.prototype,"toString",Dr)}var zr={anchor:function anchor(e){return J.CreateHTML(this,"a","name",e)},big:function big(){return J.CreateHTML(this,"big","","")},blink:function blink(){return J.CreateHTML(this,"blink","","")},bold:function bold(){return J.CreateHTML(this,"b","","")},fixed:function fixed(){return J.CreateHTML(this,"tt","","")},fontcolor:function fontcolor(e){return J.CreateHTML(this,"font","color",e)},fontsize:function fontsize(e){return J.CreateHTML(this,"font","size",e)},italics:function italics(){return J.CreateHTML(this,"i","","")},link:function link(e){return J.CreateHTML(this,"a","href",e)},small:function small(){return J.CreateHTML(this,"small","","")},strike:function strike(){return J.CreateHTML(this,"strike","","")},sub:function sub(){return J.CreateHTML(this,"sub","","")},sup:function sub(){return J.CreateHTML(this,"sup","","")}};c(Object.keys(zr),function(e){var r=String.prototype[e];var n=false;if(J.IsCallable(r)){var o=t(r,"",' " ');var i=S([],o.match(/"/g)).length;n=o!==o.toLowerCase()||i>2}else{n=true}if(n){Q(String.prototype,e,zr[e])}});var Lr=function(){if(!B.symbol(D.iterator)){return false}var e=typeof JSON==="object"&&typeof JSON.stringify==="function"?JSON.stringify:null;if(!e){return false}if(typeof e(D())!=="undefined"){return true}if(e([D()])!=="[null]"){return true}var t={a:D()};t[D()]=true;if(e(t)!=="{}"){return true}return false}();var qr=i(function(){if(!B.symbol(D.iterator)){return true}return JSON.stringify(Object(D()))==="{}"&&JSON.stringify([Object(D())])==="[{}]"});if(Lr||!qr){var Gr=JSON.stringify;Q(JSON,"stringify",function stringify(e){if(typeof e==="symbol"){return}var n;if(arguments.length>1){n=arguments[1]}var o=[e];if(!r(n)){var i=J.IsCallable(n)?n:null;var a=function(e,r){var o=n?t(n,this,e,r):r;if(typeof o!=="symbol"){if(B.symbol(o)){return Qe({})(o)}else{return o}}};o.push(a)}else{o.push(n)}if(arguments.length>2){o.push(arguments[2])}return Gr.apply(this,o)})}return m}); +//# sourceMappingURL=es6-shim.map diff --git a/testapp/ng2/lib/rxjs/bundles/Rx.js b/testapp/ng2/lib/rxjs/bundles/Rx.js new file mode 100644 index 000000000..befc0c746 --- /dev/null +++ b/testapp/ng2/lib/rxjs/bundles/Rx.js @@ -0,0 +1,10218 @@ +"format register"; +System.register("rxjs/util/noop", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function noop() {} + exports.noop = noop; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/throwError", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function throwError(e) { + throw e; + } + exports.throwError = throwError; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/tryOrOnError", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function tryOrOnError(target) { + function tryCatcher() { + try { + tryCatcher.target.apply(this, arguments); + } catch (e) { + this.error(e); + } + } + tryCatcher.target = target; + return tryCatcher; + } + exports.tryOrOnError = tryOrOnError; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/Subscription", ["rxjs/util/noop"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var noop_1 = require("rxjs/util/noop"); + var Subscription = (function() { + function Subscription(_unsubscribe) { + this.isUnsubscribed = false; + if (_unsubscribe) { + this._unsubscribe = _unsubscribe; + } + } + Subscription.prototype._unsubscribe = function() { + noop_1.noop(); + }; + Subscription.prototype.unsubscribe = function() { + if (this.isUnsubscribed) { + return ; + } + this.isUnsubscribed = true; + var unsubscribe = this._unsubscribe; + var subscriptions = this._subscriptions; + this._subscriptions = void 0; + if (unsubscribe) { + unsubscribe.call(this); + } + if (subscriptions != null) { + var index = -1; + var len = subscriptions.length; + while (++index < len) { + subscriptions[index].unsubscribe(); + } + } + }; + Subscription.prototype.add = function(subscription) { + if (!subscription || (subscription === this) || (subscription === Subscription.EMPTY)) { + return ; + } + var sub = subscription; + switch (typeof subscription) { + case 'function': + sub = new Subscription(subscription); + case 'object': + if (sub.isUnsubscribed || typeof sub.unsubscribe !== 'function') { + break; + } else if (this.isUnsubscribed) { + sub.unsubscribe(); + } else { + var subscriptions = this._subscriptions || (this._subscriptions = []); + subscriptions.push(sub); + } + break; + default: + throw new Error('Unrecognized subscription ' + subscription + ' added to Subscription.'); + } + }; + Subscription.prototype.remove = function(subscription) { + if (subscription == null || (subscription === this) || (subscription === Subscription.EMPTY)) { + return ; + } + var subscriptions = this._subscriptions; + if (subscriptions) { + var subscriptionIndex = subscriptions.indexOf(subscription); + if (subscriptionIndex !== -1) { + subscriptions.splice(subscriptionIndex, 1); + } + } + }; + Subscription.EMPTY = (function(empty) { + empty.isUnsubscribed = true; + return empty; + }(new Subscription())); + return Subscription; + })(); + exports.Subscription = Subscription; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/root", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + exports.root = (objectTypes[typeof self] && self) || (objectTypes[typeof window] && window); + var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; + var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; + var freeGlobal = objectTypes[typeof global] && global; + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + exports.root = freeGlobal; + } + global.define = __define; + return module.exports; +}); + +System.register("rxjs/subject/SubjectSubscription", ["rxjs/Subscription", "rxjs/Subscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscription_1 = require("rxjs/Subscription"); + var Subscriber_1 = require("rxjs/Subscriber"); + var SubjectSubscription = (function(_super) { + __extends(SubjectSubscription, _super); + function SubjectSubscription(subject, observer) { + _super.call(this); + this.subject = subject; + this.observer = observer; + this.isUnsubscribed = false; + } + SubjectSubscription.prototype.unsubscribe = function() { + if (this.isUnsubscribed) { + return ; + } + this.isUnsubscribed = true; + var subject = this.subject; + var observers = subject.observers; + this.subject = void 0; + if (!observers || observers.length === 0 || subject.isUnsubscribed) { + return ; + } + if (this.observer instanceof Subscriber_1.Subscriber) { + this.observer.unsubscribe(); + } + var subscriberIndex = observers.indexOf(this.observer); + if (subscriberIndex !== -1) { + observers.splice(subscriberIndex, 1); + } + }; + return SubjectSubscription; + })(Subscription_1.Subscription); + exports.SubjectSubscription = SubjectSubscription; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/errorObject", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + exports.errorObject = {e: {}}; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/throw", ["rxjs/Observable"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Observable_1 = require("rxjs/Observable"); + var ErrorObservable = (function(_super) { + __extends(ErrorObservable, _super); + function ErrorObservable(error, scheduler) { + _super.call(this); + this.error = error; + this.scheduler = scheduler; + } + ErrorObservable.create = function(error, scheduler) { + return new ErrorObservable(error, scheduler); + }; + ErrorObservable.dispatch = function(_a) { + var error = _a.error, + subscriber = _a.subscriber; + subscriber.error(error); + }; + ErrorObservable.prototype._subscribe = function(subscriber) { + var error = this.error; + var scheduler = this.scheduler; + if (scheduler) { + subscriber.add(scheduler.schedule(ErrorObservable.dispatch, 0, { + error: error, + subscriber: subscriber + })); + } else { + subscriber.error(error); + } + }; + return ErrorObservable; + })(Observable_1.Observable); + exports.ErrorObservable = ErrorObservable; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/empty", ["rxjs/Observable"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Observable_1 = require("rxjs/Observable"); + var EmptyObservable = (function(_super) { + __extends(EmptyObservable, _super); + function EmptyObservable(scheduler) { + _super.call(this); + this.scheduler = scheduler; + } + EmptyObservable.create = function(scheduler) { + return new EmptyObservable(scheduler); + }; + EmptyObservable.dispatch = function(_a) { + var subscriber = _a.subscriber; + subscriber.complete(); + }; + EmptyObservable.prototype._subscribe = function(subscriber) { + var scheduler = this.scheduler; + if (scheduler) { + subscriber.add(scheduler.schedule(EmptyObservable.dispatch, 0, {subscriber: subscriber})); + } else { + subscriber.complete(); + } + }; + return EmptyObservable; + })(Observable_1.Observable); + exports.EmptyObservable = EmptyObservable; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/isScheduler", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function isScheduler(value) { + return value && typeof value.schedule === 'function'; + } + exports.isScheduler = isScheduler; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/OuterSubscriber", ["rxjs/Subscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var OuterSubscriber = (function(_super) { + __extends(OuterSubscriber, _super); + function OuterSubscriber() { + _super.apply(this, arguments); + } + OuterSubscriber.prototype.notifyComplete = function(inner) { + this.destination.complete(); + }; + OuterSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex) { + this.destination.next(innerValue); + }; + OuterSubscriber.prototype.notifyError = function(error, inner) { + this.destination.error(error); + }; + return OuterSubscriber; + })(Subscriber_1.Subscriber); + exports.OuterSubscriber = OuterSubscriber; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/InnerSubscriber", ["rxjs/Subscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var InnerSubscriber = (function(_super) { + __extends(InnerSubscriber, _super); + function InnerSubscriber(parent, outerValue, outerIndex) { + _super.call(this); + this.parent = parent; + this.outerValue = outerValue; + this.outerIndex = outerIndex; + this.index = 0; + } + InnerSubscriber.prototype._next = function(value) { + var index = this.index++; + this.parent.notifyNext(this.outerValue, value, this.outerIndex, index); + }; + InnerSubscriber.prototype._error = function(error) { + this.parent.notifyError(error, this); + }; + InnerSubscriber.prototype._complete = function() { + this.parent.notifyComplete(this); + }; + return InnerSubscriber; + })(Subscriber_1.Subscriber); + exports.InnerSubscriber = InnerSubscriber; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/isArray", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + exports.isArray = Array.isArray || (function(x) { + return x && typeof x.length === 'number'; + }); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/scheduler/QueueAction", ["rxjs/Subscription"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscription_1 = require("rxjs/Subscription"); + var QueueAction = (function(_super) { + __extends(QueueAction, _super); + function QueueAction(scheduler, work) { + _super.call(this); + this.scheduler = scheduler; + this.work = work; + } + QueueAction.prototype.schedule = function(state) { + if (this.isUnsubscribed) { + return this; + } + this.state = state; + var scheduler = this.scheduler; + scheduler.actions.push(this); + scheduler.flush(); + return this; + }; + QueueAction.prototype.execute = function() { + if (this.isUnsubscribed) { + throw new Error('How did did we execute a canceled Action?'); + } + this.work(this.state); + }; + QueueAction.prototype.unsubscribe = function() { + var scheduler = this.scheduler; + var actions = scheduler.actions; + var index = actions.indexOf(this); + this.work = void 0; + this.state = void 0; + this.scheduler = void 0; + if (index !== -1) { + actions.splice(index, 1); + } + _super.prototype.unsubscribe.call(this); + }; + return QueueAction; + })(Subscription_1.Subscription); + exports.QueueAction = QueueAction; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/scheduler/FutureAction", ["rxjs/scheduler/QueueAction"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var QueueAction_1 = require("rxjs/scheduler/QueueAction"); + var FutureAction = (function(_super) { + __extends(FutureAction, _super); + function FutureAction(scheduler, work) { + _super.call(this, scheduler, work); + this.scheduler = scheduler; + this.work = work; + } + FutureAction.prototype.schedule = function(state, delay) { + var _this = this; + if (delay === void 0) { + delay = 0; + } + if (this.isUnsubscribed) { + return this; + } + this.delay = delay; + this.state = state; + var id = this.id; + if (id != null) { + this.id = undefined; + clearTimeout(id); + } + var scheduler = this.scheduler; + this.id = setTimeout(function() { + _this.id = void 0; + scheduler.actions.push(_this); + scheduler.flush(); + }, this.delay); + return this; + }; + FutureAction.prototype.unsubscribe = function() { + var id = this.id; + if (id != null) { + this.id = void 0; + clearTimeout(id); + } + _super.prototype.unsubscribe.call(this); + }; + return FutureAction; + })(QueueAction_1.QueueAction); + exports.FutureAction = FutureAction; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/mergeAll-support", ["rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); + var MergeAllOperator = (function() { + function MergeAllOperator(concurrent) { + this.concurrent = concurrent; + } + MergeAllOperator.prototype.call = function(observer) { + return new MergeAllSubscriber(observer, this.concurrent); + }; + return MergeAllOperator; + })(); + exports.MergeAllOperator = MergeAllOperator; + var MergeAllSubscriber = (function(_super) { + __extends(MergeAllSubscriber, _super); + function MergeAllSubscriber(destination, concurrent) { + _super.call(this, destination); + this.concurrent = concurrent; + this.hasCompleted = false; + this.buffer = []; + this.active = 0; + } + MergeAllSubscriber.prototype._next = function(observable) { + if (this.active < this.concurrent) { + if (observable._isScalar) { + this.destination.next(observable.value); + } else { + this.active++; + this.add(subscribeToResult_1.subscribeToResult(this, observable)); + } + } else { + this.buffer.push(observable); + } + }; + MergeAllSubscriber.prototype._complete = function() { + this.hasCompleted = true; + if (this.active === 0 && this.buffer.length === 0) { + this.destination.complete(); + } + }; + MergeAllSubscriber.prototype.notifyComplete = function(innerSub) { + var buffer = this.buffer; + this.remove(innerSub); + this.active--; + if (buffer.length > 0) { + this._next(buffer.shift()); + } else if (this.active === 0 && this.hasCompleted) { + this.destination.complete(); + } + }; + return MergeAllSubscriber; + })(OuterSubscriber_1.OuterSubscriber); + exports.MergeAllSubscriber = MergeAllSubscriber; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/merge-static", ["rxjs/observable/fromArray", "rxjs/operator/mergeAll-support", "rxjs/scheduler/queue", "rxjs/util/isScheduler"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var fromArray_1 = require("rxjs/observable/fromArray"); + var mergeAll_support_1 = require("rxjs/operator/mergeAll-support"); + var queue_1 = require("rxjs/scheduler/queue"); + var isScheduler_1 = require("rxjs/util/isScheduler"); + function merge() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; + } + var concurrent = Number.POSITIVE_INFINITY; + var scheduler = queue_1.queue; + var last = observables[observables.length - 1]; + if (isScheduler_1.isScheduler(last)) { + scheduler = observables.pop(); + if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') { + concurrent = observables.pop(); + } + } else if (typeof last === 'number') { + concurrent = observables.pop(); + } + if (observables.length === 1) { + return observables[0]; + } + return new fromArray_1.ArrayObservable(observables, scheduler).lift(new mergeAll_support_1.MergeAllOperator(concurrent)); + } + exports.merge = merge; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/subject/AsyncSubject", ["rxjs/Subject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subject_1 = require("rxjs/Subject"); + var AsyncSubject = (function(_super) { + __extends(AsyncSubject, _super); + function AsyncSubject() { + _super.call(this); + this._value = void 0; + this._hasNext = false; + this._isScalar = false; + } + AsyncSubject.prototype._subscribe = function(subscriber) { + if (this.completeSignal && this._hasNext) { + subscriber.next(this._value); + } + return _super.prototype._subscribe.call(this, subscriber); + }; + AsyncSubject.prototype._next = function(value) { + this._value = value; + this._hasNext = true; + }; + AsyncSubject.prototype._complete = function() { + var index = -1; + var observers = this.observers; + var len = observers.length; + this.observers = void 0; + this.isUnsubscribed = true; + if (this._hasNext) { + while (++index < len) { + var o = observers[index]; + o.next(this._value); + o.complete(); + } + } else { + while (++index < len) { + observers[index].complete(); + } + } + this.isUnsubscribed = false; + }; + return AsyncSubject; + })(Subject_1.Subject); + exports.AsyncSubject = AsyncSubject; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/defer", ["rxjs/Observable", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Observable_1 = require("rxjs/Observable"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + var DeferObservable = (function(_super) { + __extends(DeferObservable, _super); + function DeferObservable(observableFactory) { + _super.call(this); + this.observableFactory = observableFactory; + } + DeferObservable.create = function(observableFactory) { + return new DeferObservable(observableFactory); + }; + DeferObservable.prototype._subscribe = function(subscriber) { + var result = tryCatch_1.tryCatch(this.observableFactory)(); + if (result === errorObject_1.errorObject) { + subscriber.error(errorObject_1.errorObject.e); + } else { + result.subscribe(subscriber); + } + }; + return DeferObservable; + })(Observable_1.Observable); + exports.DeferObservable = DeferObservable; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/observable/empty", ["rxjs/Observable", "rxjs/observable/empty"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var empty_1 = require("rxjs/observable/empty"); + Observable_1.Observable.empty = empty_1.EmptyObservable.create; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/fromPromise", ["rxjs/Observable", "rxjs/Subscription", "rxjs/scheduler/queue"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Observable_1 = require("rxjs/Observable"); + var Subscription_1 = require("rxjs/Subscription"); + var queue_1 = require("rxjs/scheduler/queue"); + var PromiseObservable = (function(_super) { + __extends(PromiseObservable, _super); + function PromiseObservable(promise, scheduler) { + if (scheduler === void 0) { + scheduler = queue_1.queue; + } + _super.call(this); + this.promise = promise; + this.scheduler = scheduler; + this._isScalar = false; + } + PromiseObservable.create = function(promise, scheduler) { + if (scheduler === void 0) { + scheduler = queue_1.queue; + } + return new PromiseObservable(promise, scheduler); + }; + PromiseObservable.prototype._subscribe = function(subscriber) { + var _this = this; + var scheduler = this.scheduler; + var promise = this.promise; + if (scheduler === queue_1.queue) { + if (this._isScalar) { + subscriber.next(this.value); + subscriber.complete(); + } else { + promise.then(function(value) { + _this._isScalar = true; + _this.value = value; + subscriber.next(value); + subscriber.complete(); + }, function(err) { + return subscriber.error(err); + }).then(null, function(err) { + setTimeout(function() { + throw err; + }); + }); + } + } else { + var subscription = new Subscription_1.Subscription(); + if (this._isScalar) { + var value = this.value; + subscription.add(scheduler.schedule(dispatchNext, 0, { + value: value, + subscriber: subscriber + })); + } else { + promise.then(function(value) { + _this._isScalar = true; + _this.value = value; + subscription.add(scheduler.schedule(dispatchNext, 0, { + value: value, + subscriber: subscriber + })); + }, function(err) { + return subscription.add(scheduler.schedule(dispatchError, 0, { + err: err, + subscriber: subscriber + })); + }).then(null, function(err) { + scheduler.schedule(function() { + throw err; + }); + }); + } + return subscription; + } + }; + return PromiseObservable; + })(Observable_1.Observable); + exports.PromiseObservable = PromiseObservable; + function dispatchNext(_a) { + var value = _a.value, + subscriber = _a.subscriber; + subscriber.next(value); + subscriber.complete(); + } + function dispatchError(_a) { + var err = _a.err, + subscriber = _a.subscriber; + subscriber.error(err); + } + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/isPromise", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function isPromise(value) { + return value && typeof value.subscribe !== 'function' && typeof value.then === 'function'; + } + exports.isPromise = isPromise; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/IteratorObservable", ["rxjs/Observable", "rxjs/util/root", "rxjs/util/SymbolShim", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Observable_1 = require("rxjs/Observable"); + var root_1 = require("rxjs/util/root"); + var SymbolShim_1 = require("rxjs/util/SymbolShim"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + var IteratorObservable = (function(_super) { + __extends(IteratorObservable, _super); + function IteratorObservable(iterator, project, thisArg, scheduler) { + _super.call(this); + this.project = project; + this.thisArg = thisArg; + this.scheduler = scheduler; + if (iterator == null) { + throw new Error('iterator cannot be null.'); + } + if (project && typeof project !== 'function') { + throw new Error('When provided, `project` must be a function.'); + } + this.iterator = getIterator(iterator); + } + IteratorObservable.create = function(iterator, project, thisArg, scheduler) { + return new IteratorObservable(iterator, project, thisArg, scheduler); + }; + IteratorObservable.dispatch = function(state) { + var index = state.index, + hasError = state.hasError, + thisArg = state.thisArg, + project = state.project, + iterator = state.iterator, + subscriber = state.subscriber; + if (hasError) { + subscriber.error(state.error); + return ; + } + var result = iterator.next(); + if (result.done) { + subscriber.complete(); + return ; + } + if (project) { + result = tryCatch_1.tryCatch(project).call(thisArg, result.value, index); + if (result === errorObject_1.errorObject) { + state.error = errorObject_1.errorObject.e; + state.hasError = true; + } else { + subscriber.next(result); + state.index = index + 1; + } + } else { + subscriber.next(result.value); + state.index = index + 1; + } + if (subscriber.isUnsubscribed) { + return ; + } + this.schedule(state); + }; + IteratorObservable.prototype._subscribe = function(subscriber) { + var index = 0; + var _a = this, + iterator = _a.iterator, + project = _a.project, + thisArg = _a.thisArg, + scheduler = _a.scheduler; + if (scheduler) { + subscriber.add(scheduler.schedule(IteratorObservable.dispatch, 0, { + index: index, + thisArg: thisArg, + project: project, + iterator: iterator, + subscriber: subscriber + })); + } else { + do { + var result = iterator.next(); + if (result.done) { + subscriber.complete(); + break; + } else if (project) { + result = tryCatch_1.tryCatch(project).call(thisArg, result.value, index++); + if (result === errorObject_1.errorObject) { + subscriber.error(errorObject_1.errorObject.e); + break; + } + subscriber.next(result); + } else { + subscriber.next(result.value); + } + if (subscriber.isUnsubscribed) { + break; + } + } while (true); + } + }; + return IteratorObservable; + })(Observable_1.Observable); + exports.IteratorObservable = IteratorObservable; + var StringIterator = (function() { + function StringIterator(str, idx, len) { + if (idx === void 0) { + idx = 0; + } + if (len === void 0) { + len = str.length; + } + this.str = str; + this.idx = idx; + this.len = len; + } + StringIterator.prototype[SymbolShim_1.SymbolShim.iterator] = function() { + return (this); + }; + StringIterator.prototype.next = function() { + return this.idx < this.len ? { + done: false, + value: this.str.charAt(this.idx++) + } : { + done: true, + value: undefined + }; + }; + return StringIterator; + })(); + var ArrayIterator = (function() { + function ArrayIterator(arr, idx, len) { + if (idx === void 0) { + idx = 0; + } + if (len === void 0) { + len = toLength(arr); + } + this.arr = arr; + this.idx = idx; + this.len = len; + } + ArrayIterator.prototype[SymbolShim_1.SymbolShim.iterator] = function() { + return this; + }; + ArrayIterator.prototype.next = function() { + return this.idx < this.len ? { + done: false, + value: this.arr[this.idx++] + } : { + done: true, + value: undefined + }; + }; + return ArrayIterator; + })(); + function getIterator(obj) { + var i = obj[SymbolShim_1.SymbolShim.iterator]; + if (!i && typeof obj === 'string') { + return new StringIterator(obj); + } + if (!i && obj.length !== undefined) { + return new ArrayIterator(obj); + } + if (!i) { + throw new TypeError('Object is not iterable'); + } + return obj[SymbolShim_1.SymbolShim.iterator](); + } + var maxSafeInteger = Math.pow(2, 53) - 1; + function toLength(o) { + var len = +o.length; + if (isNaN(len)) { + return 0; + } + if (len === 0 || !numberIsFinite(len)) { + return len; + } + len = sign(len) * Math.floor(Math.abs(len)); + if (len <= 0) { + return 0; + } + if (len > maxSafeInteger) { + return maxSafeInteger; + } + return len; + } + function numberIsFinite(value) { + return typeof value === 'number' && root_1.root.isFinite(value); + } + function sign(value) { + var valueAsNumber = +value; + if (valueAsNumber === 0) { + return valueAsNumber; + } + if (isNaN(valueAsNumber)) { + return valueAsNumber; + } + return valueAsNumber < 0 ? -1 : 1; + } + global.define = __define; + return module.exports; +}); + +System.register("rxjs/Notification", ["rxjs/Observable"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var Notification = (function() { + function Notification(kind, value, exception) { + this.kind = kind; + this.value = value; + this.exception = exception; + this.hasValue = kind === 'N'; + } + Notification.prototype.observe = function(observer) { + switch (this.kind) { + case 'N': + return observer.next(this.value); + case 'E': + return observer.error(this.exception); + case 'C': + return observer.complete(); + } + }; + Notification.prototype.do = function(next, error, complete) { + var kind = this.kind; + switch (kind) { + case 'N': + return next(this.value); + case 'E': + return error(this.exception); + case 'C': + return complete(); + } + }; + Notification.prototype.accept = function(nextOrObserver, error, complete) { + if (nextOrObserver && typeof nextOrObserver.next === 'function') { + return this.observe(nextOrObserver); + } else { + return this.do(nextOrObserver, error, complete); + } + }; + Notification.prototype.toObservable = function() { + var kind = this.kind; + switch (kind) { + case 'N': + return Observable_1.Observable.of(this.value); + case 'E': + return Observable_1.Observable.throw(this.exception); + case 'C': + return Observable_1.Observable.empty(); + } + }; + Notification.createNext = function(value) { + if (typeof value !== 'undefined') { + return new Notification('N', value); + } + return this.undefinedValueNotification; + }; + Notification.createError = function(err) { + return new Notification('E', undefined, err); + }; + Notification.createComplete = function() { + return this.completeNotification; + }; + Notification.completeNotification = new Notification('C'); + Notification.undefinedValueNotification = new Notification('N', undefined); + return Notification; + })(); + exports.Notification = Notification; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/observable/fromArray", ["rxjs/Observable", "rxjs/observable/fromArray"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var fromArray_1 = require("rxjs/observable/fromArray"); + Observable_1.Observable.fromArray = fromArray_1.ArrayObservable.create; + Observable_1.Observable.of = fromArray_1.ArrayObservable.of; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/fromEvent", ["rxjs/Observable", "rxjs/util/tryCatch", "rxjs/util/errorObject", "rxjs/Subscription"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Observable_1 = require("rxjs/Observable"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + var Subscription_1 = require("rxjs/Subscription"); + var FromEventObservable = (function(_super) { + __extends(FromEventObservable, _super); + function FromEventObservable(sourceObj, eventName, selector) { + _super.call(this); + this.sourceObj = sourceObj; + this.eventName = eventName; + this.selector = selector; + } + FromEventObservable.create = function(sourceObj, eventName, selector) { + return new FromEventObservable(sourceObj, eventName, selector); + }; + FromEventObservable.setupSubscription = function(sourceObj, eventName, handler, subscriber) { + var unsubscribe; + var tag = sourceObj.toString(); + if (tag === '[object NodeList]' || tag === '[object HTMLCollection]') { + for (var i = 0, + len = sourceObj.length; i < len; i++) { + FromEventObservable.setupSubscription(sourceObj[i], eventName, handler, subscriber); + } + } else if (typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function') { + sourceObj.addEventListener(eventName, handler); + unsubscribe = function() { + return sourceObj.removeEventListener(eventName, handler); + }; + } else if (typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function') { + sourceObj.on(eventName, handler); + unsubscribe = function() { + return sourceObj.off(eventName, handler); + }; + } else if (typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function') { + sourceObj.addListener(eventName, handler); + unsubscribe = function() { + return sourceObj.removeListener(eventName, handler); + }; + } + subscriber.add(new Subscription_1.Subscription(unsubscribe)); + }; + FromEventObservable.prototype._subscribe = function(subscriber) { + var sourceObj = this.sourceObj; + var eventName = this.eventName; + var selector = this.selector; + var handler = selector ? function(e) { + var result = tryCatch_1.tryCatch(selector)(e); + if (result === errorObject_1.errorObject) { + subscriber.error(result.e); + } else { + subscriber.next(result); + } + } : function(e) { + return subscriber.next(e); + }; + FromEventObservable.setupSubscription(sourceObj, eventName, handler, subscriber); + }; + return FromEventObservable; + })(Observable_1.Observable); + exports.FromEventObservable = FromEventObservable; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/fromEventPattern", ["rxjs/Observable", "rxjs/Subscription", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Observable_1 = require("rxjs/Observable"); + var Subscription_1 = require("rxjs/Subscription"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + var FromEventPatternObservable = (function(_super) { + __extends(FromEventPatternObservable, _super); + function FromEventPatternObservable(addHandler, removeHandler, selector) { + _super.call(this); + this.addHandler = addHandler; + this.removeHandler = removeHandler; + this.selector = selector; + } + FromEventPatternObservable.create = function(addHandler, removeHandler, selector) { + return new FromEventPatternObservable(addHandler, removeHandler, selector); + }; + FromEventPatternObservable.prototype._subscribe = function(subscriber) { + var addHandler = this.addHandler; + var removeHandler = this.removeHandler; + var selector = this.selector; + var handler = selector ? function(e) { + var result = tryCatch_1.tryCatch(selector).apply(null, arguments); + if (result === errorObject_1.errorObject) { + subscriber.error(result.e); + } else { + subscriber.next(result); + } + } : function(e) { + subscriber.next(e); + }; + var result = tryCatch_1.tryCatch(addHandler)(handler); + if (result === errorObject_1.errorObject) { + subscriber.error(result.e); + } + subscriber.add(new Subscription_1.Subscription(function() { + removeHandler(handler); + })); + }; + return FromEventPatternObservable; + })(Observable_1.Observable); + exports.FromEventPatternObservable = FromEventPatternObservable; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/observable/fromPromise", ["rxjs/Observable", "rxjs/observable/fromPromise"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var fromPromise_1 = require("rxjs/observable/fromPromise"); + Observable_1.Observable.fromPromise = fromPromise_1.PromiseObservable.create; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/isNumeric", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var is_array = Array.isArray; + function isNumeric(val) { + return !is_array(val) && (val - parseFloat(val) + 1) >= 0; + } + exports.isNumeric = isNumeric; + ; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/Immediate", ["rxjs/util/root"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var root_1 = require("rxjs/util/root"); + var ImmediateDefinition = (function() { + function ImmediateDefinition(root) { + this.root = root; + if (root.setImmediate) { + this.setImmediate = root.setImmediate; + this.clearImmediate = root.clearImmediate; + } else { + this.nextHandle = 1; + this.tasksByHandle = {}; + this.currentlyRunningATask = false; + if (this.canUseProcessNextTick()) { + this.setImmediate = this.createProcessNextTickSetImmediate(); + } else if (this.canUsePostMessage()) { + this.setImmediate = this.createPostMessageSetImmediate(); + } else if (this.canUseMessageChannel()) { + this.setImmediate = this.createMessageChannelSetImmediate(); + } else if (this.canUseReadyStateChange()) { + this.setImmediate = this.createReadyStateChangeSetImmediate(); + } else { + this.setImmediate = this.createSetTimeoutSetImmediate(); + } + var ci = function clearImmediate(handle) { + delete clearImmediate.instance.tasksByHandle[handle]; + }; + ci.instance = this; + this.clearImmediate = ci; + } + } + ImmediateDefinition.prototype.identify = function(o) { + return this.root.Object.prototype.toString.call(o); + }; + ImmediateDefinition.prototype.canUseProcessNextTick = function() { + return this.identify(this.root.process) === '[object process]'; + }; + ImmediateDefinition.prototype.canUseMessageChannel = function() { + return Boolean(this.root.MessageChannel); + }; + ImmediateDefinition.prototype.canUseReadyStateChange = function() { + var document = this.root.document; + return Boolean(document && 'onreadystatechange' in document.createElement('script')); + }; + ImmediateDefinition.prototype.canUsePostMessage = function() { + var root = this.root; + if (root.postMessage && !root.importScripts) { + var postMessageIsAsynchronous = true; + var oldOnMessage = root.onmessage; + root.onmessage = function() { + postMessageIsAsynchronous = false; + }; + root.postMessage('', '*'); + root.onmessage = oldOnMessage; + return postMessageIsAsynchronous; + } + return false; + }; + ImmediateDefinition.prototype.partiallyApplied = function(handler) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + var fn = function result() { + var _a = result, + handler = _a.handler, + args = _a.args; + if (typeof handler === 'function') { + handler.apply(undefined, args); + } else { + (new Function('' + handler))(); + } + }; + fn.handler = handler; + fn.args = args; + return fn; + }; + ImmediateDefinition.prototype.addFromSetImmediateArguments = function(args) { + this.tasksByHandle[this.nextHandle] = this.partiallyApplied.apply(undefined, args); + return this.nextHandle++; + }; + ImmediateDefinition.prototype.createProcessNextTickSetImmediate = function() { + var fn = function setImmediate() { + var instance = setImmediate.instance; + var handle = instance.addFromSetImmediateArguments(arguments); + instance.root.process.nextTick(instance.partiallyApplied(instance.runIfPresent, handle)); + return handle; + }; + fn.instance = this; + return fn; + }; + ImmediateDefinition.prototype.createPostMessageSetImmediate = function() { + var root = this.root; + var messagePrefix = 'setImmediate$' + root.Math.random() + '$'; + var onGlobalMessage = function globalMessageHandler(event) { + var instance = globalMessageHandler.instance; + if (event.source === root && typeof event.data === 'string' && event.data.indexOf(messagePrefix) === 0) { + instance.runIfPresent(+event.data.slice(messagePrefix.length)); + } + }; + onGlobalMessage.instance = this; + root.addEventListener('message', onGlobalMessage, false); + var fn = function setImmediate() { + var _a = setImmediate, + messagePrefix = _a.messagePrefix, + instance = _a.instance; + var handle = instance.addFromSetImmediateArguments(arguments); + instance.root.postMessage(messagePrefix + handle, '*'); + return handle; + }; + fn.instance = this; + fn.messagePrefix = messagePrefix; + return fn; + }; + ImmediateDefinition.prototype.runIfPresent = function(handle) { + if (this.currentlyRunningATask) { + this.root.setTimeout(this.partiallyApplied(this.runIfPresent, handle), 0); + } else { + var task = this.tasksByHandle[handle]; + if (task) { + this.currentlyRunningATask = true; + try { + task(); + } finally { + this.clearImmediate(handle); + this.currentlyRunningATask = false; + } + } + } + }; + ImmediateDefinition.prototype.createMessageChannelSetImmediate = function() { + var _this = this; + var channel = new this.root.MessageChannel(); + channel.port1.onmessage = function(event) { + var handle = event.data; + _this.runIfPresent(handle); + }; + var fn = function setImmediate() { + var _a = setImmediate, + channel = _a.channel, + instance = _a.instance; + var handle = instance.addFromSetImmediateArguments(arguments); + channel.port2.postMessage(handle); + return handle; + }; + fn.channel = channel; + fn.instance = this; + return fn; + }; + ImmediateDefinition.prototype.createReadyStateChangeSetImmediate = function() { + var fn = function setImmediate() { + var instance = setImmediate.instance; + var root = instance.root; + var doc = root.document; + var html = doc.documentElement; + var handle = instance.addFromSetImmediateArguments(arguments); + var script = doc.createElement('script'); + script.onreadystatechange = function() { + instance.runIfPresent(handle); + script.onreadystatechange = null; + html.removeChild(script); + script = null; + }; + html.appendChild(script); + return handle; + }; + fn.instance = this; + return fn; + }; + ImmediateDefinition.prototype.createSetTimeoutSetImmediate = function() { + var fn = function setImmediate() { + var instance = setImmediate.instance; + var handle = instance.addFromSetImmediateArguments(arguments); + instance.root.setTimeout(instance.partiallyApplied(instance.runIfPresent, handle), 0); + return handle; + }; + fn.instance = this; + return fn; + }; + return ImmediateDefinition; + })(); + exports.ImmediateDefinition = ImmediateDefinition; + exports.Immediate = new ImmediateDefinition(root_1.root); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/never", ["rxjs/Observable", "rxjs/util/noop"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Observable_1 = require("rxjs/Observable"); + var noop_1 = require("rxjs/util/noop"); + var InfiniteObservable = (function(_super) { + __extends(InfiniteObservable, _super); + function InfiniteObservable() { + _super.call(this); + } + InfiniteObservable.create = function() { + return new InfiniteObservable(); + }; + InfiniteObservable.prototype._subscribe = function(subscriber) { + noop_1.noop(); + }; + return InfiniteObservable; + })(Observable_1.Observable); + exports.InfiniteObservable = InfiniteObservable; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/range", ["rxjs/Observable"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Observable_1 = require("rxjs/Observable"); + var RangeObservable = (function(_super) { + __extends(RangeObservable, _super); + function RangeObservable(start, end, scheduler) { + _super.call(this); + this.start = start; + this.end = end; + this.scheduler = scheduler; + } + RangeObservable.create = function(start, end, scheduler) { + if (start === void 0) { + start = 0; + } + if (end === void 0) { + end = 0; + } + return new RangeObservable(start, end, scheduler); + }; + RangeObservable.dispatch = function(state) { + var start = state.start, + index = state.index, + end = state.end, + subscriber = state.subscriber; + if (index >= end) { + subscriber.complete(); + return ; + } + subscriber.next(start); + if (subscriber.isUnsubscribed) { + return ; + } + state.index = index + 1; + state.start = start + 1; + this.schedule(state); + }; + RangeObservable.prototype._subscribe = function(subscriber) { + var index = 0; + var start = this.start; + var end = this.end; + var scheduler = this.scheduler; + if (scheduler) { + subscriber.add(scheduler.schedule(RangeObservable.dispatch, 0, { + index: index, + end: end, + start: start, + subscriber: subscriber + })); + } else { + do { + if (index++ >= end) { + subscriber.complete(); + break; + } + subscriber.next(start++); + if (subscriber.isUnsubscribed) { + break; + } + } while (true); + } + }; + return RangeObservable; + })(Observable_1.Observable); + exports.RangeObservable = RangeObservable; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/observable/throw", ["rxjs/Observable", "rxjs/observable/throw"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var throw_1 = require("rxjs/observable/throw"); + Observable_1.Observable.throw = throw_1.ErrorObservable.create; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/isDate", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function isDate(value) { + return value instanceof Date && !isNaN(+value); + } + exports.isDate = isDate; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/zip-support", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject", "rxjs/OuterSubscriber", "rxjs/util/subscribeToResult", "rxjs/util/SymbolShim"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); + var SymbolShim_1 = require("rxjs/util/SymbolShim"); + var isArray = Array.isArray; + var ZipOperator = (function() { + function ZipOperator(project) { + this.project = project; + } + ZipOperator.prototype.call = function(subscriber) { + return new ZipSubscriber(subscriber, this.project); + }; + return ZipOperator; + })(); + exports.ZipOperator = ZipOperator; + var ZipSubscriber = (function(_super) { + __extends(ZipSubscriber, _super); + function ZipSubscriber(destination, project, values) { + if (values === void 0) { + values = Object.create(null); + } + _super.call(this, destination); + this.index = 0; + this.iterators = []; + this.active = 0; + this.project = (typeof project === 'function') ? project : null; + this.values = values; + } + ZipSubscriber.prototype._next = function(value) { + var iterators = this.iterators; + var index = this.index++; + if (isArray(value)) { + iterators.push(new StaticArrayIterator(value)); + } else if (typeof value[SymbolShim_1.SymbolShim.iterator] === 'function') { + iterators.push(new StaticIterator(value[SymbolShim_1.SymbolShim.iterator]())); + } else { + iterators.push(new ZipBufferIterator(this.destination, this, value, index)); + } + }; + ZipSubscriber.prototype._complete = function() { + var iterators = this.iterators; + var len = iterators.length; + this.active = len; + for (var i = 0; i < len; i++) { + var iterator = iterators[i]; + if (iterator.stillUnsubscribed) { + iterator.subscribe(iterator, i); + } else { + this.active--; + } + } + }; + ZipSubscriber.prototype.notifyInactive = function() { + this.active--; + if (this.active === 0) { + this.destination.complete(); + } + }; + ZipSubscriber.prototype.checkIterators = function() { + var iterators = this.iterators; + var len = iterators.length; + var destination = this.destination; + for (var i = 0; i < len; i++) { + var iterator = iterators[i]; + if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) { + return ; + } + } + var shouldComplete = false; + var args = []; + for (var i = 0; i < len; i++) { + var iterator = iterators[i]; + var result = iterator.next(); + if (iterator.hasCompleted()) { + shouldComplete = true; + } + if (result.done) { + destination.complete(); + return ; + } + args.push(result.value); + } + var project = this.project; + if (project) { + var result = tryCatch_1.tryCatch(project).apply(this, args); + if (result === errorObject_1.errorObject) { + destination.error(errorObject_1.errorObject.e); + } else { + destination.next(result); + } + } else { + destination.next(args); + } + if (shouldComplete) { + destination.complete(); + } + }; + return ZipSubscriber; + })(Subscriber_1.Subscriber); + exports.ZipSubscriber = ZipSubscriber; + var StaticIterator = (function() { + function StaticIterator(iterator) { + this.iterator = iterator; + this.nextResult = iterator.next(); + } + StaticIterator.prototype.hasValue = function() { + return true; + }; + StaticIterator.prototype.next = function() { + var result = this.nextResult; + this.nextResult = this.iterator.next(); + return result; + }; + StaticIterator.prototype.hasCompleted = function() { + var nextResult = this.nextResult; + return nextResult && nextResult.done; + }; + return StaticIterator; + })(); + var StaticArrayIterator = (function() { + function StaticArrayIterator(array) { + this.array = array; + this.index = 0; + this.length = 0; + this.length = array.length; + } + StaticArrayIterator.prototype[SymbolShim_1.SymbolShim.iterator] = function() { + return this; + }; + StaticArrayIterator.prototype.next = function(value) { + var i = this.index++; + var array = this.array; + return i < this.length ? { + value: array[i], + done: false + } : {done: true}; + }; + StaticArrayIterator.prototype.hasValue = function() { + return this.array.length > this.index; + }; + StaticArrayIterator.prototype.hasCompleted = function() { + return this.array.length === this.index; + }; + return StaticArrayIterator; + })(); + var ZipBufferIterator = (function(_super) { + __extends(ZipBufferIterator, _super); + function ZipBufferIterator(destination, parent, observable, index) { + _super.call(this, destination); + this.parent = parent; + this.observable = observable; + this.index = index; + this.stillUnsubscribed = true; + this.buffer = []; + this.isComplete = false; + } + ZipBufferIterator.prototype[SymbolShim_1.SymbolShim.iterator] = function() { + return this; + }; + ZipBufferIterator.prototype.next = function() { + var buffer = this.buffer; + if (buffer.length === 0 && this.isComplete) { + return {done: true}; + } else { + return { + value: buffer.shift(), + done: false + }; + } + }; + ZipBufferIterator.prototype.hasValue = function() { + return this.buffer.length > 0; + }; + ZipBufferIterator.prototype.hasCompleted = function() { + return this.buffer.length === 0 && this.isComplete; + }; + ZipBufferIterator.prototype.notifyComplete = function() { + if (this.buffer.length > 0) { + this.isComplete = true; + this.parent.notifyInactive(); + } else { + this.destination.complete(); + } + }; + ZipBufferIterator.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex) { + this.buffer.push(innerValue); + this.parent.checkIterators(); + }; + ZipBufferIterator.prototype.subscribe = function(value, index) { + this.add(subscribeToResult_1.subscribeToResult(this, this.observable, this, index)); + }; + return ZipBufferIterator; + })(OuterSubscriber_1.OuterSubscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/buffer", ["rxjs/Subscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + function buffer(closingNotifier) { + return this.lift(new BufferOperator(closingNotifier)); + } + exports.buffer = buffer; + var BufferOperator = (function() { + function BufferOperator(closingNotifier) { + this.closingNotifier = closingNotifier; + } + BufferOperator.prototype.call = function(subscriber) { + return new BufferSubscriber(subscriber, this.closingNotifier); + }; + return BufferOperator; + })(); + var BufferSubscriber = (function(_super) { + __extends(BufferSubscriber, _super); + function BufferSubscriber(destination, closingNotifier) { + _super.call(this, destination); + this.buffer = []; + this.notifierSubscriber = null; + this.notifierSubscriber = new BufferClosingNotifierSubscriber(this); + this.add(closingNotifier._subscribe(this.notifierSubscriber)); + } + BufferSubscriber.prototype._next = function(value) { + this.buffer.push(value); + }; + BufferSubscriber.prototype._error = function(err) { + this.destination.error(err); + }; + BufferSubscriber.prototype._complete = function() { + this.destination.complete(); + }; + BufferSubscriber.prototype.flushBuffer = function() { + var buffer = this.buffer; + this.buffer = []; + this.destination.next(buffer); + if (this.isUnsubscribed) { + this.notifierSubscriber.unsubscribe(); + } + }; + return BufferSubscriber; + })(Subscriber_1.Subscriber); + var BufferClosingNotifierSubscriber = (function(_super) { + __extends(BufferClosingNotifierSubscriber, _super); + function BufferClosingNotifierSubscriber(parent) { + _super.call(this, null); + this.parent = parent; + } + BufferClosingNotifierSubscriber.prototype._next = function(value) { + this.parent.flushBuffer(); + }; + BufferClosingNotifierSubscriber.prototype._error = function(err) { + this.parent.error(err); + }; + BufferClosingNotifierSubscriber.prototype._complete = function() { + this.parent.complete(); + }; + return BufferClosingNotifierSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/bufferCount", ["rxjs/Subscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + function bufferCount(bufferSize, startBufferEvery) { + if (startBufferEvery === void 0) { + startBufferEvery = null; + } + return this.lift(new BufferCountOperator(bufferSize, startBufferEvery)); + } + exports.bufferCount = bufferCount; + var BufferCountOperator = (function() { + function BufferCountOperator(bufferSize, startBufferEvery) { + this.bufferSize = bufferSize; + this.startBufferEvery = startBufferEvery; + } + BufferCountOperator.prototype.call = function(subscriber) { + return new BufferCountSubscriber(subscriber, this.bufferSize, this.startBufferEvery); + }; + return BufferCountOperator; + })(); + var BufferCountSubscriber = (function(_super) { + __extends(BufferCountSubscriber, _super); + function BufferCountSubscriber(destination, bufferSize, startBufferEvery) { + _super.call(this, destination); + this.bufferSize = bufferSize; + this.startBufferEvery = startBufferEvery; + this.buffers = [[]]; + this.count = 0; + } + BufferCountSubscriber.prototype._next = function(value) { + var count = (this.count += 1); + var destination = this.destination; + var bufferSize = this.bufferSize; + var startBufferEvery = (this.startBufferEvery == null) ? bufferSize : this.startBufferEvery; + var buffers = this.buffers; + var len = buffers.length; + var remove = -1; + if (count % startBufferEvery === 0) { + buffers.push([]); + } + for (var i = 0; i < len; i++) { + var buffer = buffers[i]; + buffer.push(value); + if (buffer.length === bufferSize) { + remove = i; + destination.next(buffer); + } + } + if (remove !== -1) { + buffers.splice(remove, 1); + } + }; + BufferCountSubscriber.prototype._error = function(err) { + this.destination.error(err); + }; + BufferCountSubscriber.prototype._complete = function() { + var destination = this.destination; + var buffers = this.buffers; + while (buffers.length > 0) { + var buffer = buffers.shift(); + if (buffer.length > 0) { + destination.next(buffer); + } + } + destination.complete(); + }; + return BufferCountSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/bufferTime", ["rxjs/Subscriber", "rxjs/scheduler/asap"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var asap_1 = require("rxjs/scheduler/asap"); + function bufferTime(bufferTimeSpan, bufferCreationInterval, scheduler) { + if (bufferCreationInterval === void 0) { + bufferCreationInterval = null; + } + if (scheduler === void 0) { + scheduler = asap_1.asap; + } + return this.lift(new BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, scheduler)); + } + exports.bufferTime = bufferTime; + var BufferTimeOperator = (function() { + function BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, scheduler) { + this.bufferTimeSpan = bufferTimeSpan; + this.bufferCreationInterval = bufferCreationInterval; + this.scheduler = scheduler; + } + BufferTimeOperator.prototype.call = function(subscriber) { + return new BufferTimeSubscriber(subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.scheduler); + }; + return BufferTimeOperator; + })(); + var BufferTimeSubscriber = (function(_super) { + __extends(BufferTimeSubscriber, _super); + function BufferTimeSubscriber(destination, bufferTimeSpan, bufferCreationInterval, scheduler) { + _super.call(this, destination); + this.bufferTimeSpan = bufferTimeSpan; + this.bufferCreationInterval = bufferCreationInterval; + this.scheduler = scheduler; + this.buffers = []; + var buffer = this.openBuffer(); + if (bufferCreationInterval !== null && bufferCreationInterval >= 0) { + var closeState = { + subscriber: this, + buffer: buffer + }; + var creationState = { + bufferTimeSpan: bufferTimeSpan, + bufferCreationInterval: bufferCreationInterval, + subscriber: this, + scheduler: scheduler + }; + this.add(scheduler.schedule(dispatchBufferClose, bufferTimeSpan, closeState)); + this.add(scheduler.schedule(dispatchBufferCreation, bufferCreationInterval, creationState)); + } else { + var timeSpanOnlyState = { + subscriber: this, + buffer: buffer, + bufferTimeSpan: bufferTimeSpan + }; + this.add(scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState)); + } + } + BufferTimeSubscriber.prototype._next = function(value) { + var buffers = this.buffers; + var len = buffers.length; + for (var i = 0; i < len; i++) { + buffers[i].push(value); + } + }; + BufferTimeSubscriber.prototype._error = function(err) { + this.buffers.length = 0; + this.destination.error(err); + }; + BufferTimeSubscriber.prototype._complete = function() { + var buffers = this.buffers; + while (buffers.length > 0) { + this.destination.next(buffers.shift()); + } + this.destination.complete(); + }; + BufferTimeSubscriber.prototype.openBuffer = function() { + var buffer = []; + this.buffers.push(buffer); + return buffer; + }; + BufferTimeSubscriber.prototype.closeBuffer = function(buffer) { + this.destination.next(buffer); + var buffers = this.buffers; + buffers.splice(buffers.indexOf(buffer), 1); + }; + return BufferTimeSubscriber; + })(Subscriber_1.Subscriber); + function dispatchBufferTimeSpanOnly(state) { + var subscriber = state.subscriber; + var prevBuffer = state.buffer; + if (prevBuffer) { + subscriber.closeBuffer(prevBuffer); + } + state.buffer = subscriber.openBuffer(); + if (!subscriber.isUnsubscribed) { + this.schedule(state, state.bufferTimeSpan); + } + } + function dispatchBufferCreation(state) { + var bufferCreationInterval = state.bufferCreationInterval, + bufferTimeSpan = state.bufferTimeSpan, + subscriber = state.subscriber, + scheduler = state.scheduler; + var buffer = subscriber.openBuffer(); + var action = this; + if (!subscriber.isUnsubscribed) { + action.add(scheduler.schedule(dispatchBufferClose, bufferTimeSpan, { + subscriber: subscriber, + buffer: buffer + })); + action.schedule(state, bufferCreationInterval); + } + } + function dispatchBufferClose(_a) { + var subscriber = _a.subscriber, + buffer = _a.buffer; + subscriber.closeBuffer(buffer); + } + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/bufferToggle", ["rxjs/Subscriber", "rxjs/Subscription", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var Subscription_1 = require("rxjs/Subscription"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + function bufferToggle(openings, closingSelector) { + return this.lift(new BufferToggleOperator(openings, closingSelector)); + } + exports.bufferToggle = bufferToggle; + var BufferToggleOperator = (function() { + function BufferToggleOperator(openings, closingSelector) { + this.openings = openings; + this.closingSelector = closingSelector; + } + BufferToggleOperator.prototype.call = function(subscriber) { + return new BufferToggleSubscriber(subscriber, this.openings, this.closingSelector); + }; + return BufferToggleOperator; + })(); + var BufferToggleSubscriber = (function(_super) { + __extends(BufferToggleSubscriber, _super); + function BufferToggleSubscriber(destination, openings, closingSelector) { + _super.call(this, destination); + this.openings = openings; + this.closingSelector = closingSelector; + this.contexts = []; + this.add(this.openings._subscribe(new BufferToggleOpeningsSubscriber(this))); + } + BufferToggleSubscriber.prototype._next = function(value) { + var contexts = this.contexts; + var len = contexts.length; + for (var i = 0; i < len; i++) { + contexts[i].buffer.push(value); + } + }; + BufferToggleSubscriber.prototype._error = function(err) { + var contexts = this.contexts; + while (contexts.length > 0) { + var context = contexts.shift(); + context.subscription.unsubscribe(); + context.buffer = null; + context.subscription = null; + } + this.contexts = null; + this.destination.error(err); + }; + BufferToggleSubscriber.prototype._complete = function() { + var contexts = this.contexts; + while (contexts.length > 0) { + var context = contexts.shift(); + this.destination.next(context.buffer); + context.subscription.unsubscribe(); + context.buffer = null; + context.subscription = null; + } + this.contexts = null; + this.destination.complete(); + }; + BufferToggleSubscriber.prototype.openBuffer = function(value) { + var closingSelector = this.closingSelector; + var contexts = this.contexts; + var closingNotifier = tryCatch_1.tryCatch(closingSelector)(value); + if (closingNotifier === errorObject_1.errorObject) { + this._error(closingNotifier.e); + } else { + var context = { + buffer: [], + subscription: new Subscription_1.Subscription() + }; + contexts.push(context); + var subscriber = new BufferToggleClosingsSubscriber(this, context); + var subscription = closingNotifier._subscribe(subscriber); + context.subscription.add(subscription); + this.add(subscription); + } + }; + BufferToggleSubscriber.prototype.closeBuffer = function(context) { + var contexts = this.contexts; + if (contexts === null) { + return ; + } + var buffer = context.buffer, + subscription = context.subscription; + this.destination.next(buffer); + contexts.splice(contexts.indexOf(context), 1); + this.remove(subscription); + subscription.unsubscribe(); + }; + return BufferToggleSubscriber; + })(Subscriber_1.Subscriber); + var BufferToggleOpeningsSubscriber = (function(_super) { + __extends(BufferToggleOpeningsSubscriber, _super); + function BufferToggleOpeningsSubscriber(parent) { + _super.call(this, null); + this.parent = parent; + } + BufferToggleOpeningsSubscriber.prototype._next = function(value) { + this.parent.openBuffer(value); + }; + BufferToggleOpeningsSubscriber.prototype._error = function(err) { + this.parent.error(err); + }; + BufferToggleOpeningsSubscriber.prototype._complete = function() {}; + return BufferToggleOpeningsSubscriber; + })(Subscriber_1.Subscriber); + var BufferToggleClosingsSubscriber = (function(_super) { + __extends(BufferToggleClosingsSubscriber, _super); + function BufferToggleClosingsSubscriber(parent, context) { + _super.call(this, null); + this.parent = parent; + this.context = context; + } + BufferToggleClosingsSubscriber.prototype._next = function() { + this.parent.closeBuffer(this.context); + }; + BufferToggleClosingsSubscriber.prototype._error = function(err) { + this.parent.error(err); + }; + BufferToggleClosingsSubscriber.prototype._complete = function() { + this.parent.closeBuffer(this.context); + }; + return BufferToggleClosingsSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/bufferWhen", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + function bufferWhen(closingSelector) { + return this.lift(new BufferWhenOperator(closingSelector)); + } + exports.bufferWhen = bufferWhen; + var BufferWhenOperator = (function() { + function BufferWhenOperator(closingSelector) { + this.closingSelector = closingSelector; + } + BufferWhenOperator.prototype.call = function(subscriber) { + return new BufferWhenSubscriber(subscriber, this.closingSelector); + }; + return BufferWhenOperator; + })(); + var BufferWhenSubscriber = (function(_super) { + __extends(BufferWhenSubscriber, _super); + function BufferWhenSubscriber(destination, closingSelector) { + _super.call(this, destination); + this.closingSelector = closingSelector; + this.openBuffer(); + } + BufferWhenSubscriber.prototype._next = function(value) { + this.buffer.push(value); + }; + BufferWhenSubscriber.prototype._error = function(err) { + this.buffer = null; + this.destination.error(err); + }; + BufferWhenSubscriber.prototype._complete = function() { + var buffer = this.buffer; + this.destination.next(buffer); + this.buffer = null; + this.destination.complete(); + }; + BufferWhenSubscriber.prototype.openBuffer = function() { + var prevClosingNotification = this.closingNotification; + if (prevClosingNotification) { + this.remove(prevClosingNotification); + prevClosingNotification.unsubscribe(); + } + var buffer = this.buffer; + if (buffer) { + this.destination.next(buffer); + } + this.buffer = []; + var closingNotifier = tryCatch_1.tryCatch(this.closingSelector)(); + if (closingNotifier === errorObject_1.errorObject) { + var err = closingNotifier.e; + this.buffer = null; + this.destination.error(err); + } else { + this.add(this.closingNotification = closingNotifier._subscribe(new BufferClosingNotifierSubscriber(this))); + } + }; + return BufferWhenSubscriber; + })(Subscriber_1.Subscriber); + var BufferClosingNotifierSubscriber = (function(_super) { + __extends(BufferClosingNotifierSubscriber, _super); + function BufferClosingNotifierSubscriber(parent) { + _super.call(this, null); + this.parent = parent; + } + BufferClosingNotifierSubscriber.prototype._next = function() { + this.parent.openBuffer(); + }; + BufferClosingNotifierSubscriber.prototype._error = function(err) { + this.parent.error(err); + }; + BufferClosingNotifierSubscriber.prototype._complete = function() { + this.parent.openBuffer(); + }; + return BufferClosingNotifierSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/catch", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + function _catch(selector) { + var catchOperator = new CatchOperator(selector); + var caught = this.lift(catchOperator); + catchOperator.caught = caught; + return caught; + } + exports._catch = _catch; + var CatchOperator = (function() { + function CatchOperator(selector) { + this.selector = selector; + } + CatchOperator.prototype.call = function(subscriber) { + return new CatchSubscriber(subscriber, this.selector, this.caught); + }; + return CatchOperator; + })(); + var CatchSubscriber = (function(_super) { + __extends(CatchSubscriber, _super); + function CatchSubscriber(destination, selector, caught) { + _super.call(this, null); + this.destination = destination; + this.selector = selector; + this.caught = caught; + this.lastSubscription = this; + this.destination.add(this); + } + CatchSubscriber.prototype._next = function(value) { + this.destination.next(value); + }; + CatchSubscriber.prototype._error = function(err) { + var result = tryCatch_1.tryCatch(this.selector)(err, this.caught); + if (result === errorObject_1.errorObject) { + this.destination.error(errorObject_1.errorObject.e); + } else { + this.lastSubscription.unsubscribe(); + this.lastSubscription = result.subscribe(this.destination); + } + }; + CatchSubscriber.prototype._complete = function() { + this.lastSubscription.unsubscribe(); + this.destination.complete(); + }; + CatchSubscriber.prototype._unsubscribe = function() { + this.lastSubscription.unsubscribe(); + }; + return CatchSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/combineAll", ["rxjs/operator/combineLatest-support"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var combineLatest_support_1 = require("rxjs/operator/combineLatest-support"); + function combineAll(project) { + return this.lift(new combineLatest_support_1.CombineLatestOperator(project)); + } + exports.combineAll = combineAll; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/combineLatest", ["rxjs/observable/fromArray", "rxjs/operator/combineLatest-support", "rxjs/util/isArray"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var fromArray_1 = require("rxjs/observable/fromArray"); + var combineLatest_support_1 = require("rxjs/operator/combineLatest-support"); + var isArray_1 = require("rxjs/util/isArray"); + function combineLatest() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; + } + var project = null; + if (typeof observables[observables.length - 1] === 'function') { + project = observables.pop(); + } + if (observables.length === 1 && isArray_1.isArray(observables[0])) { + observables = observables[0]; + } + observables.unshift(this); + return new fromArray_1.ArrayObservable(observables).lift(new combineLatest_support_1.CombineLatestOperator(project)); + } + exports.combineLatest = combineLatest; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/concat", ["rxjs/util/isScheduler", "rxjs/observable/fromArray", "rxjs/operator/mergeAll-support"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var isScheduler_1 = require("rxjs/util/isScheduler"); + var fromArray_1 = require("rxjs/observable/fromArray"); + var mergeAll_support_1 = require("rxjs/operator/mergeAll-support"); + function concat() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; + } + var args = observables; + args.unshift(this); + var scheduler = null; + if (isScheduler_1.isScheduler(args[args.length - 1])) { + scheduler = args.pop(); + } + return new fromArray_1.ArrayObservable(args, scheduler).lift(new mergeAll_support_1.MergeAllOperator(1)); + } + exports.concat = concat; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/concatAll", ["rxjs/operator/mergeAll-support"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var mergeAll_support_1 = require("rxjs/operator/mergeAll-support"); + function concatAll() { + return this.lift(new mergeAll_support_1.MergeAllOperator(1)); + } + exports.concatAll = concatAll; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/mergeMap-support", ["rxjs/util/tryCatch", "rxjs/util/errorObject", "rxjs/util/subscribeToResult", "rxjs/OuterSubscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var MergeMapOperator = (function() { + function MergeMapOperator(project, resultSelector, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + this.project = project; + this.resultSelector = resultSelector; + this.concurrent = concurrent; + } + MergeMapOperator.prototype.call = function(observer) { + return new MergeMapSubscriber(observer, this.project, this.resultSelector, this.concurrent); + }; + return MergeMapOperator; + })(); + exports.MergeMapOperator = MergeMapOperator; + var MergeMapSubscriber = (function(_super) { + __extends(MergeMapSubscriber, _super); + function MergeMapSubscriber(destination, project, resultSelector, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + _super.call(this, destination); + this.project = project; + this.resultSelector = resultSelector; + this.concurrent = concurrent; + this.hasCompleted = false; + this.buffer = []; + this.active = 0; + this.index = 0; + } + MergeMapSubscriber.prototype._next = function(value) { + if (this.active < this.concurrent) { + var index = this.index++; + var ish = tryCatch_1.tryCatch(this.project)(value, index); + var destination = this.destination; + if (ish === errorObject_1.errorObject) { + destination.error(ish.e); + } else { + this.active++; + this._innerSub(ish, value, index); + } + } else { + this.buffer.push(value); + } + }; + MergeMapSubscriber.prototype._innerSub = function(ish, value, index) { + this.add(subscribeToResult_1.subscribeToResult(this, ish, value, index)); + }; + MergeMapSubscriber.prototype._complete = function() { + this.hasCompleted = true; + if (this.active === 0 && this.buffer.length === 0) { + this.destination.complete(); + } + }; + MergeMapSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex) { + var _a = this, + destination = _a.destination, + resultSelector = _a.resultSelector; + if (resultSelector) { + var result = tryCatch_1.tryCatch(resultSelector)(outerValue, innerValue, outerIndex, innerIndex); + if (result === errorObject_1.errorObject) { + destination.error(errorObject_1.errorObject.e); + } else { + destination.next(result); + } + } else { + destination.next(innerValue); + } + }; + MergeMapSubscriber.prototype.notifyComplete = function(innerSub) { + var buffer = this.buffer; + this.remove(innerSub); + this.active--; + if (buffer.length > 0) { + this._next(buffer.shift()); + } else if (this.active === 0 && this.hasCompleted) { + this.destination.complete(); + } + }; + return MergeMapSubscriber; + })(OuterSubscriber_1.OuterSubscriber); + exports.MergeMapSubscriber = MergeMapSubscriber; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/mergeMapTo-support", ["rxjs/util/tryCatch", "rxjs/util/errorObject", "rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); + var MergeMapToOperator = (function() { + function MergeMapToOperator(ish, resultSelector, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + this.ish = ish; + this.resultSelector = resultSelector; + this.concurrent = concurrent; + } + MergeMapToOperator.prototype.call = function(observer) { + return new MergeMapToSubscriber(observer, this.ish, this.resultSelector, this.concurrent); + }; + return MergeMapToOperator; + })(); + exports.MergeMapToOperator = MergeMapToOperator; + var MergeMapToSubscriber = (function(_super) { + __extends(MergeMapToSubscriber, _super); + function MergeMapToSubscriber(destination, ish, resultSelector, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + _super.call(this, destination); + this.ish = ish; + this.resultSelector = resultSelector; + this.concurrent = concurrent; + this.hasCompleted = false; + this.buffer = []; + this.active = 0; + this.index = 0; + } + MergeMapToSubscriber.prototype._next = function(value) { + if (this.active < this.concurrent) { + var resultSelector = this.resultSelector; + var index = this.index++; + var ish = this.ish; + var destination = this.destination; + this.active++; + this._innerSub(ish, destination, resultSelector, value, index); + } else { + this.buffer.push(value); + } + }; + MergeMapToSubscriber.prototype._innerSub = function(ish, destination, resultSelector, value, index) { + this.add(subscribeToResult_1.subscribeToResult(this, ish, value, index)); + }; + MergeMapToSubscriber.prototype._complete = function() { + this.hasCompleted = true; + if (this.active === 0 && this.buffer.length === 0) { + this.destination.complete(); + } + }; + MergeMapToSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex) { + var _a = this, + resultSelector = _a.resultSelector, + destination = _a.destination; + if (resultSelector) { + var result = tryCatch_1.tryCatch(resultSelector)(outerValue, innerValue, outerIndex, innerIndex); + if (result === errorObject_1.errorObject) { + destination.error(errorObject_1.errorObject.e); + } else { + destination.next(result); + } + } else { + destination.next(innerValue); + } + }; + MergeMapToSubscriber.prototype.notifyError = function(err) { + this.destination.error(err); + }; + MergeMapToSubscriber.prototype.notifyComplete = function(innerSub) { + var buffer = this.buffer; + this.remove(innerSub); + this.active--; + if (buffer.length > 0) { + this._next(buffer.shift()); + } else if (this.active === 0 && this.hasCompleted) { + this.destination.complete(); + } + }; + return MergeMapToSubscriber; + })(OuterSubscriber_1.OuterSubscriber); + exports.MergeMapToSubscriber = MergeMapToSubscriber; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/count", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + function count(predicate) { + return this.lift(new CountOperator(predicate, this)); + } + exports.count = count; + var CountOperator = (function() { + function CountOperator(predicate, source) { + this.predicate = predicate; + this.source = source; + } + CountOperator.prototype.call = function(subscriber) { + return new CountSubscriber(subscriber, this.predicate, this.source); + }; + return CountOperator; + })(); + var CountSubscriber = (function(_super) { + __extends(CountSubscriber, _super); + function CountSubscriber(destination, predicate, source) { + _super.call(this, destination); + this.predicate = predicate; + this.source = source; + this.count = 0; + this.index = 0; + } + CountSubscriber.prototype._next = function(value) { + var predicate = this.predicate; + var passed = true; + if (predicate) { + passed = tryCatch_1.tryCatch(predicate)(value, this.index++, this.source); + if (passed === errorObject_1.errorObject) { + this.destination.error(passed.e); + return ; + } + } + if (passed) { + this.count += 1; + } + }; + CountSubscriber.prototype._complete = function() { + this.destination.next(this.count); + this.destination.complete(); + }; + return CountSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/dematerialize", ["rxjs/Subscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + function dematerialize() { + return this.lift(new DeMaterializeOperator()); + } + exports.dematerialize = dematerialize; + var DeMaterializeOperator = (function() { + function DeMaterializeOperator() {} + DeMaterializeOperator.prototype.call = function(subscriber) { + return new DeMaterializeSubscriber(subscriber); + }; + return DeMaterializeOperator; + })(); + var DeMaterializeSubscriber = (function(_super) { + __extends(DeMaterializeSubscriber, _super); + function DeMaterializeSubscriber(destination) { + _super.call(this, destination); + } + DeMaterializeSubscriber.prototype._next = function(value) { + value.observe(this.destination); + }; + return DeMaterializeSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/debounce", ["rxjs/observable/fromPromise", "rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/isPromise", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var fromPromise_1 = require("rxjs/observable/fromPromise"); + var Subscriber_1 = require("rxjs/Subscriber"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var isPromise_1 = require("rxjs/util/isPromise"); + var errorObject_1 = require("rxjs/util/errorObject"); + function debounce(durationSelector) { + return this.lift(new DebounceOperator(durationSelector)); + } + exports.debounce = debounce; + var DebounceOperator = (function() { + function DebounceOperator(durationSelector) { + this.durationSelector = durationSelector; + } + DebounceOperator.prototype.call = function(observer) { + return new DebounceSubscriber(observer, this.durationSelector); + }; + return DebounceOperator; + })(); + var DebounceSubscriber = (function(_super) { + __extends(DebounceSubscriber, _super); + function DebounceSubscriber(destination, durationSelector) { + _super.call(this, destination); + this.durationSelector = durationSelector; + this.debouncedSubscription = null; + this.lastValue = null; + this._index = 0; + } + Object.defineProperty(DebounceSubscriber.prototype, "index", { + get: function() { + return this._index; + }, + enumerable: true, + configurable: true + }); + DebounceSubscriber.prototype._next = function(value) { + var destination = this.destination; + var currentIndex = ++this._index; + var debounce = tryCatch_1.tryCatch(this.durationSelector)(value); + if (debounce === errorObject_1.errorObject) { + destination.error(errorObject_1.errorObject.e); + } else { + if (isPromise_1.isPromise(debounce)) { + debounce = fromPromise_1.PromiseObservable.create(debounce); + } + this.lastValue = value; + this.clearDebounce(); + this.add(this.debouncedSubscription = debounce._subscribe(new DurationSelectorSubscriber(this, currentIndex))); + } + }; + DebounceSubscriber.prototype._complete = function() { + this.debouncedNext(); + this.destination.complete(); + }; + DebounceSubscriber.prototype.debouncedNext = function() { + this.clearDebounce(); + if (this.lastValue != null) { + this.destination.next(this.lastValue); + this.lastValue = null; + } + }; + DebounceSubscriber.prototype.clearDebounce = function() { + var debouncedSubscription = this.debouncedSubscription; + if (debouncedSubscription) { + debouncedSubscription.unsubscribe(); + this.remove(debouncedSubscription); + this.debouncedSubscription = null; + } + }; + return DebounceSubscriber; + })(Subscriber_1.Subscriber); + var DurationSelectorSubscriber = (function(_super) { + __extends(DurationSelectorSubscriber, _super); + function DurationSelectorSubscriber(parent, currentIndex) { + _super.call(this, null); + this.parent = parent; + this.currentIndex = currentIndex; + } + DurationSelectorSubscriber.prototype.debounceNext = function() { + var parent = this.parent; + if (this.currentIndex === parent.index) { + parent.debouncedNext(); + if (!this.isUnsubscribed) { + this.unsubscribe(); + } + } + }; + DurationSelectorSubscriber.prototype._next = function(unused) { + this.debounceNext(); + }; + DurationSelectorSubscriber.prototype._error = function(err) { + this.parent.error(err); + }; + DurationSelectorSubscriber.prototype._complete = function() { + this.debounceNext(); + }; + return DurationSelectorSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/debounceTime", ["rxjs/Subscriber", "rxjs/scheduler/asap"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var asap_1 = require("rxjs/scheduler/asap"); + function debounceTime(dueTime, scheduler) { + if (scheduler === void 0) { + scheduler = asap_1.asap; + } + return this.lift(new DebounceTimeOperator(dueTime, scheduler)); + } + exports.debounceTime = debounceTime; + var DebounceTimeOperator = (function() { + function DebounceTimeOperator(dueTime, scheduler) { + this.dueTime = dueTime; + this.scheduler = scheduler; + } + DebounceTimeOperator.prototype.call = function(subscriber) { + return new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler); + }; + return DebounceTimeOperator; + })(); + var DebounceTimeSubscriber = (function(_super) { + __extends(DebounceTimeSubscriber, _super); + function DebounceTimeSubscriber(destination, dueTime, scheduler) { + _super.call(this, destination); + this.dueTime = dueTime; + this.scheduler = scheduler; + this.debouncedSubscription = null; + this.lastValue = null; + } + DebounceTimeSubscriber.prototype._next = function(value) { + this.clearDebounce(); + this.lastValue = value; + this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this)); + }; + DebounceTimeSubscriber.prototype._complete = function() { + this.debouncedNext(); + this.destination.complete(); + }; + DebounceTimeSubscriber.prototype.debouncedNext = function() { + this.clearDebounce(); + if (this.lastValue != null) { + this.destination.next(this.lastValue); + this.lastValue = null; + } + }; + DebounceTimeSubscriber.prototype.clearDebounce = function() { + var debouncedSubscription = this.debouncedSubscription; + if (debouncedSubscription !== null) { + this.remove(debouncedSubscription); + debouncedSubscription.unsubscribe(); + this.debouncedSubscription = null; + } + }; + return DebounceTimeSubscriber; + })(Subscriber_1.Subscriber); + function dispatchNext(subscriber) { + subscriber.debouncedNext(); + } + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/defaultIfEmpty", ["rxjs/Subscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + function defaultIfEmpty(defaultValue) { + if (defaultValue === void 0) { + defaultValue = null; + } + return this.lift(new DefaultIfEmptyOperator(defaultValue)); + } + exports.defaultIfEmpty = defaultIfEmpty; + var DefaultIfEmptyOperator = (function() { + function DefaultIfEmptyOperator(defaultValue) { + this.defaultValue = defaultValue; + } + DefaultIfEmptyOperator.prototype.call = function(subscriber) { + return new DefaultIfEmptySubscriber(subscriber, this.defaultValue); + }; + return DefaultIfEmptyOperator; + })(); + var DefaultIfEmptySubscriber = (function(_super) { + __extends(DefaultIfEmptySubscriber, _super); + function DefaultIfEmptySubscriber(destination, defaultValue) { + _super.call(this, destination); + this.defaultValue = defaultValue; + this.isEmpty = true; + } + DefaultIfEmptySubscriber.prototype._next = function(value) { + this.isEmpty = false; + this.destination.next(value); + }; + DefaultIfEmptySubscriber.prototype._complete = function() { + if (this.isEmpty) { + this.destination.next(this.defaultValue); + } + this.destination.complete(); + }; + return DefaultIfEmptySubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/delay", ["rxjs/Subscriber", "rxjs/Notification", "rxjs/scheduler/queue", "rxjs/util/isDate"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var Notification_1 = require("rxjs/Notification"); + var queue_1 = require("rxjs/scheduler/queue"); + var isDate_1 = require("rxjs/util/isDate"); + function delay(delay, scheduler) { + if (scheduler === void 0) { + scheduler = queue_1.queue; + } + var absoluteDelay = isDate_1.isDate(delay); + var delayFor = absoluteDelay ? (+delay - scheduler.now()) : delay; + return this.lift(new DelayOperator(delayFor, scheduler)); + } + exports.delay = delay; + var DelayOperator = (function() { + function DelayOperator(delay, scheduler) { + this.delay = delay; + this.scheduler = scheduler; + } + DelayOperator.prototype.call = function(subscriber) { + return new DelaySubscriber(subscriber, this.delay, this.scheduler); + }; + return DelayOperator; + })(); + var DelaySubscriber = (function(_super) { + __extends(DelaySubscriber, _super); + function DelaySubscriber(destination, delay, scheduler) { + _super.call(this, destination); + this.delay = delay; + this.scheduler = scheduler; + this.queue = []; + this.active = false; + this.errored = false; + } + DelaySubscriber.dispatch = function(state) { + var source = state.source; + var queue = source.queue; + var scheduler = state.scheduler; + var destination = state.destination; + while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) { + queue.shift().notification.observe(destination); + } + if (queue.length > 0) { + var delay_1 = Math.max(0, queue[0].time - scheduler.now()); + this.schedule(state, delay_1); + } else { + source.active = false; + } + }; + DelaySubscriber.prototype._schedule = function(scheduler) { + this.active = true; + this.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, { + source: this, + destination: this.destination, + scheduler: scheduler + })); + }; + DelaySubscriber.prototype.scheduleNotification = function(notification) { + if (this.errored === true) { + return ; + } + var scheduler = this.scheduler; + var message = new DelayMessage(scheduler.now() + this.delay, notification); + this.queue.push(message); + if (this.active === false) { + this._schedule(scheduler); + } + }; + DelaySubscriber.prototype._next = function(value) { + this.scheduleNotification(Notification_1.Notification.createNext(value)); + }; + DelaySubscriber.prototype._error = function(err) { + this.errored = true; + this.queue = []; + this.destination.error(err); + }; + DelaySubscriber.prototype._complete = function() { + this.scheduleNotification(Notification_1.Notification.createComplete()); + }; + return DelaySubscriber; + })(Subscriber_1.Subscriber); + var DelayMessage = (function() { + function DelayMessage(time, notification) { + this.time = time; + this.notification = notification; + } + return DelayMessage; + })(); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/distinctUntilChanged", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + function distinctUntilChanged(compare) { + return this.lift(new DistinctUntilChangedOperator(compare)); + } + exports.distinctUntilChanged = distinctUntilChanged; + var DistinctUntilChangedOperator = (function() { + function DistinctUntilChangedOperator(compare) { + this.compare = compare; + } + DistinctUntilChangedOperator.prototype.call = function(subscriber) { + return new DistinctUntilChangedSubscriber(subscriber, this.compare); + }; + return DistinctUntilChangedOperator; + })(); + var DistinctUntilChangedSubscriber = (function(_super) { + __extends(DistinctUntilChangedSubscriber, _super); + function DistinctUntilChangedSubscriber(destination, compare) { + _super.call(this, destination); + this.hasValue = false; + if (typeof compare === 'function') { + this.compare = compare; + } + } + DistinctUntilChangedSubscriber.prototype.compare = function(x, y) { + return x === y; + }; + DistinctUntilChangedSubscriber.prototype._next = function(value) { + var result = false; + if (this.hasValue) { + result = tryCatch_1.tryCatch(this.compare)(this.value, value); + if (result === errorObject_1.errorObject) { + this.destination.error(errorObject_1.errorObject.e); + return ; + } + } else { + this.hasValue = true; + } + if (Boolean(result) === false) { + this.value = value; + this.destination.next(value); + } + }; + return DistinctUntilChangedSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/do", ["rxjs/Subscriber", "rxjs/util/noop", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var noop_1 = require("rxjs/util/noop"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + function _do(nextOrObserver, error, complete) { + var next; + if (nextOrObserver && typeof nextOrObserver === 'object') { + next = nextOrObserver.next; + error = nextOrObserver.error; + complete = nextOrObserver.complete; + } else { + next = nextOrObserver; + } + return this.lift(new DoOperator(next || noop_1.noop, error || noop_1.noop, complete || noop_1.noop)); + } + exports._do = _do; + var DoOperator = (function() { + function DoOperator(next, error, complete) { + this.next = next; + this.error = error; + this.complete = complete; + } + DoOperator.prototype.call = function(subscriber) { + return new DoSubscriber(subscriber, this.next, this.error, this.complete); + }; + return DoOperator; + })(); + var DoSubscriber = (function(_super) { + __extends(DoSubscriber, _super); + function DoSubscriber(destination, next, error, complete) { + _super.call(this, destination); + this.__next = next; + this.__error = error; + this.__complete = complete; + } + DoSubscriber.prototype._next = function(x) { + var result = tryCatch_1.tryCatch(this.__next)(x); + if (result === errorObject_1.errorObject) { + this.destination.error(errorObject_1.errorObject.e); + } else { + this.destination.next(x); + } + }; + DoSubscriber.prototype._error = function(e) { + var result = tryCatch_1.tryCatch(this.__error)(e); + if (result === errorObject_1.errorObject) { + this.destination.error(errorObject_1.errorObject.e); + } else { + this.destination.error(e); + } + }; + DoSubscriber.prototype._complete = function() { + var result = tryCatch_1.tryCatch(this.__complete)(); + if (result === errorObject_1.errorObject) { + this.destination.error(errorObject_1.errorObject.e); + } else { + this.destination.complete(); + } + }; + return DoSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/expand-support", ["rxjs/util/tryCatch", "rxjs/util/errorObject", "rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); + var ExpandOperator = (function() { + function ExpandOperator(project, concurrent, scheduler) { + this.project = project; + this.concurrent = concurrent; + this.scheduler = scheduler; + } + ExpandOperator.prototype.call = function(subscriber) { + return new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler); + }; + return ExpandOperator; + })(); + exports.ExpandOperator = ExpandOperator; + var ExpandSubscriber = (function(_super) { + __extends(ExpandSubscriber, _super); + function ExpandSubscriber(destination, project, concurrent, scheduler) { + _super.call(this, destination); + this.project = project; + this.concurrent = concurrent; + this.scheduler = scheduler; + this.index = 0; + this.active = 0; + this.hasCompleted = false; + if (concurrent < Number.POSITIVE_INFINITY) { + this.buffer = []; + } + } + ExpandSubscriber.dispatch = function(_a) { + var subscriber = _a.subscriber, + result = _a.result, + value = _a.value, + index = _a.index; + subscriber.subscribeToProjection(result, value, index); + }; + ExpandSubscriber.prototype._next = function(value) { + var destination = this.destination; + if (destination.isUnsubscribed) { + this._complete(); + return ; + } + var index = this.index++; + if (this.active < this.concurrent) { + destination.next(value); + var result = tryCatch_1.tryCatch(this.project)(value, index); + if (result === errorObject_1.errorObject) { + destination.error(result.e); + } else if (!this.scheduler) { + this.subscribeToProjection(result, value, index); + } else { + var state = { + subscriber: this, + result: result, + value: value, + index: index + }; + this.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state)); + } + } else { + this.buffer.push(value); + } + }; + ExpandSubscriber.prototype.subscribeToProjection = function(result, value, index) { + if (result._isScalar) { + this._next(result.value); + } else { + this.active++; + this.add(subscribeToResult_1.subscribeToResult(this, result, value, index)); + } + }; + ExpandSubscriber.prototype._complete = function() { + this.hasCompleted = true; + if (this.hasCompleted && this.active === 0) { + this.destination.complete(); + } + }; + ExpandSubscriber.prototype.notifyComplete = function(innerSub) { + var buffer = this.buffer; + this.remove(innerSub); + this.active--; + if (buffer && buffer.length > 0) { + this._next(buffer.shift()); + } + if (this.hasCompleted && this.active === 0) { + this.destination.complete(); + } + }; + ExpandSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex) { + this._next(innerValue); + }; + return ExpandSubscriber; + })(OuterSubscriber_1.OuterSubscriber); + exports.ExpandSubscriber = ExpandSubscriber; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/filter", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + function filter(select, thisArg) { + return this.lift(new FilterOperator(select, thisArg)); + } + exports.filter = filter; + var FilterOperator = (function() { + function FilterOperator(select, thisArg) { + this.select = select; + this.thisArg = thisArg; + } + FilterOperator.prototype.call = function(subscriber) { + return new FilterSubscriber(subscriber, this.select, this.thisArg); + }; + return FilterOperator; + })(); + var FilterSubscriber = (function(_super) { + __extends(FilterSubscriber, _super); + function FilterSubscriber(destination, select, thisArg) { + _super.call(this, destination); + this.thisArg = thisArg; + this.count = 0; + this.select = select; + } + FilterSubscriber.prototype._next = function(x) { + var result = tryCatch_1.tryCatch(this.select).call(this.thisArg || this, x, this.count++); + if (result === errorObject_1.errorObject) { + this.destination.error(errorObject_1.errorObject.e); + } else if (Boolean(result)) { + this.destination.next(x); + } + }; + return FilterSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/finally", ["rxjs/Subscriber", "rxjs/Subscription"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var Subscription_1 = require("rxjs/Subscription"); + function _finally(finallySelector) { + return this.lift(new FinallyOperator(finallySelector)); + } + exports._finally = _finally; + var FinallyOperator = (function() { + function FinallyOperator(finallySelector) { + this.finallySelector = finallySelector; + } + FinallyOperator.prototype.call = function(subscriber) { + return new FinallySubscriber(subscriber, this.finallySelector); + }; + return FinallyOperator; + })(); + var FinallySubscriber = (function(_super) { + __extends(FinallySubscriber, _super); + function FinallySubscriber(destination, finallySelector) { + _super.call(this, destination); + this.add(new Subscription_1.Subscription(finallySelector)); + } + return FinallySubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/EmptyError", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var EmptyError = (function() { + function EmptyError() { + this.name = 'EmptyError'; + this.message = 'no elements in sequence'; + } + return EmptyError; + })(); + exports.EmptyError = EmptyError; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/MapPolyfill", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var MapPolyfill = (function() { + function MapPolyfill() { + this.size = 0; + this._values = []; + this._keys = []; + } + MapPolyfill.prototype.get = function(key) { + var i = this._keys.indexOf(key); + return i === -1 ? undefined : this._values[i]; + }; + MapPolyfill.prototype.set = function(key, value) { + var i = this._keys.indexOf(key); + if (i === -1) { + this._keys.push(key); + this._values.push(value); + this.size++; + } else { + this._values[i] = value; + } + return this; + }; + MapPolyfill.prototype.delete = function(key) { + var i = this._keys.indexOf(key); + if (i === -1) { + return false; + } + this._values.splice(i, 1); + this._keys.splice(i, 1); + this.size--; + return true; + }; + MapPolyfill.prototype.forEach = function(cb, thisArg) { + for (var i = 0; i < this.size; i++) { + cb.call(thisArg, this._values[i], this._keys[i]); + } + }; + return MapPolyfill; + })(); + exports.MapPolyfill = MapPolyfill; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/FastMap", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var FastMap = (function() { + function FastMap() { + this.values = {}; + } + FastMap.prototype.delete = function(key) { + this.values[key] = null; + return true; + }; + FastMap.prototype.set = function(key, value) { + this.values[key] = value; + return this; + }; + FastMap.prototype.get = function(key) { + return this.values[key]; + }; + FastMap.prototype.forEach = function(cb, thisArg) { + var values = this.values; + for (var key in values) { + if (values.hasOwnProperty(key) && values[key] !== null) { + cb.call(thisArg, values[key], key); + } + } + }; + FastMap.prototype.clear = function() { + this.values = {}; + }; + return FastMap; + })(); + exports.FastMap = FastMap; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/groupBy-support", ["rxjs/Subscription", "rxjs/Observable"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscription_1 = require("rxjs/Subscription"); + var Observable_1 = require("rxjs/Observable"); + var RefCountSubscription = (function(_super) { + __extends(RefCountSubscription, _super); + function RefCountSubscription() { + _super.call(this); + this.attemptedToUnsubscribePrimary = false; + this.count = 0; + } + RefCountSubscription.prototype.setPrimary = function(subscription) { + this.primary = subscription; + }; + RefCountSubscription.prototype.unsubscribe = function() { + if (!this.isUnsubscribed && !this.attemptedToUnsubscribePrimary) { + this.attemptedToUnsubscribePrimary = true; + if (this.count === 0) { + _super.prototype.unsubscribe.call(this); + this.primary.unsubscribe(); + } + } + }; + return RefCountSubscription; + })(Subscription_1.Subscription); + exports.RefCountSubscription = RefCountSubscription; + var GroupedObservable = (function(_super) { + __extends(GroupedObservable, _super); + function GroupedObservable(key, groupSubject, refCountSubscription) { + _super.call(this); + this.key = key; + this.groupSubject = groupSubject; + this.refCountSubscription = refCountSubscription; + } + GroupedObservable.prototype._subscribe = function(subscriber) { + var subscription = new Subscription_1.Subscription(); + if (this.refCountSubscription && !this.refCountSubscription.isUnsubscribed) { + subscription.add(new InnerRefCountSubscription(this.refCountSubscription)); + } + subscription.add(this.groupSubject.subscribe(subscriber)); + return subscription; + }; + return GroupedObservable; + })(Observable_1.Observable); + exports.GroupedObservable = GroupedObservable; + var InnerRefCountSubscription = (function(_super) { + __extends(InnerRefCountSubscription, _super); + function InnerRefCountSubscription(parent) { + _super.call(this); + this.parent = parent; + parent.count++; + } + InnerRefCountSubscription.prototype.unsubscribe = function() { + if (!this.parent.isUnsubscribed && !this.isUnsubscribed) { + _super.prototype.unsubscribe.call(this); + this.parent.count--; + if (this.parent.count === 0 && this.parent.attemptedToUnsubscribePrimary) { + this.parent.unsubscribe(); + this.parent.primary.unsubscribe(); + } + } + }; + return InnerRefCountSubscription; + })(Subscription_1.Subscription); + exports.InnerRefCountSubscription = InnerRefCountSubscription; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/ignoreElements", ["rxjs/Subscriber", "rxjs/util/noop"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var noop_1 = require("rxjs/util/noop"); + function ignoreElements() { + return this.lift(new IgnoreElementsOperator()); + } + exports.ignoreElements = ignoreElements; + ; + var IgnoreElementsOperator = (function() { + function IgnoreElementsOperator() {} + IgnoreElementsOperator.prototype.call = function(subscriber) { + return new IgnoreElementsSubscriber(subscriber); + }; + return IgnoreElementsOperator; + })(); + var IgnoreElementsSubscriber = (function(_super) { + __extends(IgnoreElementsSubscriber, _super); + function IgnoreElementsSubscriber() { + _super.apply(this, arguments); + } + IgnoreElementsSubscriber.prototype._next = function(unused) { + noop_1.noop(); + }; + return IgnoreElementsSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/every", ["rxjs/observable/ScalarObservable", "rxjs/observable/fromArray", "rxjs/observable/throw", "rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var ScalarObservable_1 = require("rxjs/observable/ScalarObservable"); + var fromArray_1 = require("rxjs/observable/fromArray"); + var throw_1 = require("rxjs/observable/throw"); + var Subscriber_1 = require("rxjs/Subscriber"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + function every(predicate, thisArg) { + var source = this; + var result; + if (source._isScalar) { + result = tryCatch_1.tryCatch(predicate).call(thisArg || this, source.value, 0, source); + if (result === errorObject_1.errorObject) { + return new throw_1.ErrorObservable(errorObject_1.errorObject.e, source.scheduler); + } else { + return new ScalarObservable_1.ScalarObservable(result, source.scheduler); + } + } + if (source instanceof fromArray_1.ArrayObservable) { + var array = source.array; + var result_1 = tryCatch_1.tryCatch(function(array, predicate, thisArg) { + return array.every(predicate, thisArg); + })(array, predicate, thisArg); + if (result_1 === errorObject_1.errorObject) { + return new throw_1.ErrorObservable(errorObject_1.errorObject.e, source.scheduler); + } else { + return new ScalarObservable_1.ScalarObservable(result_1, source.scheduler); + } + } + return source.lift(new EveryOperator(predicate, thisArg, source)); + } + exports.every = every; + var EveryOperator = (function() { + function EveryOperator(predicate, thisArg, source) { + this.predicate = predicate; + this.thisArg = thisArg; + this.source = source; + } + EveryOperator.prototype.call = function(observer) { + return new EverySubscriber(observer, this.predicate, this.thisArg, this.source); + }; + return EveryOperator; + })(); + var EverySubscriber = (function(_super) { + __extends(EverySubscriber, _super); + function EverySubscriber(destination, predicate, thisArg, source) { + _super.call(this, destination); + this.predicate = predicate; + this.thisArg = thisArg; + this.source = source; + this.index = 0; + } + EverySubscriber.prototype.notifyComplete = function(everyValueMatch) { + this.destination.next(everyValueMatch); + this.destination.complete(); + }; + EverySubscriber.prototype._next = function(value) { + var result = tryCatch_1.tryCatch(this.predicate).call(this.thisArg || this, value, this.index++, this.source); + if (result === errorObject_1.errorObject) { + this.destination.error(result.e); + } else if (!result) { + this.notifyComplete(false); + } + }; + EverySubscriber.prototype._complete = function() { + this.notifyComplete(true); + }; + return EverySubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/last", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject", "rxjs/util/EmptyError"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + var EmptyError_1 = require("rxjs/util/EmptyError"); + function last(predicate, resultSelector, defaultValue) { + return this.lift(new LastOperator(predicate, resultSelector, defaultValue, this)); + } + exports.last = last; + var LastOperator = (function() { + function LastOperator(predicate, resultSelector, defaultValue, source) { + this.predicate = predicate; + this.resultSelector = resultSelector; + this.defaultValue = defaultValue; + this.source = source; + } + LastOperator.prototype.call = function(observer) { + return new LastSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source); + }; + return LastOperator; + })(); + var LastSubscriber = (function(_super) { + __extends(LastSubscriber, _super); + function LastSubscriber(destination, predicate, resultSelector, defaultValue, source) { + _super.call(this, destination); + this.predicate = predicate; + this.resultSelector = resultSelector; + this.defaultValue = defaultValue; + this.source = source; + this.hasValue = false; + this.index = 0; + if (typeof defaultValue !== 'undefined') { + this.lastValue = defaultValue; + this.hasValue = true; + } + } + LastSubscriber.prototype._next = function(value) { + var _a = this, + predicate = _a.predicate, + resultSelector = _a.resultSelector, + destination = _a.destination; + var index = this.index++; + if (predicate) { + var found = tryCatch_1.tryCatch(predicate)(value, index, this.source); + if (found === errorObject_1.errorObject) { + destination.error(errorObject_1.errorObject.e); + return ; + } + if (found) { + if (resultSelector) { + var result = tryCatch_1.tryCatch(resultSelector)(value, index); + if (result === errorObject_1.errorObject) { + destination.error(errorObject_1.errorObject.e); + return ; + } + this.lastValue = result; + } else { + this.lastValue = value; + } + this.hasValue = true; + } + } else { + this.lastValue = value; + this.hasValue = true; + } + }; + LastSubscriber.prototype._complete = function() { + var destination = this.destination; + if (this.hasValue) { + destination.next(this.lastValue); + destination.complete(); + } else { + destination.error(new EmptyError_1.EmptyError); + } + }; + return LastSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/map", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + function map(project, thisArg) { + if (typeof project !== 'function') { + throw new TypeError('argument is not a function. Are you looking for `mapTo()`?'); + } + return this.lift(new MapOperator(project, thisArg)); + } + exports.map = map; + var MapOperator = (function() { + function MapOperator(project, thisArg) { + this.project = project; + this.thisArg = thisArg; + } + MapOperator.prototype.call = function(subscriber) { + return new MapSubscriber(subscriber, this.project, this.thisArg); + }; + return MapOperator; + })(); + var MapSubscriber = (function(_super) { + __extends(MapSubscriber, _super); + function MapSubscriber(destination, project, thisArg) { + _super.call(this, destination); + this.project = project; + this.thisArg = thisArg; + this.count = 0; + } + MapSubscriber.prototype._next = function(x) { + var result = tryCatch_1.tryCatch(this.project).call(this.thisArg || this, x, this.count++); + if (result === errorObject_1.errorObject) { + this.error(errorObject_1.errorObject.e); + } else { + this.destination.next(result); + } + }; + return MapSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/mapTo", ["rxjs/Subscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + function mapTo(value) { + return this.lift(new MapToOperator(value)); + } + exports.mapTo = mapTo; + var MapToOperator = (function() { + function MapToOperator(value) { + this.value = value; + } + MapToOperator.prototype.call = function(subscriber) { + return new MapToSubscriber(subscriber, this.value); + }; + return MapToOperator; + })(); + var MapToSubscriber = (function(_super) { + __extends(MapToSubscriber, _super); + function MapToSubscriber(destination, value) { + _super.call(this, destination); + this.value = value; + } + MapToSubscriber.prototype._next = function(x) { + this.destination.next(this.value); + }; + return MapToSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/materialize", ["rxjs/Subscriber", "rxjs/Notification"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var Notification_1 = require("rxjs/Notification"); + function materialize() { + return this.lift(new MaterializeOperator()); + } + exports.materialize = materialize; + var MaterializeOperator = (function() { + function MaterializeOperator() {} + MaterializeOperator.prototype.call = function(subscriber) { + return new MaterializeSubscriber(subscriber); + }; + return MaterializeOperator; + })(); + var MaterializeSubscriber = (function(_super) { + __extends(MaterializeSubscriber, _super); + function MaterializeSubscriber(destination) { + _super.call(this, destination); + } + MaterializeSubscriber.prototype._next = function(value) { + this.destination.next(Notification_1.Notification.createNext(value)); + }; + MaterializeSubscriber.prototype._error = function(err) { + var destination = this.destination; + destination.next(Notification_1.Notification.createError(err)); + destination.complete(); + }; + MaterializeSubscriber.prototype._complete = function() { + var destination = this.destination; + destination.next(Notification_1.Notification.createComplete()); + destination.complete(); + }; + return MaterializeSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/merge", ["rxjs/operator/merge-static"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var merge_static_1 = require("rxjs/operator/merge-static"); + function merge() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; + } + observables.unshift(this); + return merge_static_1.merge.apply(this, observables); + } + exports.merge = merge; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/mergeAll", ["rxjs/operator/mergeAll-support"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var mergeAll_support_1 = require("rxjs/operator/mergeAll-support"); + function mergeAll(concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + return this.lift(new mergeAll_support_1.MergeAllOperator(concurrent)); + } + exports.mergeAll = mergeAll; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/mergeMap", ["rxjs/operator/mergeMap-support"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var mergeMap_support_1 = require("rxjs/operator/mergeMap-support"); + function mergeMap(project, resultSelector, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + return this.lift(new mergeMap_support_1.MergeMapOperator(project, resultSelector, concurrent)); + } + exports.mergeMap = mergeMap; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/mergeMapTo", ["rxjs/operator/mergeMapTo-support"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var mergeMapTo_support_1 = require("rxjs/operator/mergeMapTo-support"); + function mergeMapTo(observable, resultSelector, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + return this.lift(new mergeMapTo_support_1.MergeMapToOperator(observable, resultSelector, concurrent)); + } + exports.mergeMapTo = mergeMapTo; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/ConnectableObservable", ["rxjs/Observable", "rxjs/Subscription", "rxjs/Subscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Observable_1 = require("rxjs/Observable"); + var Subscription_1 = require("rxjs/Subscription"); + var Subscriber_1 = require("rxjs/Subscriber"); + var ConnectableObservable = (function(_super) { + __extends(ConnectableObservable, _super); + function ConnectableObservable(source, subjectFactory) { + _super.call(this); + this.source = source; + this.subjectFactory = subjectFactory; + } + ConnectableObservable.prototype._subscribe = function(subscriber) { + return this._getSubject().subscribe(subscriber); + }; + ConnectableObservable.prototype._getSubject = function() { + var subject = this.subject; + if (subject && !subject.isUnsubscribed) { + return subject; + } + return (this.subject = this.subjectFactory()); + }; + ConnectableObservable.prototype.connect = function() { + var source = this.source; + var subscription = this.subscription; + if (subscription && !subscription.isUnsubscribed) { + return subscription; + } + subscription = source.subscribe(this._getSubject()); + subscription.add(new ConnectableSubscription(this)); + return (this.subscription = subscription); + }; + ConnectableObservable.prototype.refCount = function() { + return new RefCountObservable(this); + }; + return ConnectableObservable; + })(Observable_1.Observable); + exports.ConnectableObservable = ConnectableObservable; + var ConnectableSubscription = (function(_super) { + __extends(ConnectableSubscription, _super); + function ConnectableSubscription(connectable) { + _super.call(this); + this.connectable = connectable; + } + ConnectableSubscription.prototype._unsubscribe = function() { + var connectable = this.connectable; + connectable.subject = void 0; + connectable.subscription = void 0; + this.connectable = void 0; + }; + return ConnectableSubscription; + })(Subscription_1.Subscription); + var RefCountObservable = (function(_super) { + __extends(RefCountObservable, _super); + function RefCountObservable(connectable, refCount) { + if (refCount === void 0) { + refCount = 0; + } + _super.call(this); + this.connectable = connectable; + this.refCount = refCount; + } + RefCountObservable.prototype._subscribe = function(subscriber) { + var connectable = this.connectable; + var refCountSubscriber = new RefCountSubscriber(subscriber, this); + var subscription = connectable.subscribe(refCountSubscriber); + if (!subscription.isUnsubscribed && ++this.refCount === 1) { + refCountSubscriber.connection = this.connection = connectable.connect(); + } + return subscription; + }; + return RefCountObservable; + })(Observable_1.Observable); + var RefCountSubscriber = (function(_super) { + __extends(RefCountSubscriber, _super); + function RefCountSubscriber(destination, refCountObservable) { + _super.call(this, null); + this.destination = destination; + this.refCountObservable = refCountObservable; + this.connection = refCountObservable.connection; + destination.add(this); + } + RefCountSubscriber.prototype._next = function(value) { + this.destination.next(value); + }; + RefCountSubscriber.prototype._error = function(err) { + this._resetConnectable(); + this.destination.error(err); + }; + RefCountSubscriber.prototype._complete = function() { + this._resetConnectable(); + this.destination.complete(); + }; + RefCountSubscriber.prototype._resetConnectable = function() { + var observable = this.refCountObservable; + var obsConnection = observable.connection; + var subConnection = this.connection; + if (subConnection && subConnection === obsConnection) { + observable.refCount = 0; + obsConnection.unsubscribe(); + observable.connection = void 0; + this.unsubscribe(); + } + }; + RefCountSubscriber.prototype._unsubscribe = function() { + var observable = this.refCountObservable; + if (observable.refCount === 0) { + return ; + } + if (--observable.refCount === 0) { + var obsConnection = observable.connection; + var subConnection = this.connection; + if (subConnection && subConnection === obsConnection) { + obsConnection.unsubscribe(); + observable.connection = void 0; + } + } + }; + return RefCountSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/observeOn", ["rxjs/operator/observeOn-support"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var observeOn_support_1 = require("rxjs/operator/observeOn-support"); + function observeOn(scheduler, delay) { + if (delay === void 0) { + delay = 0; + } + return this.lift(new observeOn_support_1.ObserveOnOperator(scheduler, delay)); + } + exports.observeOn = observeOn; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/not", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + function not(pred, thisArg) { + function notPred() { + return !(notPred.pred.apply(notPred.thisArg, arguments)); + } + notPred.pred = pred; + notPred.thisArg = thisArg; + return notPred; + } + exports.not = not; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/publish", ["rxjs/Subject", "rxjs/operator/multicast"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Subject_1 = require("rxjs/Subject"); + var multicast_1 = require("rxjs/operator/multicast"); + function publish() { + return multicast_1.multicast.call(this, new Subject_1.Subject()); + } + exports.publish = publish; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/ObjectUnsubscribedError", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var ObjectUnsubscribedError = (function(_super) { + __extends(ObjectUnsubscribedError, _super); + function ObjectUnsubscribedError() { + _super.call(this, 'object unsubscribed'); + this.name = 'ObjectUnsubscribedError'; + } + return ObjectUnsubscribedError; + })(Error); + exports.ObjectUnsubscribedError = ObjectUnsubscribedError; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/subject/ReplaySubject", ["rxjs/Subject", "rxjs/scheduler/queue"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subject_1 = require("rxjs/Subject"); + var queue_1 = require("rxjs/scheduler/queue"); + var ReplaySubject = (function(_super) { + __extends(ReplaySubject, _super); + function ReplaySubject(bufferSize, windowTime, scheduler) { + if (bufferSize === void 0) { + bufferSize = Number.POSITIVE_INFINITY; + } + if (windowTime === void 0) { + windowTime = Number.POSITIVE_INFINITY; + } + _super.call(this); + this.events = []; + this.bufferSize = bufferSize < 1 ? 1 : bufferSize; + this._windowTime = windowTime < 1 ? 1 : windowTime; + this.scheduler = scheduler; + } + ReplaySubject.prototype._next = function(value) { + var now = this._getNow(); + this.events.push(new ReplayEvent(now, value)); + this._trimBufferThenGetEvents(now); + _super.prototype._next.call(this, value); + }; + ReplaySubject.prototype._subscribe = function(subscriber) { + var events = this._trimBufferThenGetEvents(this._getNow()); + var index = -1; + var len = events.length; + while (!subscriber.isUnsubscribed && ++index < len) { + subscriber.next(events[index].value); + } + return _super.prototype._subscribe.call(this, subscriber); + }; + ReplaySubject.prototype._getNow = function() { + return (this.scheduler || queue_1.queue).now(); + }; + ReplaySubject.prototype._trimBufferThenGetEvents = function(now) { + var bufferSize = this.bufferSize; + var _windowTime = this._windowTime; + var events = this.events; + var eventsCount = events.length; + var spliceCount = 0; + while (spliceCount < eventsCount) { + if ((now - events[spliceCount].time) < _windowTime) { + break; + } + spliceCount += 1; + } + if (eventsCount > bufferSize) { + spliceCount = Math.max(spliceCount, eventsCount - bufferSize); + } + if (spliceCount > 0) { + events.splice(0, spliceCount); + } + return events; + }; + return ReplaySubject; + })(Subject_1.Subject); + exports.ReplaySubject = ReplaySubject; + var ReplayEvent = (function() { + function ReplayEvent(time, value) { + this.time = time; + this.value = value; + } + return ReplayEvent; + })(); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/publishLast", ["rxjs/subject/AsyncSubject", "rxjs/operator/multicast"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var AsyncSubject_1 = require("rxjs/subject/AsyncSubject"); + var multicast_1 = require("rxjs/operator/multicast"); + function publishLast() { + return multicast_1.multicast.call(this, new AsyncSubject_1.AsyncSubject()); + } + exports.publishLast = publishLast; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/reduce-support", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + var ReduceOperator = (function() { + function ReduceOperator(project, seed) { + this.project = project; + this.seed = seed; + } + ReduceOperator.prototype.call = function(subscriber) { + return new ReduceSubscriber(subscriber, this.project, this.seed); + }; + return ReduceOperator; + })(); + exports.ReduceOperator = ReduceOperator; + var ReduceSubscriber = (function(_super) { + __extends(ReduceSubscriber, _super); + function ReduceSubscriber(destination, project, seed) { + _super.call(this, destination); + this.hasValue = false; + this.acc = seed; + this.project = project; + this.hasSeed = typeof seed !== 'undefined'; + } + ReduceSubscriber.prototype._next = function(x) { + if (this.hasValue || (this.hasValue = this.hasSeed)) { + var result = tryCatch_1.tryCatch(this.project).call(this, this.acc, x); + if (result === errorObject_1.errorObject) { + this.destination.error(errorObject_1.errorObject.e); + } else { + this.acc = result; + } + } else { + this.acc = x; + this.hasValue = true; + } + }; + ReduceSubscriber.prototype._complete = function() { + if (this.hasValue || this.hasSeed) { + this.destination.next(this.acc); + } + this.destination.complete(); + }; + return ReduceSubscriber; + })(Subscriber_1.Subscriber); + exports.ReduceSubscriber = ReduceSubscriber; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/repeat", ["rxjs/Subscriber", "rxjs/observable/empty"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var empty_1 = require("rxjs/observable/empty"); + function repeat(count) { + if (count === void 0) { + count = -1; + } + if (count === 0) { + return new empty_1.EmptyObservable(); + } else { + return this.lift(new RepeatOperator(count, this)); + } + } + exports.repeat = repeat; + var RepeatOperator = (function() { + function RepeatOperator(count, source) { + this.count = count; + this.source = source; + } + RepeatOperator.prototype.call = function(subscriber) { + return new FirstRepeatSubscriber(subscriber, this.count, this.source); + }; + return RepeatOperator; + })(); + var FirstRepeatSubscriber = (function(_super) { + __extends(FirstRepeatSubscriber, _super); + function FirstRepeatSubscriber(destination, count, source) { + _super.call(this); + this.destination = destination; + this.count = count; + this.source = source; + destination.add(this); + this.lastSubscription = this; + } + FirstRepeatSubscriber.prototype._next = function(value) { + this.destination.next(value); + }; + FirstRepeatSubscriber.prototype._error = function(err) { + this.destination.error(err); + }; + FirstRepeatSubscriber.prototype.complete = function() { + if (!this.isUnsubscribed) { + this.resubscribe(this.count); + } + }; + FirstRepeatSubscriber.prototype.unsubscribe = function() { + var lastSubscription = this.lastSubscription; + if (lastSubscription === this) { + _super.prototype.unsubscribe.call(this); + } else { + lastSubscription.unsubscribe(); + } + }; + FirstRepeatSubscriber.prototype.resubscribe = function(count) { + var _a = this, + destination = _a.destination, + lastSubscription = _a.lastSubscription; + destination.remove(lastSubscription); + lastSubscription.unsubscribe(); + if (count - 1 === 0) { + destination.complete(); + } else { + var nextSubscriber = new MoreRepeatSubscriber(this, count - 1); + this.lastSubscription = this.source.subscribe(nextSubscriber); + destination.add(this.lastSubscription); + } + }; + return FirstRepeatSubscriber; + })(Subscriber_1.Subscriber); + var MoreRepeatSubscriber = (function(_super) { + __extends(MoreRepeatSubscriber, _super); + function MoreRepeatSubscriber(parent, count) { + _super.call(this); + this.parent = parent; + this.count = count; + } + MoreRepeatSubscriber.prototype._next = function(value) { + this.parent.destination.next(value); + }; + MoreRepeatSubscriber.prototype._error = function(err) { + this.parent.destination.error(err); + }; + MoreRepeatSubscriber.prototype._complete = function() { + var count = this.count; + this.parent.resubscribe(count < 0 ? -1 : count); + }; + return MoreRepeatSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/retry", ["rxjs/Subscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + function retry(count) { + if (count === void 0) { + count = 0; + } + return this.lift(new RetryOperator(count, this)); + } + exports.retry = retry; + var RetryOperator = (function() { + function RetryOperator(count, source) { + this.count = count; + this.source = source; + } + RetryOperator.prototype.call = function(subscriber) { + return new FirstRetrySubscriber(subscriber, this.count, this.source); + }; + return RetryOperator; + })(); + var FirstRetrySubscriber = (function(_super) { + __extends(FirstRetrySubscriber, _super); + function FirstRetrySubscriber(destination, count, source) { + _super.call(this); + this.destination = destination; + this.count = count; + this.source = source; + destination.add(this); + this.lastSubscription = this; + } + FirstRetrySubscriber.prototype._next = function(value) { + this.destination.next(value); + }; + FirstRetrySubscriber.prototype.error = function(error) { + if (!this.isUnsubscribed) { + this.unsubscribe(); + this.resubscribe(); + } + }; + FirstRetrySubscriber.prototype._complete = function() { + this.unsubscribe(); + this.destination.complete(); + }; + FirstRetrySubscriber.prototype.resubscribe = function(retried) { + if (retried === void 0) { + retried = 0; + } + var _a = this, + lastSubscription = _a.lastSubscription, + destination = _a.destination; + destination.remove(lastSubscription); + lastSubscription.unsubscribe(); + var nextSubscriber = new RetryMoreSubscriber(this, this.count, retried + 1); + this.lastSubscription = this.source.subscribe(nextSubscriber); + destination.add(this.lastSubscription); + }; + return FirstRetrySubscriber; + })(Subscriber_1.Subscriber); + var RetryMoreSubscriber = (function(_super) { + __extends(RetryMoreSubscriber, _super); + function RetryMoreSubscriber(parent, count, retried) { + if (retried === void 0) { + retried = 0; + } + _super.call(this, null); + this.parent = parent; + this.count = count; + this.retried = retried; + } + RetryMoreSubscriber.prototype._next = function(value) { + this.parent.destination.next(value); + }; + RetryMoreSubscriber.prototype._error = function(err) { + var parent = this.parent; + var retried = this.retried; + var count = this.count; + if (count && retried === count) { + parent.destination.error(err); + } else { + parent.resubscribe(retried); + } + }; + RetryMoreSubscriber.prototype._complete = function() { + this.parent.destination.complete(); + }; + return RetryMoreSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/retryWhen", ["rxjs/Subscriber", "rxjs/Subject", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var Subject_1 = require("rxjs/Subject"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + function retryWhen(notifier) { + return this.lift(new RetryWhenOperator(notifier, this)); + } + exports.retryWhen = retryWhen; + var RetryWhenOperator = (function() { + function RetryWhenOperator(notifier, source) { + this.notifier = notifier; + this.source = source; + } + RetryWhenOperator.prototype.call = function(subscriber) { + return new FirstRetryWhenSubscriber(subscriber, this.notifier, this.source); + }; + return RetryWhenOperator; + })(); + var FirstRetryWhenSubscriber = (function(_super) { + __extends(FirstRetryWhenSubscriber, _super); + function FirstRetryWhenSubscriber(destination, notifier, source) { + _super.call(this); + this.destination = destination; + this.notifier = notifier; + this.source = source; + destination.add(this); + this.lastSubscription = this; + } + FirstRetryWhenSubscriber.prototype._next = function(value) { + this.destination.next(value); + }; + FirstRetryWhenSubscriber.prototype.error = function(err) { + var destination = this.destination; + if (!this.isUnsubscribed) { + _super.prototype.unsubscribe.call(this); + if (!this.retryNotifications) { + this.errors = new Subject_1.Subject(); + var notifications = tryCatch_1.tryCatch(this.notifier).call(this, this.errors); + if (notifications === errorObject_1.errorObject) { + destination.error(errorObject_1.errorObject.e); + } else { + this.retryNotifications = notifications; + var notificationSubscriber = new RetryNotificationSubscriber(this); + this.notificationSubscription = notifications.subscribe(notificationSubscriber); + destination.add(this.notificationSubscription); + } + } + this.errors.next(err); + } + }; + FirstRetryWhenSubscriber.prototype.destinationError = function(err) { + this.tearDown(); + this.destination.error(err); + }; + FirstRetryWhenSubscriber.prototype._complete = function() { + this.destinationComplete(); + }; + FirstRetryWhenSubscriber.prototype.destinationComplete = function() { + this.tearDown(); + this.destination.complete(); + }; + FirstRetryWhenSubscriber.prototype.unsubscribe = function() { + var lastSubscription = this.lastSubscription; + if (lastSubscription === this) { + _super.prototype.unsubscribe.call(this); + } else { + this.tearDown(); + } + }; + FirstRetryWhenSubscriber.prototype.tearDown = function() { + _super.prototype.unsubscribe.call(this); + this.lastSubscription.unsubscribe(); + var notificationSubscription = this.notificationSubscription; + if (notificationSubscription) { + notificationSubscription.unsubscribe(); + } + }; + FirstRetryWhenSubscriber.prototype.resubscribe = function() { + var _a = this, + destination = _a.destination, + lastSubscription = _a.lastSubscription; + destination.remove(lastSubscription); + lastSubscription.unsubscribe(); + var nextSubscriber = new MoreRetryWhenSubscriber(this); + this.lastSubscription = this.source.subscribe(nextSubscriber); + destination.add(this.lastSubscription); + }; + return FirstRetryWhenSubscriber; + })(Subscriber_1.Subscriber); + var MoreRetryWhenSubscriber = (function(_super) { + __extends(MoreRetryWhenSubscriber, _super); + function MoreRetryWhenSubscriber(parent) { + _super.call(this, null); + this.parent = parent; + } + MoreRetryWhenSubscriber.prototype._next = function(value) { + this.parent.destination.next(value); + }; + MoreRetryWhenSubscriber.prototype._error = function(err) { + this.parent.errors.next(err); + }; + MoreRetryWhenSubscriber.prototype._complete = function() { + this.parent.destinationComplete(); + }; + return MoreRetryWhenSubscriber; + })(Subscriber_1.Subscriber); + var RetryNotificationSubscriber = (function(_super) { + __extends(RetryNotificationSubscriber, _super); + function RetryNotificationSubscriber(parent) { + _super.call(this, null); + this.parent = parent; + } + RetryNotificationSubscriber.prototype._next = function(value) { + this.parent.resubscribe(); + }; + RetryNotificationSubscriber.prototype._error = function(err) { + this.parent.destinationError(err); + }; + RetryNotificationSubscriber.prototype._complete = function() { + this.parent.destinationComplete(); + }; + return RetryNotificationSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/sample", ["rxjs/Subscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + function sample(notifier) { + return this.lift(new SampleOperator(notifier)); + } + exports.sample = sample; + var SampleOperator = (function() { + function SampleOperator(notifier) { + this.notifier = notifier; + } + SampleOperator.prototype.call = function(subscriber) { + return new SampleSubscriber(subscriber, this.notifier); + }; + return SampleOperator; + })(); + var SampleSubscriber = (function(_super) { + __extends(SampleSubscriber, _super); + function SampleSubscriber(destination, notifier) { + _super.call(this, destination); + this.notifier = notifier; + this.hasValue = false; + this.add(notifier._subscribe(new SampleNotificationSubscriber(this))); + } + SampleSubscriber.prototype._next = function(value) { + this.lastValue = value; + this.hasValue = true; + }; + SampleSubscriber.prototype.notifyNext = function() { + if (this.hasValue) { + this.hasValue = false; + this.destination.next(this.lastValue); + } + }; + return SampleSubscriber; + })(Subscriber_1.Subscriber); + var SampleNotificationSubscriber = (function(_super) { + __extends(SampleNotificationSubscriber, _super); + function SampleNotificationSubscriber(parent) { + _super.call(this, null); + this.parent = parent; + } + SampleNotificationSubscriber.prototype._next = function() { + this.parent.notifyNext(); + }; + SampleNotificationSubscriber.prototype._error = function(err) { + this.parent.error(err); + }; + SampleNotificationSubscriber.prototype._complete = function() { + this.parent.notifyNext(); + }; + return SampleNotificationSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/sampleTime", ["rxjs/Subscriber", "rxjs/scheduler/asap"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var asap_1 = require("rxjs/scheduler/asap"); + function sampleTime(delay, scheduler) { + if (scheduler === void 0) { + scheduler = asap_1.asap; + } + return this.lift(new SampleTimeOperator(delay, scheduler)); + } + exports.sampleTime = sampleTime; + var SampleTimeOperator = (function() { + function SampleTimeOperator(delay, scheduler) { + this.delay = delay; + this.scheduler = scheduler; + } + SampleTimeOperator.prototype.call = function(subscriber) { + return new SampleTimeSubscriber(subscriber, this.delay, this.scheduler); + }; + return SampleTimeOperator; + })(); + var SampleTimeSubscriber = (function(_super) { + __extends(SampleTimeSubscriber, _super); + function SampleTimeSubscriber(destination, delay, scheduler) { + _super.call(this, destination); + this.delay = delay; + this.scheduler = scheduler; + this.hasValue = false; + this.add(scheduler.schedule(dispatchNotification, delay, { + subscriber: this, + delay: delay + })); + } + SampleTimeSubscriber.prototype._next = function(value) { + this.lastValue = value; + this.hasValue = true; + }; + SampleTimeSubscriber.prototype.notifyNext = function() { + if (this.hasValue) { + this.hasValue = false; + this.destination.next(this.lastValue); + } + }; + return SampleTimeSubscriber; + })(Subscriber_1.Subscriber); + function dispatchNotification(state) { + var subscriber = state.subscriber, + delay = state.delay; + subscriber.notifyNext(); + this.schedule(state, delay); + } + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/scan", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + function scan(accumulator, seed) { + return this.lift(new ScanOperator(accumulator, seed)); + } + exports.scan = scan; + var ScanOperator = (function() { + function ScanOperator(accumulator, seed) { + this.accumulator = accumulator; + this.seed = seed; + } + ScanOperator.prototype.call = function(subscriber) { + return new ScanSubscriber(subscriber, this.accumulator, this.seed); + }; + return ScanOperator; + })(); + var ScanSubscriber = (function(_super) { + __extends(ScanSubscriber, _super); + function ScanSubscriber(destination, accumulator, seed) { + _super.call(this, destination); + this.accumulator = accumulator; + this.accumulatorSet = false; + this.seed = seed; + this.accumulator = accumulator; + this.accumulatorSet = typeof seed !== 'undefined'; + } + Object.defineProperty(ScanSubscriber.prototype, "seed", { + get: function() { + return this._seed; + }, + set: function(value) { + this.accumulatorSet = true; + this._seed = value; + }, + enumerable: true, + configurable: true + }); + ScanSubscriber.prototype._next = function(value) { + if (!this.accumulatorSet) { + this.seed = value; + this.destination.next(value); + } else { + var result = tryCatch_1.tryCatch(this.accumulator).call(this, this.seed, value); + if (result === errorObject_1.errorObject) { + this.destination.error(errorObject_1.errorObject.e); + } else { + this.seed = result; + this.destination.next(this.seed); + } + } + }; + return ScanSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/share", ["rxjs/operator/multicast", "rxjs/Subject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var multicast_1 = require("rxjs/operator/multicast"); + var Subject_1 = require("rxjs/Subject"); + function shareSubjectFactory() { + return new Subject_1.Subject(); + } + function share() { + return multicast_1.multicast.call(this, shareSubjectFactory).refCount(); + } + exports.share = share; + ; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/single", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject", "rxjs/util/EmptyError"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + var EmptyError_1 = require("rxjs/util/EmptyError"); + function single(predicate) { + return this.lift(new SingleOperator(predicate, this)); + } + exports.single = single; + var SingleOperator = (function() { + function SingleOperator(predicate, source) { + this.predicate = predicate; + this.source = source; + } + SingleOperator.prototype.call = function(subscriber) { + return new SingleSubscriber(subscriber, this.predicate, this.source); + }; + return SingleOperator; + })(); + var SingleSubscriber = (function(_super) { + __extends(SingleSubscriber, _super); + function SingleSubscriber(destination, predicate, source) { + _super.call(this, destination); + this.predicate = predicate; + this.source = source; + this.seenValue = false; + this.index = 0; + } + SingleSubscriber.prototype.applySingleValue = function(value) { + if (this.seenValue) { + this.destination.error('Sequence contains more than one element'); + } else { + this.seenValue = true; + this.singleValue = value; + } + }; + SingleSubscriber.prototype._next = function(value) { + var predicate = this.predicate; + var currentIndex = this.index++; + if (predicate) { + var result = tryCatch_1.tryCatch(predicate)(value, currentIndex, this.source); + if (result === errorObject_1.errorObject) { + this.destination.error(result.e); + } else if (result) { + this.applySingleValue(value); + } + } else { + this.applySingleValue(value); + } + }; + SingleSubscriber.prototype._complete = function() { + var destination = this.destination; + if (this.index > 0) { + destination.next(this.seenValue ? this.singleValue : undefined); + destination.complete(); + } else { + destination.error(new EmptyError_1.EmptyError); + } + }; + return SingleSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/skip", ["rxjs/Subscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + function skip(total) { + return this.lift(new SkipOperator(total)); + } + exports.skip = skip; + var SkipOperator = (function() { + function SkipOperator(total) { + this.total = total; + } + SkipOperator.prototype.call = function(subscriber) { + return new SkipSubscriber(subscriber, this.total); + }; + return SkipOperator; + })(); + var SkipSubscriber = (function(_super) { + __extends(SkipSubscriber, _super); + function SkipSubscriber(destination, total) { + _super.call(this, destination); + this.total = total; + this.count = 0; + } + SkipSubscriber.prototype._next = function(x) { + if (++this.count > this.total) { + this.destination.next(x); + } + }; + return SkipSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/skipUntil", ["rxjs/Subscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + function skipUntil(notifier) { + return this.lift(new SkipUntilOperator(notifier)); + } + exports.skipUntil = skipUntil; + var SkipUntilOperator = (function() { + function SkipUntilOperator(notifier) { + this.notifier = notifier; + } + SkipUntilOperator.prototype.call = function(subscriber) { + return new SkipUntilSubscriber(subscriber, this.notifier); + }; + return SkipUntilOperator; + })(); + var SkipUntilSubscriber = (function(_super) { + __extends(SkipUntilSubscriber, _super); + function SkipUntilSubscriber(destination, notifier) { + _super.call(this, destination); + this.notifier = notifier; + this.notificationSubscriber = null; + this.notificationSubscriber = new NotificationSubscriber(this); + this.add(this.notifier.subscribe(this.notificationSubscriber)); + } + SkipUntilSubscriber.prototype._next = function(value) { + if (this.notificationSubscriber.hasValue) { + this.destination.next(value); + } + }; + SkipUntilSubscriber.prototype._error = function(err) { + this.destination.error(err); + }; + SkipUntilSubscriber.prototype._complete = function() { + if (this.notificationSubscriber.hasCompleted) { + this.destination.complete(); + } + this.notificationSubscriber.unsubscribe(); + }; + SkipUntilSubscriber.prototype.unsubscribe = function() { + if (this._isUnsubscribed) { + return ; + } else if (this._subscription) { + this._subscription.unsubscribe(); + this._isUnsubscribed = true; + } else { + _super.prototype.unsubscribe.call(this); + } + }; + return SkipUntilSubscriber; + })(Subscriber_1.Subscriber); + var NotificationSubscriber = (function(_super) { + __extends(NotificationSubscriber, _super); + function NotificationSubscriber(parent) { + _super.call(this, null); + this.parent = parent; + this.hasValue = false; + this.hasCompleted = false; + } + NotificationSubscriber.prototype._next = function(unused) { + this.hasValue = true; + }; + NotificationSubscriber.prototype._error = function(err) { + this.parent.error(err); + this.hasValue = true; + }; + NotificationSubscriber.prototype._complete = function() { + this.hasCompleted = true; + }; + return NotificationSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/skipWhile", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + function skipWhile(predicate) { + return this.lift(new SkipWhileOperator(predicate)); + } + exports.skipWhile = skipWhile; + var SkipWhileOperator = (function() { + function SkipWhileOperator(predicate) { + this.predicate = predicate; + } + SkipWhileOperator.prototype.call = function(subscriber) { + return new SkipWhileSubscriber(subscriber, this.predicate); + }; + return SkipWhileOperator; + })(); + var SkipWhileSubscriber = (function(_super) { + __extends(SkipWhileSubscriber, _super); + function SkipWhileSubscriber(destination, predicate) { + _super.call(this, destination); + this.predicate = predicate; + this.skipping = true; + this.index = 0; + } + SkipWhileSubscriber.prototype._next = function(value) { + var destination = this.destination; + if (this.skipping === true) { + var index = this.index++; + var result = tryCatch_1.tryCatch(this.predicate)(value, index); + if (result === errorObject_1.errorObject) { + destination.error(result.e); + } else { + this.skipping = Boolean(result); + } + } + if (this.skipping === false) { + destination.next(value); + } + }; + return SkipWhileSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/startWith", ["rxjs/observable/fromArray", "rxjs/observable/ScalarObservable", "rxjs/observable/empty", "rxjs/operator/concat-static", "rxjs/util/isScheduler"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var fromArray_1 = require("rxjs/observable/fromArray"); + var ScalarObservable_1 = require("rxjs/observable/ScalarObservable"); + var empty_1 = require("rxjs/observable/empty"); + var concat_static_1 = require("rxjs/operator/concat-static"); + var isScheduler_1 = require("rxjs/util/isScheduler"); + function startWith() { + var array = []; + for (var _i = 0; _i < arguments.length; _i++) { + array[_i - 0] = arguments[_i]; + } + var scheduler = array[array.length - 1]; + if (isScheduler_1.isScheduler(scheduler)) { + array.pop(); + } else { + scheduler = void 0; + } + var len = array.length; + if (len === 1) { + return concat_static_1.concat(new ScalarObservable_1.ScalarObservable(array[0], scheduler), this); + } else if (len > 1) { + return concat_static_1.concat(new fromArray_1.ArrayObservable(array, scheduler), this); + } else { + return concat_static_1.concat(new empty_1.EmptyObservable(scheduler), this); + } + } + exports.startWith = startWith; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/SubscribeOnObservable", ["rxjs/Observable", "rxjs/scheduler/asap", "rxjs/util/isNumeric"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Observable_1 = require("rxjs/Observable"); + var asap_1 = require("rxjs/scheduler/asap"); + var isNumeric_1 = require("rxjs/util/isNumeric"); + var SubscribeOnObservable = (function(_super) { + __extends(SubscribeOnObservable, _super); + function SubscribeOnObservable(source, delayTime, scheduler) { + if (delayTime === void 0) { + delayTime = 0; + } + if (scheduler === void 0) { + scheduler = asap_1.asap; + } + _super.call(this); + this.source = source; + this.delayTime = delayTime; + this.scheduler = scheduler; + if (!isNumeric_1.isNumeric(delayTime) || delayTime < 0) { + this.delayTime = 0; + } + if (!scheduler || typeof scheduler.schedule !== 'function') { + this.scheduler = asap_1.asap; + } + } + SubscribeOnObservable.create = function(source, delay, scheduler) { + if (delay === void 0) { + delay = 0; + } + if (scheduler === void 0) { + scheduler = asap_1.asap; + } + return new SubscribeOnObservable(source, delay, scheduler); + }; + SubscribeOnObservable.dispatch = function(_a) { + var source = _a.source, + subscriber = _a.subscriber; + return source.subscribe(subscriber); + }; + SubscribeOnObservable.prototype._subscribe = function(subscriber) { + var delay = this.delayTime; + var source = this.source; + var scheduler = this.scheduler; + subscriber.add(scheduler.schedule(SubscribeOnObservable.dispatch, delay, { + source: source, + subscriber: subscriber + })); + }; + return SubscribeOnObservable; + })(Observable_1.Observable); + exports.SubscribeOnObservable = SubscribeOnObservable; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/switch", ["rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); + function _switch() { + return this.lift(new SwitchOperator()); + } + exports._switch = _switch; + var SwitchOperator = (function() { + function SwitchOperator() {} + SwitchOperator.prototype.call = function(subscriber) { + return new SwitchSubscriber(subscriber); + }; + return SwitchOperator; + })(); + var SwitchSubscriber = (function(_super) { + __extends(SwitchSubscriber, _super); + function SwitchSubscriber(destination) { + _super.call(this, destination); + this.active = 0; + this.hasCompleted = false; + } + SwitchSubscriber.prototype._next = function(value) { + this.unsubscribeInner(); + this.active++; + this.add(this.innerSubscription = subscribeToResult_1.subscribeToResult(this, value)); + }; + SwitchSubscriber.prototype._complete = function() { + this.hasCompleted = true; + if (this.active === 0) { + this.destination.complete(); + } + }; + SwitchSubscriber.prototype.unsubscribeInner = function() { + this.active = this.active > 0 ? this.active - 1 : 0; + var innerSubscription = this.innerSubscription; + if (innerSubscription) { + innerSubscription.unsubscribe(); + this.remove(innerSubscription); + } + }; + SwitchSubscriber.prototype.notifyNext = function(outerValue, innerValue) { + this.destination.next(innerValue); + }; + SwitchSubscriber.prototype.notifyError = function(err) { + this.destination.error(err); + }; + SwitchSubscriber.prototype.notifyComplete = function() { + this.unsubscribeInner(); + if (this.hasCompleted && this.active === 0) { + this.destination.complete(); + } + }; + return SwitchSubscriber; + })(OuterSubscriber_1.OuterSubscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/switchMap", ["rxjs/util/tryCatch", "rxjs/util/errorObject", "rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); + function switchMap(project, resultSelector) { + return this.lift(new SwitchMapOperator(project, resultSelector)); + } + exports.switchMap = switchMap; + var SwitchMapOperator = (function() { + function SwitchMapOperator(project, resultSelector) { + this.project = project; + this.resultSelector = resultSelector; + } + SwitchMapOperator.prototype.call = function(subscriber) { + return new SwitchMapSubscriber(subscriber, this.project, this.resultSelector); + }; + return SwitchMapOperator; + })(); + var SwitchMapSubscriber = (function(_super) { + __extends(SwitchMapSubscriber, _super); + function SwitchMapSubscriber(destination, project, resultSelector) { + _super.call(this, destination); + this.project = project; + this.resultSelector = resultSelector; + this.hasCompleted = false; + this.index = 0; + } + SwitchMapSubscriber.prototype._next = function(value) { + var index = this.index++; + var destination = this.destination; + var result = tryCatch_1.tryCatch(this.project)(value, index); + if (result === errorObject_1.errorObject) { + destination.error(result.e); + } else { + var innerSubscription = this.innerSubscription; + if (innerSubscription) { + innerSubscription.unsubscribe(); + } + this.add(this.innerSubscription = subscribeToResult_1.subscribeToResult(this, result, value, index)); + } + }; + SwitchMapSubscriber.prototype._complete = function() { + var innerSubscription = this.innerSubscription; + this.hasCompleted = true; + if (!innerSubscription || innerSubscription.isUnsubscribed) { + this.destination.complete(); + } + }; + SwitchMapSubscriber.prototype.notifyComplete = function(innerSub) { + this.remove(innerSub); + var prevSubscription = this.innerSubscription; + if (prevSubscription) { + prevSubscription.unsubscribe(); + } + this.innerSubscription = null; + if (this.hasCompleted) { + this.destination.complete(); + } + }; + SwitchMapSubscriber.prototype.notifyError = function(err) { + this.destination.error(err); + }; + SwitchMapSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex) { + var _a = this, + resultSelector = _a.resultSelector, + destination = _a.destination; + if (resultSelector) { + var result = tryCatch_1.tryCatch(resultSelector)(outerValue, innerValue, outerIndex, innerIndex); + if (result === errorObject_1.errorObject) { + destination.error(errorObject_1.errorObject.e); + } else { + destination.next(result); + } + } else { + destination.next(innerValue); + } + }; + return SwitchMapSubscriber; + })(OuterSubscriber_1.OuterSubscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/switchMapTo", ["rxjs/util/tryCatch", "rxjs/util/errorObject", "rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); + function switchMapTo(observable, projectResult) { + return this.lift(new SwitchMapToOperator(observable, projectResult)); + } + exports.switchMapTo = switchMapTo; + var SwitchMapToOperator = (function() { + function SwitchMapToOperator(observable, resultSelector) { + this.observable = observable; + this.resultSelector = resultSelector; + } + SwitchMapToOperator.prototype.call = function(subscriber) { + return new SwitchMapToSubscriber(subscriber, this.observable, this.resultSelector); + }; + return SwitchMapToOperator; + })(); + var SwitchMapToSubscriber = (function(_super) { + __extends(SwitchMapToSubscriber, _super); + function SwitchMapToSubscriber(destination, inner, resultSelector) { + _super.call(this, destination); + this.inner = inner; + this.resultSelector = resultSelector; + this.hasCompleted = false; + this.index = 0; + } + SwitchMapToSubscriber.prototype._next = function(value) { + var index = this.index++; + var innerSubscription = this.innerSubscription; + if (innerSubscription) { + innerSubscription.unsubscribe(); + } + this.add(this.innerSubscription = subscribeToResult_1.subscribeToResult(this, this.inner, value, index)); + }; + SwitchMapToSubscriber.prototype._complete = function() { + var innerSubscription = this.innerSubscription; + this.hasCompleted = true; + if (!innerSubscription || innerSubscription.isUnsubscribed) { + this.destination.complete(); + } + }; + SwitchMapToSubscriber.prototype.notifyComplete = function(innerSub) { + this.remove(innerSub); + var prevSubscription = this.innerSubscription; + if (prevSubscription) { + prevSubscription.unsubscribe(); + } + this.innerSubscription = null; + if (this.hasCompleted) { + this.destination.complete(); + } + }; + SwitchMapToSubscriber.prototype.notifyError = function(err) { + this.destination.error(err); + }; + SwitchMapToSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex) { + var _a = this, + resultSelector = _a.resultSelector, + destination = _a.destination; + if (resultSelector) { + var result = tryCatch_1.tryCatch(resultSelector)(outerValue, innerValue, outerIndex, innerIndex); + if (result === errorObject_1.errorObject) { + destination.error(errorObject_1.errorObject.e); + } else { + destination.next(result); + } + } else { + destination.next(innerValue); + } + }; + return SwitchMapToSubscriber; + })(OuterSubscriber_1.OuterSubscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/ArgumentOutOfRangeError", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var ArgumentOutOfRangeError = (function() { + function ArgumentOutOfRangeError() { + this.name = 'ArgumentOutOfRangeError'; + this.message = 'argument out of range'; + } + return ArgumentOutOfRangeError; + })(); + exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/takeUntil", ["rxjs/Subscriber", "rxjs/util/noop"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var noop_1 = require("rxjs/util/noop"); + function takeUntil(notifier) { + return this.lift(new TakeUntilOperator(notifier)); + } + exports.takeUntil = takeUntil; + var TakeUntilOperator = (function() { + function TakeUntilOperator(notifier) { + this.notifier = notifier; + } + TakeUntilOperator.prototype.call = function(subscriber) { + return new TakeUntilSubscriber(subscriber, this.notifier); + }; + return TakeUntilOperator; + })(); + var TakeUntilSubscriber = (function(_super) { + __extends(TakeUntilSubscriber, _super); + function TakeUntilSubscriber(destination, notifier) { + _super.call(this, destination); + this.notifier = notifier; + this.notificationSubscriber = null; + this.notificationSubscriber = new TakeUntilInnerSubscriber(destination); + this.add(notifier.subscribe(this.notificationSubscriber)); + } + TakeUntilSubscriber.prototype._complete = function() { + this.destination.complete(); + this.notificationSubscriber.unsubscribe(); + }; + return TakeUntilSubscriber; + })(Subscriber_1.Subscriber); + var TakeUntilInnerSubscriber = (function(_super) { + __extends(TakeUntilInnerSubscriber, _super); + function TakeUntilInnerSubscriber(destination) { + _super.call(this, null); + this.destination = destination; + } + TakeUntilInnerSubscriber.prototype._next = function(unused) { + this.destination.complete(); + }; + TakeUntilInnerSubscriber.prototype._error = function(err) { + this.destination.error(err); + }; + TakeUntilInnerSubscriber.prototype._complete = function() { + noop_1.noop(); + }; + return TakeUntilInnerSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/takeWhile", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + function takeWhile(predicate) { + return this.lift(new TakeWhileOperator(predicate)); + } + exports.takeWhile = takeWhile; + var TakeWhileOperator = (function() { + function TakeWhileOperator(predicate) { + this.predicate = predicate; + } + TakeWhileOperator.prototype.call = function(subscriber) { + return new TakeWhileSubscriber(subscriber, this.predicate); + }; + return TakeWhileOperator; + })(); + var TakeWhileSubscriber = (function(_super) { + __extends(TakeWhileSubscriber, _super); + function TakeWhileSubscriber(destination, predicate) { + _super.call(this, destination); + this.predicate = predicate; + this.index = 0; + } + TakeWhileSubscriber.prototype._next = function(value) { + var destination = this.destination; + var result = tryCatch_1.tryCatch(this.predicate)(value, this.index++); + if (result == errorObject_1.errorObject) { + destination.error(result.e); + } else if (Boolean(result)) { + destination.next(value); + } else { + destination.complete(); + } + }; + return TakeWhileSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/throttle", ["rxjs/observable/fromPromise", "rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/isPromise", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var fromPromise_1 = require("rxjs/observable/fromPromise"); + var Subscriber_1 = require("rxjs/Subscriber"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var isPromise_1 = require("rxjs/util/isPromise"); + var errorObject_1 = require("rxjs/util/errorObject"); + function throttle(durationSelector) { + return this.lift(new ThrottleOperator(durationSelector)); + } + exports.throttle = throttle; + var ThrottleOperator = (function() { + function ThrottleOperator(durationSelector) { + this.durationSelector = durationSelector; + } + ThrottleOperator.prototype.call = function(subscriber) { + return new ThrottleSubscriber(subscriber, this.durationSelector); + }; + return ThrottleOperator; + })(); + var ThrottleSubscriber = (function(_super) { + __extends(ThrottleSubscriber, _super); + function ThrottleSubscriber(destination, durationSelector) { + _super.call(this, destination); + this.durationSelector = durationSelector; + } + ThrottleSubscriber.prototype._next = function(value) { + if (!this.throttled) { + var destination = this.destination; + var duration = tryCatch_1.tryCatch(this.durationSelector)(value); + if (duration === errorObject_1.errorObject) { + destination.error(errorObject_1.errorObject.e); + return ; + } + if (isPromise_1.isPromise(duration)) { + duration = fromPromise_1.PromiseObservable.create(duration); + } + this.add(this.throttled = duration._subscribe(new ThrottleDurationSelectorSubscriber(this))); + destination.next(value); + } + }; + ThrottleSubscriber.prototype._error = function(err) { + this.clearThrottle(); + _super.prototype._error.call(this, err); + }; + ThrottleSubscriber.prototype._complete = function() { + this.clearThrottle(); + _super.prototype._complete.call(this); + }; + ThrottleSubscriber.prototype.clearThrottle = function() { + var throttled = this.throttled; + if (throttled) { + throttled.unsubscribe(); + this.remove(throttled); + this.throttled = null; + } + }; + return ThrottleSubscriber; + })(Subscriber_1.Subscriber); + var ThrottleDurationSelectorSubscriber = (function(_super) { + __extends(ThrottleDurationSelectorSubscriber, _super); + function ThrottleDurationSelectorSubscriber(parent) { + _super.call(this, null); + this.parent = parent; + } + ThrottleDurationSelectorSubscriber.prototype._next = function(unused) { + this.parent.clearThrottle(); + }; + ThrottleDurationSelectorSubscriber.prototype._error = function(err) { + this.parent.error(err); + }; + ThrottleDurationSelectorSubscriber.prototype._complete = function() { + this.parent.clearThrottle(); + }; + return ThrottleDurationSelectorSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/throttleTime", ["rxjs/Subscriber", "rxjs/scheduler/asap"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var asap_1 = require("rxjs/scheduler/asap"); + function throttleTime(delay, scheduler) { + if (scheduler === void 0) { + scheduler = asap_1.asap; + } + return this.lift(new ThrottleTimeOperator(delay, scheduler)); + } + exports.throttleTime = throttleTime; + var ThrottleTimeOperator = (function() { + function ThrottleTimeOperator(delay, scheduler) { + this.delay = delay; + this.scheduler = scheduler; + } + ThrottleTimeOperator.prototype.call = function(subscriber) { + return new ThrottleTimeSubscriber(subscriber, this.delay, this.scheduler); + }; + return ThrottleTimeOperator; + })(); + var ThrottleTimeSubscriber = (function(_super) { + __extends(ThrottleTimeSubscriber, _super); + function ThrottleTimeSubscriber(destination, delay, scheduler) { + _super.call(this, destination); + this.delay = delay; + this.scheduler = scheduler; + } + ThrottleTimeSubscriber.prototype._next = function(value) { + if (!this.throttled) { + this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.delay, {subscriber: this})); + this.destination.next(value); + } + }; + ThrottleTimeSubscriber.prototype.clearThrottle = function() { + var throttled = this.throttled; + if (throttled) { + throttled.unsubscribe(); + this.remove(throttled); + this.throttled = null; + } + }; + return ThrottleTimeSubscriber; + })(Subscriber_1.Subscriber); + function dispatchNext(_a) { + var subscriber = _a.subscriber; + subscriber.clearThrottle(); + } + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/timeout", ["rxjs/Subscriber", "rxjs/scheduler/queue", "rxjs/util/isDate"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var queue_1 = require("rxjs/scheduler/queue"); + var isDate_1 = require("rxjs/util/isDate"); + function timeout(due, errorToSend, scheduler) { + if (errorToSend === void 0) { + errorToSend = null; + } + if (scheduler === void 0) { + scheduler = queue_1.queue; + } + var absoluteTimeout = isDate_1.isDate(due); + var waitFor = absoluteTimeout ? (+due - scheduler.now()) : due; + return this.lift(new TimeoutOperator(waitFor, absoluteTimeout, errorToSend, scheduler)); + } + exports.timeout = timeout; + var TimeoutOperator = (function() { + function TimeoutOperator(waitFor, absoluteTimeout, errorToSend, scheduler) { + this.waitFor = waitFor; + this.absoluteTimeout = absoluteTimeout; + this.errorToSend = errorToSend; + this.scheduler = scheduler; + } + TimeoutOperator.prototype.call = function(subscriber) { + return new TimeoutSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.errorToSend, this.scheduler); + }; + return TimeoutOperator; + })(); + var TimeoutSubscriber = (function(_super) { + __extends(TimeoutSubscriber, _super); + function TimeoutSubscriber(destination, absoluteTimeout, waitFor, errorToSend, scheduler) { + _super.call(this, destination); + this.absoluteTimeout = absoluteTimeout; + this.waitFor = waitFor; + this.errorToSend = errorToSend; + this.scheduler = scheduler; + this.index = 0; + this._previousIndex = 0; + this._hasCompleted = false; + this.scheduleTimeout(); + } + Object.defineProperty(TimeoutSubscriber.prototype, "previousIndex", { + get: function() { + return this._previousIndex; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(TimeoutSubscriber.prototype, "hasCompleted", { + get: function() { + return this._hasCompleted; + }, + enumerable: true, + configurable: true + }); + TimeoutSubscriber.dispatchTimeout = function(state) { + var source = state.subscriber; + var currentIndex = state.index; + if (!source.hasCompleted && source.previousIndex === currentIndex) { + source.notifyTimeout(); + } + }; + TimeoutSubscriber.prototype.scheduleTimeout = function() { + var currentIndex = this.index; + this.scheduler.schedule(TimeoutSubscriber.dispatchTimeout, this.waitFor, { + subscriber: this, + index: currentIndex + }); + this.index++; + this._previousIndex = currentIndex; + }; + TimeoutSubscriber.prototype._next = function(value) { + this.destination.next(value); + if (!this.absoluteTimeout) { + this.scheduleTimeout(); + } + }; + TimeoutSubscriber.prototype._error = function(err) { + this.destination.error(err); + this._hasCompleted = true; + }; + TimeoutSubscriber.prototype._complete = function() { + this.destination.complete(); + this._hasCompleted = true; + }; + TimeoutSubscriber.prototype.notifyTimeout = function() { + this.error(this.errorToSend || new Error('timeout')); + }; + return TimeoutSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/timeoutWith", ["rxjs/scheduler/queue", "rxjs/util/isDate", "rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var queue_1 = require("rxjs/scheduler/queue"); + var isDate_1 = require("rxjs/util/isDate"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); + function timeoutWith(due, withObservable, scheduler) { + if (scheduler === void 0) { + scheduler = queue_1.queue; + } + var absoluteTimeout = isDate_1.isDate(due); + var waitFor = absoluteTimeout ? (+due - scheduler.now()) : due; + return this.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler)); + } + exports.timeoutWith = timeoutWith; + var TimeoutWithOperator = (function() { + function TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler) { + this.waitFor = waitFor; + this.absoluteTimeout = absoluteTimeout; + this.withObservable = withObservable; + this.scheduler = scheduler; + } + TimeoutWithOperator.prototype.call = function(subscriber) { + return new TimeoutWithSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler); + }; + return TimeoutWithOperator; + })(); + var TimeoutWithSubscriber = (function(_super) { + __extends(TimeoutWithSubscriber, _super); + function TimeoutWithSubscriber(destination, absoluteTimeout, waitFor, withObservable, scheduler) { + _super.call(this, null); + this.destination = destination; + this.absoluteTimeout = absoluteTimeout; + this.waitFor = waitFor; + this.withObservable = withObservable; + this.scheduler = scheduler; + this.timeoutSubscription = undefined; + this.index = 0; + this._previousIndex = 0; + this._hasCompleted = false; + destination.add(this); + this.scheduleTimeout(); + } + Object.defineProperty(TimeoutWithSubscriber.prototype, "previousIndex", { + get: function() { + return this._previousIndex; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(TimeoutWithSubscriber.prototype, "hasCompleted", { + get: function() { + return this._hasCompleted; + }, + enumerable: true, + configurable: true + }); + TimeoutWithSubscriber.dispatchTimeout = function(state) { + var source = state.subscriber; + var currentIndex = state.index; + if (!source.hasCompleted && source.previousIndex === currentIndex) { + source.handleTimeout(); + } + }; + TimeoutWithSubscriber.prototype.scheduleTimeout = function() { + var currentIndex = this.index; + var timeoutState = { + subscriber: this, + index: currentIndex + }; + this.scheduler.schedule(TimeoutWithSubscriber.dispatchTimeout, this.waitFor, timeoutState); + this.index++; + this._previousIndex = currentIndex; + }; + TimeoutWithSubscriber.prototype._next = function(value) { + this.destination.next(value); + if (!this.absoluteTimeout) { + this.scheduleTimeout(); + } + }; + TimeoutWithSubscriber.prototype._error = function(err) { + this.destination.error(err); + this._hasCompleted = true; + }; + TimeoutWithSubscriber.prototype._complete = function() { + this.destination.complete(); + this._hasCompleted = true; + }; + TimeoutWithSubscriber.prototype.handleTimeout = function() { + if (!this.isUnsubscribed) { + var withObservable = this.withObservable; + this.unsubscribe(); + this.destination.add(this.timeoutSubscription = subscribeToResult_1.subscribeToResult(this, withObservable)); + } + }; + return TimeoutWithSubscriber; + })(OuterSubscriber_1.OuterSubscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/toArray", ["rxjs/Subscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + function toArray() { + return this.lift(new ToArrayOperator()); + } + exports.toArray = toArray; + var ToArrayOperator = (function() { + function ToArrayOperator() {} + ToArrayOperator.prototype.call = function(subscriber) { + return new ToArraySubscriber(subscriber); + }; + return ToArrayOperator; + })(); + var ToArraySubscriber = (function(_super) { + __extends(ToArraySubscriber, _super); + function ToArraySubscriber(destination) { + _super.call(this, destination); + this.array = []; + } + ToArraySubscriber.prototype._next = function(x) { + this.array.push(x); + }; + ToArraySubscriber.prototype._complete = function() { + this.destination.next(this.array); + this.destination.complete(); + }; + return ToArraySubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/toPromise", ["rxjs/util/root"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var root_1 = require("rxjs/util/root"); + function toPromise(PromiseCtor) { + var _this = this; + if (!PromiseCtor) { + if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) { + PromiseCtor = root_1.root.Rx.config.Promise; + } else if (root_1.root.Promise) { + PromiseCtor = root_1.root.Promise; + } + } + if (!PromiseCtor) { + throw new Error('no Promise impl found'); + } + return new PromiseCtor(function(resolve, reject) { + var value; + _this.subscribe(function(x) { + return value = x; + }, function(err) { + return reject(err); + }, function() { + return resolve(value); + }); + }); + } + exports.toPromise = toPromise; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/window", ["rxjs/Subscriber", "rxjs/Subject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var Subject_1 = require("rxjs/Subject"); + function window(closingNotifier) { + return this.lift(new WindowOperator(closingNotifier)); + } + exports.window = window; + var WindowOperator = (function() { + function WindowOperator(closingNotifier) { + this.closingNotifier = closingNotifier; + } + WindowOperator.prototype.call = function(subscriber) { + return new WindowSubscriber(subscriber, this.closingNotifier); + }; + return WindowOperator; + })(); + var WindowSubscriber = (function(_super) { + __extends(WindowSubscriber, _super); + function WindowSubscriber(destination, closingNotifier) { + _super.call(this, destination); + this.destination = destination; + this.closingNotifier = closingNotifier; + this.add(closingNotifier._subscribe(new WindowClosingNotifierSubscriber(this))); + this.openWindow(); + } + WindowSubscriber.prototype._next = function(value) { + this.window.next(value); + }; + WindowSubscriber.prototype._error = function(err) { + this.window.error(err); + this.destination.error(err); + }; + WindowSubscriber.prototype._complete = function() { + this.window.complete(); + this.destination.complete(); + }; + WindowSubscriber.prototype.openWindow = function() { + var prevWindow = this.window; + if (prevWindow) { + prevWindow.complete(); + } + var destination = this.destination; + var newWindow = this.window = new Subject_1.Subject(); + destination.add(newWindow); + destination.next(newWindow); + }; + return WindowSubscriber; + })(Subscriber_1.Subscriber); + var WindowClosingNotifierSubscriber = (function(_super) { + __extends(WindowClosingNotifierSubscriber, _super); + function WindowClosingNotifierSubscriber(parent) { + _super.call(this, null); + this.parent = parent; + } + WindowClosingNotifierSubscriber.prototype._next = function() { + this.parent.openWindow(); + }; + WindowClosingNotifierSubscriber.prototype._error = function(err) { + this.parent._error(err); + }; + WindowClosingNotifierSubscriber.prototype._complete = function() { + this.parent._complete(); + }; + return WindowClosingNotifierSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/windowCount", ["rxjs/Subscriber", "rxjs/Subject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var Subject_1 = require("rxjs/Subject"); + function windowCount(windowSize, startWindowEvery) { + if (startWindowEvery === void 0) { + startWindowEvery = 0; + } + return this.lift(new WindowCountOperator(windowSize, startWindowEvery)); + } + exports.windowCount = windowCount; + var WindowCountOperator = (function() { + function WindowCountOperator(windowSize, startWindowEvery) { + this.windowSize = windowSize; + this.startWindowEvery = startWindowEvery; + } + WindowCountOperator.prototype.call = function(subscriber) { + return new WindowCountSubscriber(subscriber, this.windowSize, this.startWindowEvery); + }; + return WindowCountOperator; + })(); + var WindowCountSubscriber = (function(_super) { + __extends(WindowCountSubscriber, _super); + function WindowCountSubscriber(destination, windowSize, startWindowEvery) { + _super.call(this, destination); + this.destination = destination; + this.windowSize = windowSize; + this.startWindowEvery = startWindowEvery; + this.windows = [new Subject_1.Subject()]; + this.count = 0; + var firstWindow = this.windows[0]; + destination.add(firstWindow); + destination.next(firstWindow); + } + WindowCountSubscriber.prototype._next = function(value) { + var startWindowEvery = (this.startWindowEvery > 0) ? this.startWindowEvery : this.windowSize; + var destination = this.destination; + var windowSize = this.windowSize; + var windows = this.windows; + var len = windows.length; + for (var i = 0; i < len; i++) { + windows[i].next(value); + } + var c = this.count - windowSize + 1; + if (c >= 0 && c % startWindowEvery === 0) { + windows.shift().complete(); + } + if (++this.count % startWindowEvery === 0) { + var window_1 = new Subject_1.Subject(); + windows.push(window_1); + destination.add(window_1); + destination.next(window_1); + } + }; + WindowCountSubscriber.prototype._error = function(err) { + var windows = this.windows; + while (windows.length > 0) { + windows.shift().error(err); + } + this.destination.error(err); + }; + WindowCountSubscriber.prototype._complete = function() { + var windows = this.windows; + while (windows.length > 0) { + windows.shift().complete(); + } + this.destination.complete(); + }; + return WindowCountSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/windowTime", ["rxjs/Subscriber", "rxjs/Subject", "rxjs/scheduler/asap"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var Subject_1 = require("rxjs/Subject"); + var asap_1 = require("rxjs/scheduler/asap"); + function windowTime(windowTimeSpan, windowCreationInterval, scheduler) { + if (windowCreationInterval === void 0) { + windowCreationInterval = null; + } + if (scheduler === void 0) { + scheduler = asap_1.asap; + } + return this.lift(new WindowTimeOperator(windowTimeSpan, windowCreationInterval, scheduler)); + } + exports.windowTime = windowTime; + var WindowTimeOperator = (function() { + function WindowTimeOperator(windowTimeSpan, windowCreationInterval, scheduler) { + this.windowTimeSpan = windowTimeSpan; + this.windowCreationInterval = windowCreationInterval; + this.scheduler = scheduler; + } + WindowTimeOperator.prototype.call = function(subscriber) { + return new WindowTimeSubscriber(subscriber, this.windowTimeSpan, this.windowCreationInterval, this.scheduler); + }; + return WindowTimeOperator; + })(); + var WindowTimeSubscriber = (function(_super) { + __extends(WindowTimeSubscriber, _super); + function WindowTimeSubscriber(destination, windowTimeSpan, windowCreationInterval, scheduler) { + _super.call(this, destination); + this.destination = destination; + this.windowTimeSpan = windowTimeSpan; + this.windowCreationInterval = windowCreationInterval; + this.scheduler = scheduler; + this.windows = []; + if (windowCreationInterval !== null && windowCreationInterval >= 0) { + var window_1 = this.openWindow(); + var closeState = { + subscriber: this, + window: window_1, + context: null + }; + var creationState = { + windowTimeSpan: windowTimeSpan, + windowCreationInterval: windowCreationInterval, + subscriber: this, + scheduler: scheduler + }; + this.add(scheduler.schedule(dispatchWindowClose, windowTimeSpan, closeState)); + this.add(scheduler.schedule(dispatchWindowCreation, windowCreationInterval, creationState)); + } else { + var window_2 = this.openWindow(); + var timeSpanOnlyState = { + subscriber: this, + window: window_2, + windowTimeSpan: windowTimeSpan + }; + this.add(scheduler.schedule(dispatchWindowTimeSpanOnly, windowTimeSpan, timeSpanOnlyState)); + } + } + WindowTimeSubscriber.prototype._next = function(value) { + var windows = this.windows; + var len = windows.length; + for (var i = 0; i < len; i++) { + windows[i].next(value); + } + }; + WindowTimeSubscriber.prototype._error = function(err) { + var windows = this.windows; + while (windows.length > 0) { + windows.shift().error(err); + } + this.destination.error(err); + }; + WindowTimeSubscriber.prototype._complete = function() { + var windows = this.windows; + while (windows.length > 0) { + windows.shift().complete(); + } + this.destination.complete(); + }; + WindowTimeSubscriber.prototype.openWindow = function() { + var window = new Subject_1.Subject(); + this.windows.push(window); + var destination = this.destination; + destination.add(window); + destination.next(window); + return window; + }; + WindowTimeSubscriber.prototype.closeWindow = function(window) { + window.complete(); + var windows = this.windows; + windows.splice(windows.indexOf(window), 1); + }; + return WindowTimeSubscriber; + })(Subscriber_1.Subscriber); + function dispatchWindowTimeSpanOnly(state) { + var subscriber = state.subscriber, + windowTimeSpan = state.windowTimeSpan, + window = state.window; + if (window) { + window.complete(); + } + state.window = subscriber.openWindow(); + this.schedule(state, windowTimeSpan); + } + function dispatchWindowCreation(state) { + var windowTimeSpan = state.windowTimeSpan, + subscriber = state.subscriber, + scheduler = state.scheduler, + windowCreationInterval = state.windowCreationInterval; + var window = subscriber.openWindow(); + var action = this; + var context = { + action: action, + subscription: null + }; + var timeSpanState = { + subscriber: subscriber, + window: window, + context: context + }; + context.subscription = scheduler.schedule(dispatchWindowClose, windowTimeSpan, timeSpanState); + action.add(context.subscription); + action.schedule(state, windowCreationInterval); + } + function dispatchWindowClose(_a) { + var subscriber = _a.subscriber, + window = _a.window, + context = _a.context; + if (context && context.action && context.subscription) { + context.action.remove(context.subscription); + } + subscriber.closeWindow(window); + } + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/windowToggle", ["rxjs/Subscriber", "rxjs/Subject", "rxjs/Subscription", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var Subject_1 = require("rxjs/Subject"); + var Subscription_1 = require("rxjs/Subscription"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + function windowToggle(openings, closingSelector) { + return this.lift(new WindowToggleOperator(openings, closingSelector)); + } + exports.windowToggle = windowToggle; + var WindowToggleOperator = (function() { + function WindowToggleOperator(openings, closingSelector) { + this.openings = openings; + this.closingSelector = closingSelector; + } + WindowToggleOperator.prototype.call = function(subscriber) { + return new WindowToggleSubscriber(subscriber, this.openings, this.closingSelector); + }; + return WindowToggleOperator; + })(); + var WindowToggleSubscriber = (function(_super) { + __extends(WindowToggleSubscriber, _super); + function WindowToggleSubscriber(destination, openings, closingSelector) { + _super.call(this, destination); + this.destination = destination; + this.openings = openings; + this.closingSelector = closingSelector; + this.contexts = []; + this.add(this.openings._subscribe(new WindowToggleOpeningsSubscriber(this))); + } + WindowToggleSubscriber.prototype._next = function(value) { + var contexts = this.contexts; + var len = contexts.length; + for (var i = 0; i < len; i++) { + contexts[i].window.next(value); + } + }; + WindowToggleSubscriber.prototype._error = function(err) { + var contexts = this.contexts; + while (contexts.length > 0) { + contexts.shift().window.error(err); + } + this.destination.error(err); + }; + WindowToggleSubscriber.prototype._complete = function() { + var contexts = this.contexts; + while (contexts.length > 0) { + var context = contexts.shift(); + context.window.complete(); + context.subscription.unsubscribe(); + } + this.destination.complete(); + }; + WindowToggleSubscriber.prototype.openWindow = function(value) { + var closingSelector = this.closingSelector; + var closingNotifier = tryCatch_1.tryCatch(closingSelector)(value); + if (closingNotifier === errorObject_1.errorObject) { + this.error(closingNotifier.e); + } else { + var destination = this.destination; + var window_1 = new Subject_1.Subject(); + var subscription = new Subscription_1.Subscription(); + var context = { + window: window_1, + subscription: subscription + }; + this.contexts.push(context); + var subscriber = new WindowClosingNotifierSubscriber(this, context); + var closingSubscription = closingNotifier._subscribe(subscriber); + subscription.add(closingSubscription); + destination.add(subscription); + destination.add(window_1); + destination.next(window_1); + } + }; + WindowToggleSubscriber.prototype.closeWindow = function(context) { + var window = context.window, + subscription = context.subscription; + var contexts = this.contexts; + var destination = this.destination; + contexts.splice(contexts.indexOf(context), 1); + window.complete(); + destination.remove(subscription); + destination.remove(window); + subscription.unsubscribe(); + }; + return WindowToggleSubscriber; + })(Subscriber_1.Subscriber); + var WindowClosingNotifierSubscriber = (function(_super) { + __extends(WindowClosingNotifierSubscriber, _super); + function WindowClosingNotifierSubscriber(parent, windowContext) { + _super.call(this, null); + this.parent = parent; + this.windowContext = windowContext; + } + WindowClosingNotifierSubscriber.prototype._next = function() { + this.parent.closeWindow(this.windowContext); + }; + WindowClosingNotifierSubscriber.prototype._error = function(err) { + this.parent.error(err); + }; + WindowClosingNotifierSubscriber.prototype._complete = function() { + this.parent.closeWindow(this.windowContext); + }; + return WindowClosingNotifierSubscriber; + })(Subscriber_1.Subscriber); + var WindowToggleOpeningsSubscriber = (function(_super) { + __extends(WindowToggleOpeningsSubscriber, _super); + function WindowToggleOpeningsSubscriber(parent) { + _super.call(this); + this.parent = parent; + } + WindowToggleOpeningsSubscriber.prototype._next = function(value) { + this.parent.openWindow(value); + }; + WindowToggleOpeningsSubscriber.prototype._error = function(err) { + this.parent.error(err); + }; + WindowToggleOpeningsSubscriber.prototype._complete = function() {}; + return WindowToggleOpeningsSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/windowWhen", ["rxjs/Subscriber", "rxjs/Subject", "rxjs/Subscription", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var Subject_1 = require("rxjs/Subject"); + var Subscription_1 = require("rxjs/Subscription"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + function windowWhen(closingSelector) { + return this.lift(new WindowOperator(closingSelector)); + } + exports.windowWhen = windowWhen; + var WindowOperator = (function() { + function WindowOperator(closingSelector) { + this.closingSelector = closingSelector; + } + WindowOperator.prototype.call = function(subscriber) { + return new WindowSubscriber(subscriber, this.closingSelector); + }; + return WindowOperator; + })(); + var WindowSubscriber = (function(_super) { + __extends(WindowSubscriber, _super); + function WindowSubscriber(destination, closingSelector) { + _super.call(this, destination); + this.destination = destination; + this.closingSelector = closingSelector; + this.openWindow(); + } + WindowSubscriber.prototype._next = function(value) { + this.window.next(value); + }; + WindowSubscriber.prototype._error = function(err) { + this.window.error(err); + this.destination.error(err); + this._unsubscribeClosingNotification(); + }; + WindowSubscriber.prototype._complete = function() { + this.window.complete(); + this.destination.complete(); + this._unsubscribeClosingNotification(); + }; + WindowSubscriber.prototype.unsubscribe = function() { + _super.prototype.unsubscribe.call(this); + this._unsubscribeClosingNotification(); + }; + WindowSubscriber.prototype._unsubscribeClosingNotification = function() { + var closingNotification = this.closingNotification; + if (closingNotification) { + closingNotification.unsubscribe(); + } + }; + WindowSubscriber.prototype.openWindow = function() { + var prevClosingNotification = this.closingNotification; + if (prevClosingNotification) { + this.remove(prevClosingNotification); + prevClosingNotification.unsubscribe(); + } + var prevWindow = this.window; + if (prevWindow) { + prevWindow.complete(); + } + var window = this.window = new Subject_1.Subject(); + this.destination.next(window); + var closingNotifier = tryCatch_1.tryCatch(this.closingSelector)(); + if (closingNotifier === errorObject_1.errorObject) { + var err = closingNotifier.e; + this.destination.error(err); + this.window.error(err); + } else { + var closingNotification = this.closingNotification = new Subscription_1.Subscription(); + closingNotification.add(closingNotifier._subscribe(new WindowClosingNotifierSubscriber(this))); + this.add(closingNotification); + this.add(window); + } + }; + return WindowSubscriber; + })(Subscriber_1.Subscriber); + var WindowClosingNotifierSubscriber = (function(_super) { + __extends(WindowClosingNotifierSubscriber, _super); + function WindowClosingNotifierSubscriber(parent) { + _super.call(this, null); + this.parent = parent; + } + WindowClosingNotifierSubscriber.prototype._next = function() { + this.parent.openWindow(); + }; + WindowClosingNotifierSubscriber.prototype._error = function(err) { + this.parent.error(err); + }; + WindowClosingNotifierSubscriber.prototype._complete = function() { + this.parent.openWindow(); + }; + return WindowClosingNotifierSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/withLatestFrom", ["rxjs/util/tryCatch", "rxjs/util/errorObject", "rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); + function withLatestFrom() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + var project; + if (typeof args[args.length - 1] === 'function') { + project = args.pop(); + } + var observables = args; + return this.lift(new WithLatestFromOperator(observables, project)); + } + exports.withLatestFrom = withLatestFrom; + var WithLatestFromOperator = (function() { + function WithLatestFromOperator(observables, project) { + this.observables = observables; + this.project = project; + } + WithLatestFromOperator.prototype.call = function(subscriber) { + return new WithLatestFromSubscriber(subscriber, this.observables, this.project); + }; + return WithLatestFromOperator; + })(); + var WithLatestFromSubscriber = (function(_super) { + __extends(WithLatestFromSubscriber, _super); + function WithLatestFromSubscriber(destination, observables, project) { + _super.call(this, destination); + this.observables = observables; + this.project = project; + this.toRespond = []; + var len = observables.length; + this.values = new Array(len); + for (var i = 0; i < len; i++) { + this.toRespond.push(i); + } + for (var i = 0; i < len; i++) { + var observable = observables[i]; + this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i)); + } + } + WithLatestFromSubscriber.prototype.notifyNext = function(observable, value, observableIndex, index) { + this.values[observableIndex] = value; + var toRespond = this.toRespond; + if (toRespond.length > 0) { + var found = toRespond.indexOf(observableIndex); + if (found !== -1) { + toRespond.splice(found, 1); + } + } + }; + WithLatestFromSubscriber.prototype.notifyComplete = function() {}; + WithLatestFromSubscriber.prototype._next = function(value) { + if (this.toRespond.length === 0) { + var values = this.values; + var destination = this.destination; + var project = this.project; + var args = [value].concat(values); + if (project) { + var result = tryCatch_1.tryCatch(this.project).apply(this, args); + if (result === errorObject_1.errorObject) { + destination.error(result.e); + } else { + destination.next(result); + } + } else { + destination.next(args); + } + } + }; + return WithLatestFromSubscriber; + })(OuterSubscriber_1.OuterSubscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/zip", ["rxjs/operator/zip-static"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var zip_static_1 = require("rxjs/operator/zip-static"); + function zipProto() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; + } + observables.unshift(this); + return zip_static_1.zip.apply(this, observables); + } + exports.zipProto = zipProto; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/zipAll", ["rxjs/operator/zip-support"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var zip_support_1 = require("rxjs/operator/zip-support"); + function zipAll(project) { + return this.lift(new zip_support_1.ZipOperator(project)); + } + exports.zipAll = zipAll; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/SymbolShim", ["rxjs/util/root"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var root_1 = require("rxjs/util/root"); + function polyfillSymbol(root) { + var Symbol = ensureSymbol(root); + ensureIterator(Symbol, root); + ensureObservable(Symbol); + ensureFor(Symbol); + return Symbol; + } + exports.polyfillSymbol = polyfillSymbol; + function ensureFor(Symbol) { + if (!Symbol.for) { + Symbol.for = symbolForPolyfill; + } + } + exports.ensureFor = ensureFor; + var id = 0; + function ensureSymbol(root) { + if (!root.Symbol) { + root.Symbol = function symbolFuncPolyfill(description) { + return "@@Symbol(" + description + "):" + id++; + }; + } + return root.Symbol; + } + exports.ensureSymbol = ensureSymbol; + function symbolForPolyfill(key) { + return '@@' + key; + } + exports.symbolForPolyfill = symbolForPolyfill; + function ensureIterator(Symbol, root) { + if (!Symbol.iterator) { + if (typeof Symbol.for === 'function') { + Symbol.iterator = Symbol.for('iterator'); + } else if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { + Symbol.iterator = '@@iterator'; + } else if (root.Map) { + var keys = Object.getOwnPropertyNames(root.Map.prototype); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (key !== 'entries' && key !== 'size' && root.Map.prototype[key] === root.Map.prototype['entries']) { + Symbol.iterator = key; + break; + } + } + } else { + Symbol.iterator = '@@iterator'; + } + } + } + exports.ensureIterator = ensureIterator; + function ensureObservable(Symbol) { + if (!Symbol.observable) { + if (typeof Symbol.for === 'function') { + Symbol.observable = Symbol.for('observable'); + } else { + Symbol.observable = '@@observable'; + } + } + } + exports.ensureObservable = ensureObservable; + exports.SymbolShim = polyfillSymbol(root_1.root); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/tryCatch", ["rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var errorObject_1 = require("rxjs/util/errorObject"); + var tryCatchTarget; + function tryCatcher() { + try { + return tryCatchTarget.apply(this, arguments); + } catch (e) { + errorObject_1.errorObject.e = e; + return errorObject_1.errorObject; + } + } + function tryCatch(fn) { + tryCatchTarget = fn; + return tryCatcher; + } + exports.tryCatch = tryCatch; + ; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/subscribeToResult", ["rxjs/Observable", "rxjs/util/SymbolShim", "rxjs/InnerSubscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var SymbolShim_1 = require("rxjs/util/SymbolShim"); + var InnerSubscriber_1 = require("rxjs/InnerSubscriber"); + var isArray = Array.isArray; + function subscribeToResult(outerSubscriber, result, outerValue, outerIndex) { + var destination = new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex); + if (destination.isUnsubscribed) { + return ; + } + if (result instanceof Observable_1.Observable) { + if (result._isScalar) { + destination.next(result.value); + destination.complete(); + return ; + } else { + return result.subscribe(destination); + } + } + if (isArray(result)) { + for (var i = 0, + len = result.length; i < len && !destination.isUnsubscribed; i++) { + destination.next(result[i]); + } + if (!destination.isUnsubscribed) { + destination.complete(); + } + } else if (typeof result.then === 'function') { + result.then(function(x) { + if (!destination.isUnsubscribed) { + destination.next(x); + destination.complete(); + } + }, function(err) { + return destination.error(err); + }).then(null, function(err) { + setTimeout(function() { + throw err; + }); + }); + return destination; + } else if (typeof result[SymbolShim_1.SymbolShim.iterator] === 'function') { + for (var _i = 0, + result_1 = result; _i < result_1.length; _i++) { + var item = result_1[_i]; + destination.next(item); + if (destination.isUnsubscribed) { + break; + } + } + if (!destination.isUnsubscribed) { + destination.complete(); + } + } else if (typeof result[SymbolShim_1.SymbolShim.observable] === 'function') { + var obs = result[SymbolShim_1.SymbolShim.observable](); + if (typeof obs.subscribe !== 'function') { + destination.error('invalid observable'); + } else { + return obs.subscribe(new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex)); + } + } else { + destination.error(new TypeError('unknown type returned')); + } + } + exports.subscribeToResult = subscribeToResult; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/scheduler/QueueScheduler", ["rxjs/scheduler/QueueAction", "rxjs/scheduler/FutureAction"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var QueueAction_1 = require("rxjs/scheduler/QueueAction"); + var FutureAction_1 = require("rxjs/scheduler/FutureAction"); + var QueueScheduler = (function() { + function QueueScheduler() { + this.actions = []; + this.active = false; + this.scheduled = false; + } + QueueScheduler.prototype.now = function() { + return Date.now(); + }; + QueueScheduler.prototype.flush = function() { + if (this.active || this.scheduled) { + return ; + } + this.active = true; + var actions = this.actions; + for (var action = void 0; action = actions.shift(); ) { + action.execute(); + } + this.active = false; + }; + QueueScheduler.prototype.schedule = function(work, delay, state) { + if (delay === void 0) { + delay = 0; + } + return (delay <= 0) ? this.scheduleNow(work, state) : this.scheduleLater(work, delay, state); + }; + QueueScheduler.prototype.scheduleNow = function(work, state) { + return new QueueAction_1.QueueAction(this, work).schedule(state); + }; + QueueScheduler.prototype.scheduleLater = function(work, delay, state) { + return new FutureAction_1.FutureAction(this, work).schedule(state, delay); + }; + return QueueScheduler; + })(); + exports.QueueScheduler = QueueScheduler; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/merge-static", ["rxjs/Observable", "rxjs/operator/merge-static"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var merge_static_1 = require("rxjs/operator/merge-static"); + Observable_1.Observable.merge = merge_static_1.merge; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/bindCallback", ["rxjs/Observable", "rxjs/util/tryCatch", "rxjs/util/errorObject", "rxjs/subject/AsyncSubject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Observable_1 = require("rxjs/Observable"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + var AsyncSubject_1 = require("rxjs/subject/AsyncSubject"); + var BoundCallbackObservable = (function(_super) { + __extends(BoundCallbackObservable, _super); + function BoundCallbackObservable(callbackFunc, selector, args, scheduler) { + _super.call(this); + this.callbackFunc = callbackFunc; + this.selector = selector; + this.args = args; + this.scheduler = scheduler; + } + BoundCallbackObservable.create = function(callbackFunc, selector, scheduler) { + if (selector === void 0) { + selector = undefined; + } + return function() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + return new BoundCallbackObservable(callbackFunc, selector, args, scheduler); + }; + }; + BoundCallbackObservable.prototype._subscribe = function(subscriber) { + var callbackFunc = this.callbackFunc; + var args = this.args; + var scheduler = this.scheduler; + var subject = this.subject; + if (!scheduler) { + if (!subject) { + subject = this.subject = new AsyncSubject_1.AsyncSubject(); + var handler = function handlerFn() { + var innerArgs = []; + for (var _i = 0; _i < arguments.length; _i++) { + innerArgs[_i - 0] = arguments[_i]; + } + var source = handlerFn.source; + var selector = source.selector, + subject = source.subject; + if (selector) { + var result_1 = tryCatch_1.tryCatch(selector).apply(this, innerArgs); + if (result_1 === errorObject_1.errorObject) { + subject.error(errorObject_1.errorObject.e); + } else { + subject.next(result_1); + subject.complete(); + } + } else { + subject.next(innerArgs.length === 1 ? innerArgs[0] : innerArgs); + subject.complete(); + } + }; + handler.source = this; + var result = tryCatch_1.tryCatch(callbackFunc).apply(this, args.concat(handler)); + if (result === errorObject_1.errorObject) { + subject.error(errorObject_1.errorObject.e); + } + } + return subject.subscribe(subscriber); + } else { + subscriber.add(scheduler.schedule(dispatch, 0, { + source: this, + subscriber: subscriber + })); + return subscriber; + } + }; + return BoundCallbackObservable; + })(Observable_1.Observable); + exports.BoundCallbackObservable = BoundCallbackObservable; + function dispatch(state) { + var source = state.source, + subscriber = state.subscriber; + var callbackFunc = source.callbackFunc, + args = source.args, + scheduler = source.scheduler; + var subject = source.subject; + if (!subject) { + subject = source.subject = new AsyncSubject_1.AsyncSubject(); + var handler = function handlerFn() { + var innerArgs = []; + for (var _i = 0; _i < arguments.length; _i++) { + innerArgs[_i - 0] = arguments[_i]; + } + var source = handlerFn.source; + var selector = source.selector, + subject = source.subject; + if (selector) { + var result_2 = tryCatch_1.tryCatch(selector).apply(this, innerArgs); + if (result_2 === errorObject_1.errorObject) { + subject.add(scheduler.schedule(dispatchError, 0, { + err: errorObject_1.errorObject.e, + subject: subject + })); + } else { + subject.add(scheduler.schedule(dispatchNext, 0, { + value: result_2, + subject: subject + })); + } + } else { + var value = innerArgs.length === 1 ? innerArgs[0] : innerArgs; + subject.add(scheduler.schedule(dispatchNext, 0, { + value: value, + subject: subject + })); + } + }; + handler.source = source; + var result = tryCatch_1.tryCatch(callbackFunc).apply(this, args.concat(handler)); + if (result === errorObject_1.errorObject) { + subject.error(errorObject_1.errorObject.e); + } + } + this.add(subject.subscribe(subscriber)); + } + function dispatchNext(_a) { + var value = _a.value, + subject = _a.subject; + subject.next(value); + subject.complete(); + } + function dispatchError(_a) { + var err = _a.err, + subject = _a.subject; + subject.error(err); + } + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/observable/defer", ["rxjs/Observable", "rxjs/observable/defer"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var defer_1 = require("rxjs/observable/defer"); + Observable_1.Observable.defer = defer_1.DeferObservable.create; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/forkJoin", ["rxjs/Observable", "rxjs/Subscriber", "rxjs/observable/fromPromise", "rxjs/observable/empty", "rxjs/util/isPromise", "rxjs/util/isArray"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Observable_1 = require("rxjs/Observable"); + var Subscriber_1 = require("rxjs/Subscriber"); + var fromPromise_1 = require("rxjs/observable/fromPromise"); + var empty_1 = require("rxjs/observable/empty"); + var isPromise_1 = require("rxjs/util/isPromise"); + var isArray_1 = require("rxjs/util/isArray"); + var ForkJoinObservable = (function(_super) { + __extends(ForkJoinObservable, _super); + function ForkJoinObservable(sources, resultSelector) { + _super.call(this); + this.sources = sources; + this.resultSelector = resultSelector; + } + ForkJoinObservable.create = function() { + var sources = []; + for (var _i = 0; _i < arguments.length; _i++) { + sources[_i - 0] = arguments[_i]; + } + if (sources === null || arguments.length === 0) { + return new empty_1.EmptyObservable(); + } + var resultSelector = null; + if (typeof sources[sources.length - 1] === 'function') { + resultSelector = sources.pop(); + } + if (sources.length === 1 && isArray_1.isArray(sources[0])) { + sources = sources[0]; + } + return new ForkJoinObservable(sources, resultSelector); + }; + ForkJoinObservable.prototype._subscribe = function(subscriber) { + var sources = this.sources; + var len = sources.length; + var context = { + completed: 0, + total: len, + values: emptyArray(len), + selector: this.resultSelector + }; + for (var i = 0; i < len; i++) { + var source = sources[i]; + if (isPromise_1.isPromise(source)) { + source = new fromPromise_1.PromiseObservable(source); + } + source.subscribe(new AllSubscriber(subscriber, i, context)); + } + }; + return ForkJoinObservable; + })(Observable_1.Observable); + exports.ForkJoinObservable = ForkJoinObservable; + var AllSubscriber = (function(_super) { + __extends(AllSubscriber, _super); + function AllSubscriber(destination, index, context) { + _super.call(this, destination); + this.index = index; + this.context = context; + this._value = null; + } + AllSubscriber.prototype._next = function(value) { + this._value = value; + }; + AllSubscriber.prototype._complete = function() { + var destination = this.destination; + if (this._value == null) { + destination.complete(); + } + var context = this.context; + context.completed++; + context.values[this.index] = this._value; + var values = context.values; + if (context.completed !== values.length) { + return ; + } + if (values.every(hasValue)) { + var value = context.selector ? context.selector.apply(this, values) : values; + destination.next(value); + } + destination.complete(); + }; + return AllSubscriber; + })(Subscriber_1.Subscriber); + function hasValue(x) { + return x !== null; + } + function emptyArray(len) { + var arr = []; + for (var i = 0; i < len; i++) { + arr.push(null); + } + return arr; + } + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/observeOn-support", ["rxjs/Subscriber", "rxjs/Notification"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var Notification_1 = require("rxjs/Notification"); + var ObserveOnOperator = (function() { + function ObserveOnOperator(scheduler, delay) { + if (delay === void 0) { + delay = 0; + } + this.scheduler = scheduler; + this.delay = delay; + } + ObserveOnOperator.prototype.call = function(subscriber) { + return new ObserveOnSubscriber(subscriber, this.scheduler, this.delay); + }; + return ObserveOnOperator; + })(); + exports.ObserveOnOperator = ObserveOnOperator; + var ObserveOnSubscriber = (function(_super) { + __extends(ObserveOnSubscriber, _super); + function ObserveOnSubscriber(destination, scheduler, delay) { + if (delay === void 0) { + delay = 0; + } + _super.call(this, destination); + this.scheduler = scheduler; + this.delay = delay; + } + ObserveOnSubscriber.dispatch = function(_a) { + var notification = _a.notification, + destination = _a.destination; + notification.observe(destination); + }; + ObserveOnSubscriber.prototype.scheduleMessage = function(notification) { + this.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination))); + }; + ObserveOnSubscriber.prototype._next = function(value) { + this.scheduleMessage(Notification_1.Notification.createNext(value)); + }; + ObserveOnSubscriber.prototype._error = function(err) { + this.scheduleMessage(Notification_1.Notification.createError(err)); + }; + ObserveOnSubscriber.prototype._complete = function() { + this.scheduleMessage(Notification_1.Notification.createComplete()); + }; + return ObserveOnSubscriber; + })(Subscriber_1.Subscriber); + exports.ObserveOnSubscriber = ObserveOnSubscriber; + var ObserveOnMessage = (function() { + function ObserveOnMessage(notification, destination) { + this.notification = notification; + this.destination = destination; + } + return ObserveOnMessage; + })(); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/observable/fromEvent", ["rxjs/Observable", "rxjs/observable/fromEvent"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var fromEvent_1 = require("rxjs/observable/fromEvent"); + Observable_1.Observable.fromEvent = fromEvent_1.FromEventObservable.create; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/observable/fromEventPattern", ["rxjs/Observable", "rxjs/observable/fromEventPattern"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var fromEventPattern_1 = require("rxjs/observable/fromEventPattern"); + Observable_1.Observable.fromEventPattern = fromEventPattern_1.FromEventPatternObservable.create; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/scheduler/AsapAction", ["rxjs/util/Immediate", "rxjs/scheduler/QueueAction"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Immediate_1 = require("rxjs/util/Immediate"); + var QueueAction_1 = require("rxjs/scheduler/QueueAction"); + var AsapAction = (function(_super) { + __extends(AsapAction, _super); + function AsapAction() { + _super.apply(this, arguments); + } + AsapAction.prototype.schedule = function(state) { + var _this = this; + if (this.isUnsubscribed) { + return this; + } + this.state = state; + var scheduler = this.scheduler; + scheduler.actions.push(this); + if (!scheduler.scheduled) { + scheduler.scheduled = true; + this.id = Immediate_1.Immediate.setImmediate(function() { + _this.id = null; + _this.scheduler.scheduled = false; + _this.scheduler.flush(); + }); + } + return this; + }; + AsapAction.prototype.unsubscribe = function() { + var id = this.id; + var scheduler = this.scheduler; + _super.prototype.unsubscribe.call(this); + if (scheduler.actions.length === 0) { + scheduler.active = false; + scheduler.scheduled = false; + } + if (id) { + this.id = null; + Immediate_1.Immediate.clearImmediate(id); + } + }; + return AsapAction; + })(QueueAction_1.QueueAction); + exports.AsapAction = AsapAction; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/observable/never", ["rxjs/Observable", "rxjs/observable/never"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var never_1 = require("rxjs/observable/never"); + Observable_1.Observable.never = never_1.InfiniteObservable.create; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/observable/range", ["rxjs/Observable", "rxjs/observable/range"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var range_1 = require("rxjs/observable/range"); + Observable_1.Observable.range = range_1.RangeObservable.create; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/timer", ["rxjs/util/isNumeric", "rxjs/Observable", "rxjs/scheduler/asap", "rxjs/util/isScheduler", "rxjs/util/isDate"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var isNumeric_1 = require("rxjs/util/isNumeric"); + var Observable_1 = require("rxjs/Observable"); + var asap_1 = require("rxjs/scheduler/asap"); + var isScheduler_1 = require("rxjs/util/isScheduler"); + var isDate_1 = require("rxjs/util/isDate"); + var TimerObservable = (function(_super) { + __extends(TimerObservable, _super); + function TimerObservable(dueTime, period, scheduler) { + if (dueTime === void 0) { + dueTime = 0; + } + _super.call(this); + this.period = period; + this.scheduler = scheduler; + this.dueTime = 0; + if (isNumeric_1.isNumeric(period)) { + this._period = Number(period) < 1 && 1 || Number(period); + } else if (isScheduler_1.isScheduler(period)) { + scheduler = period; + } + if (!isScheduler_1.isScheduler(scheduler)) { + scheduler = asap_1.asap; + } + this.scheduler = scheduler; + var absoluteDueTime = isDate_1.isDate(dueTime); + this.dueTime = absoluteDueTime ? (+dueTime - this.scheduler.now()) : dueTime; + } + TimerObservable.create = function(dueTime, period, scheduler) { + if (dueTime === void 0) { + dueTime = 0; + } + return new TimerObservable(dueTime, period, scheduler); + }; + TimerObservable.dispatch = function(state) { + var index = state.index, + period = state.period, + subscriber = state.subscriber; + var action = this; + subscriber.next(index); + if (typeof period === 'undefined') { + subscriber.complete(); + return ; + } else if (subscriber.isUnsubscribed) { + return ; + } + if (typeof action.delay === 'undefined') { + action.add(action.scheduler.schedule(TimerObservable.dispatch, period, { + index: index + 1, + period: period, + subscriber: subscriber + })); + } else { + state.index = index + 1; + action.schedule(state, period); + } + }; + TimerObservable.prototype._subscribe = function(subscriber) { + var index = 0; + var period = this._period; + var dueTime = this.dueTime; + var scheduler = this.scheduler; + subscriber.add(scheduler.schedule(TimerObservable.dispatch, dueTime, { + index: index, + period: period, + subscriber: subscriber + })); + }; + return TimerObservable; + })(Observable_1.Observable); + exports.TimerObservable = TimerObservable; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/zip-static", ["rxjs/observable/fromArray", "rxjs/operator/zip-support"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var fromArray_1 = require("rxjs/observable/fromArray"); + var zip_support_1 = require("rxjs/operator/zip-support"); + function zip() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; + } + var project = observables[observables.length - 1]; + if (typeof project === 'function') { + observables.pop(); + } + return new fromArray_1.ArrayObservable(observables).lift(new zip_support_1.ZipOperator(project)); + } + exports.zip = zip; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/buffer", ["rxjs/Observable", "rxjs/operator/buffer"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var buffer_1 = require("rxjs/operator/buffer"); + Observable_1.Observable.prototype.buffer = buffer_1.buffer; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/bufferCount", ["rxjs/Observable", "rxjs/operator/bufferCount"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var bufferCount_1 = require("rxjs/operator/bufferCount"); + Observable_1.Observable.prototype.bufferCount = bufferCount_1.bufferCount; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/bufferTime", ["rxjs/Observable", "rxjs/operator/bufferTime"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var bufferTime_1 = require("rxjs/operator/bufferTime"); + Observable_1.Observable.prototype.bufferTime = bufferTime_1.bufferTime; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/bufferToggle", ["rxjs/Observable", "rxjs/operator/bufferToggle"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var bufferToggle_1 = require("rxjs/operator/bufferToggle"); + Observable_1.Observable.prototype.bufferToggle = bufferToggle_1.bufferToggle; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/bufferWhen", ["rxjs/Observable", "rxjs/operator/bufferWhen"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var bufferWhen_1 = require("rxjs/operator/bufferWhen"); + Observable_1.Observable.prototype.bufferWhen = bufferWhen_1.bufferWhen; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/catch", ["rxjs/Observable", "rxjs/operator/catch"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var catch_1 = require("rxjs/operator/catch"); + Observable_1.Observable.prototype.catch = catch_1._catch; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/combineAll", ["rxjs/Observable", "rxjs/operator/combineAll"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var combineAll_1 = require("rxjs/operator/combineAll"); + Observable_1.Observable.prototype.combineAll = combineAll_1.combineAll; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/combineLatest", ["rxjs/Observable", "rxjs/operator/combineLatest"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var combineLatest_1 = require("rxjs/operator/combineLatest"); + Observable_1.Observable.prototype.combineLatest = combineLatest_1.combineLatest; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/concat", ["rxjs/Observable", "rxjs/operator/concat"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var concat_1 = require("rxjs/operator/concat"); + Observable_1.Observable.prototype.concat = concat_1.concat; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/concatAll", ["rxjs/Observable", "rxjs/operator/concatAll"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var concatAll_1 = require("rxjs/operator/concatAll"); + Observable_1.Observable.prototype.concatAll = concatAll_1.concatAll; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/concatMap", ["rxjs/operator/mergeMap-support"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var mergeMap_support_1 = require("rxjs/operator/mergeMap-support"); + function concatMap(project, projectResult) { + return this.lift(new mergeMap_support_1.MergeMapOperator(project, projectResult, 1)); + } + exports.concatMap = concatMap; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/concatMapTo", ["rxjs/operator/mergeMapTo-support"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var mergeMapTo_support_1 = require("rxjs/operator/mergeMapTo-support"); + function concatMapTo(observable, projectResult) { + return this.lift(new mergeMapTo_support_1.MergeMapToOperator(observable, projectResult, 1)); + } + exports.concatMapTo = concatMapTo; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/count", ["rxjs/Observable", "rxjs/operator/count"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var count_1 = require("rxjs/operator/count"); + Observable_1.Observable.prototype.count = count_1.count; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/dematerialize", ["rxjs/Observable", "rxjs/operator/dematerialize"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var dematerialize_1 = require("rxjs/operator/dematerialize"); + Observable_1.Observable.prototype.dematerialize = dematerialize_1.dematerialize; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/debounce", ["rxjs/Observable", "rxjs/operator/debounce"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var debounce_1 = require("rxjs/operator/debounce"); + Observable_1.Observable.prototype.debounce = debounce_1.debounce; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/debounceTime", ["rxjs/Observable", "rxjs/operator/debounceTime"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var debounceTime_1 = require("rxjs/operator/debounceTime"); + Observable_1.Observable.prototype.debounceTime = debounceTime_1.debounceTime; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/defaultIfEmpty", ["rxjs/Observable", "rxjs/operator/defaultIfEmpty"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var defaultIfEmpty_1 = require("rxjs/operator/defaultIfEmpty"); + Observable_1.Observable.prototype.defaultIfEmpty = defaultIfEmpty_1.defaultIfEmpty; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/delay", ["rxjs/Observable", "rxjs/operator/delay"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var delay_1 = require("rxjs/operator/delay"); + Observable_1.Observable.prototype.delay = delay_1.delay; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/distinctUntilChanged", ["rxjs/Observable", "rxjs/operator/distinctUntilChanged"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var distinctUntilChanged_1 = require("rxjs/operator/distinctUntilChanged"); + Observable_1.Observable.prototype.distinctUntilChanged = distinctUntilChanged_1.distinctUntilChanged; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/do", ["rxjs/Observable", "rxjs/operator/do"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var do_1 = require("rxjs/operator/do"); + Observable_1.Observable.prototype.do = do_1._do; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/expand", ["rxjs/operator/expand-support"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var expand_support_1 = require("rxjs/operator/expand-support"); + function expand(project, concurrent, scheduler) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + if (scheduler === void 0) { + scheduler = undefined; + } + concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent; + return this.lift(new expand_support_1.ExpandOperator(project, concurrent, scheduler)); + } + exports.expand = expand; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/filter", ["rxjs/Observable", "rxjs/operator/filter"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var filter_1 = require("rxjs/operator/filter"); + Observable_1.Observable.prototype.filter = filter_1.filter; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/finally", ["rxjs/Observable", "rxjs/operator/finally"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var finally_1 = require("rxjs/operator/finally"); + Observable_1.Observable.prototype.finally = finally_1._finally; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/first", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject", "rxjs/util/EmptyError"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + var EmptyError_1 = require("rxjs/util/EmptyError"); + function first(predicate, resultSelector, defaultValue) { + return this.lift(new FirstOperator(predicate, resultSelector, defaultValue, this)); + } + exports.first = first; + var FirstOperator = (function() { + function FirstOperator(predicate, resultSelector, defaultValue, source) { + this.predicate = predicate; + this.resultSelector = resultSelector; + this.defaultValue = defaultValue; + this.source = source; + } + FirstOperator.prototype.call = function(observer) { + return new FirstSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source); + }; + return FirstOperator; + })(); + var FirstSubscriber = (function(_super) { + __extends(FirstSubscriber, _super); + function FirstSubscriber(destination, predicate, resultSelector, defaultValue, source) { + _super.call(this, destination); + this.predicate = predicate; + this.resultSelector = resultSelector; + this.defaultValue = defaultValue; + this.source = source; + this.index = 0; + this.hasCompleted = false; + } + FirstSubscriber.prototype._next = function(value) { + var _a = this, + destination = _a.destination, + predicate = _a.predicate, + resultSelector = _a.resultSelector; + var index = this.index++; + var passed = true; + if (predicate) { + passed = tryCatch_1.tryCatch(predicate)(value, index, this.source); + if (passed === errorObject_1.errorObject) { + destination.error(errorObject_1.errorObject.e); + return ; + } + } + if (passed) { + if (resultSelector) { + var result = tryCatch_1.tryCatch(resultSelector)(value, index); + if (result === errorObject_1.errorObject) { + destination.error(errorObject_1.errorObject.e); + return ; + } + destination.next(result); + } else { + destination.next(value); + } + destination.complete(); + this.hasCompleted = true; + } + }; + FirstSubscriber.prototype._complete = function() { + var destination = this.destination; + if (!this.hasCompleted && typeof this.defaultValue !== 'undefined') { + destination.next(this.defaultValue); + destination.complete(); + } else if (!this.hasCompleted) { + destination.error(new EmptyError_1.EmptyError); + } + }; + return FirstSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/Map", ["rxjs/util/root", "rxjs/util/MapPolyfill"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var root_1 = require("rxjs/util/root"); + var MapPolyfill_1 = require("rxjs/util/MapPolyfill"); + exports.Map = root_1.root.Map || (function() { + return MapPolyfill_1.MapPolyfill; + })(); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/ignoreElements", ["rxjs/Observable", "rxjs/operator/ignoreElements"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var ignoreElements_1 = require("rxjs/operator/ignoreElements"); + Observable_1.Observable.prototype.ignoreElements = ignoreElements_1.ignoreElements; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/every", ["rxjs/Observable", "rxjs/operator/every"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var every_1 = require("rxjs/operator/every"); + Observable_1.Observable.prototype.every = every_1.every; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/last", ["rxjs/Observable", "rxjs/operator/last"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var last_1 = require("rxjs/operator/last"); + Observable_1.Observable.prototype.last = last_1.last; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/map", ["rxjs/Observable", "rxjs/operator/map"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var map_1 = require("rxjs/operator/map"); + Observable_1.Observable.prototype.map = map_1.map; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/mapTo", ["rxjs/Observable", "rxjs/operator/mapTo"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var mapTo_1 = require("rxjs/operator/mapTo"); + Observable_1.Observable.prototype.mapTo = mapTo_1.mapTo; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/materialize", ["rxjs/Observable", "rxjs/operator/materialize"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var materialize_1 = require("rxjs/operator/materialize"); + Observable_1.Observable.prototype.materialize = materialize_1.materialize; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/merge", ["rxjs/Observable", "rxjs/operator/merge"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var merge_1 = require("rxjs/operator/merge"); + Observable_1.Observable.prototype.merge = merge_1.merge; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/mergeAll", ["rxjs/Observable", "rxjs/operator/mergeAll"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var mergeAll_1 = require("rxjs/operator/mergeAll"); + Observable_1.Observable.prototype.mergeAll = mergeAll_1.mergeAll; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/mergeMap", ["rxjs/Observable", "rxjs/operator/mergeMap"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var mergeMap_1 = require("rxjs/operator/mergeMap"); + Observable_1.Observable.prototype.mergeMap = mergeMap_1.mergeMap; + Observable_1.Observable.prototype.flatMap = mergeMap_1.mergeMap; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/mergeMapTo", ["rxjs/Observable", "rxjs/operator/mergeMapTo"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var mergeMapTo_1 = require("rxjs/operator/mergeMapTo"); + Observable_1.Observable.prototype.mergeMapTo = mergeMapTo_1.mergeMapTo; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/multicast", ["rxjs/observable/ConnectableObservable"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var ConnectableObservable_1 = require("rxjs/observable/ConnectableObservable"); + function multicast(subjectOrSubjectFactory) { + var subjectFactory; + if (typeof subjectOrSubjectFactory === 'function') { + subjectFactory = subjectOrSubjectFactory; + } else { + subjectFactory = function subjectFactory() { + return subjectOrSubjectFactory; + }; + } + return new ConnectableObservable_1.ConnectableObservable(this, subjectFactory); + } + exports.multicast = multicast; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/observeOn", ["rxjs/Observable", "rxjs/operator/observeOn"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var observeOn_1 = require("rxjs/operator/observeOn"); + Observable_1.Observable.prototype.observeOn = observeOn_1.observeOn; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/partition", ["rxjs/util/not", "rxjs/operator/filter"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var not_1 = require("rxjs/util/not"); + var filter_1 = require("rxjs/operator/filter"); + function partition(predicate, thisArg) { + return [filter_1.filter.call(this, predicate), filter_1.filter.call(this, not_1.not(predicate, thisArg))]; + } + exports.partition = partition; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/publish", ["rxjs/Observable", "rxjs/operator/publish"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var publish_1 = require("rxjs/operator/publish"); + Observable_1.Observable.prototype.publish = publish_1.publish; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/subject/BehaviorSubject", ["rxjs/Subject", "rxjs/util/throwError", "rxjs/util/ObjectUnsubscribedError"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subject_1 = require("rxjs/Subject"); + var throwError_1 = require("rxjs/util/throwError"); + var ObjectUnsubscribedError_1 = require("rxjs/util/ObjectUnsubscribedError"); + var BehaviorSubject = (function(_super) { + __extends(BehaviorSubject, _super); + function BehaviorSubject(_value) { + _super.call(this); + this._value = _value; + this._hasError = false; + } + BehaviorSubject.prototype.getValue = function() { + if (this._hasError) { + throwError_1.throwError(this._err); + } else if (this.isUnsubscribed) { + throwError_1.throwError(new ObjectUnsubscribedError_1.ObjectUnsubscribedError()); + } else { + return this._value; + } + }; + Object.defineProperty(BehaviorSubject.prototype, "value", { + get: function() { + return this.getValue(); + }, + enumerable: true, + configurable: true + }); + BehaviorSubject.prototype._subscribe = function(subscriber) { + var subscription = _super.prototype._subscribe.call(this, subscriber); + if (!subscription) { + return ; + } else if (!subscription.isUnsubscribed) { + subscriber.next(this._value); + } + return subscription; + }; + BehaviorSubject.prototype._next = function(value) { + _super.prototype._next.call(this, this._value = value); + }; + BehaviorSubject.prototype._error = function(err) { + this._hasError = true; + _super.prototype._error.call(this, this._err = err); + }; + return BehaviorSubject; + })(Subject_1.Subject); + exports.BehaviorSubject = BehaviorSubject; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/publishReplay", ["rxjs/subject/ReplaySubject", "rxjs/operator/multicast"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var ReplaySubject_1 = require("rxjs/subject/ReplaySubject"); + var multicast_1 = require("rxjs/operator/multicast"); + function publishReplay(bufferSize, windowTime, scheduler) { + if (bufferSize === void 0) { + bufferSize = Number.POSITIVE_INFINITY; + } + if (windowTime === void 0) { + windowTime = Number.POSITIVE_INFINITY; + } + return multicast_1.multicast.call(this, new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler)); + } + exports.publishReplay = publishReplay; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/publishLast", ["rxjs/Observable", "rxjs/operator/publishLast"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var publishLast_1 = require("rxjs/operator/publishLast"); + Observable_1.Observable.prototype.publishLast = publishLast_1.publishLast; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/reduce", ["rxjs/operator/reduce-support"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var reduce_support_1 = require("rxjs/operator/reduce-support"); + function reduce(project, seed) { + return this.lift(new reduce_support_1.ReduceOperator(project, seed)); + } + exports.reduce = reduce; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/repeat", ["rxjs/Observable", "rxjs/operator/repeat"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var repeat_1 = require("rxjs/operator/repeat"); + Observable_1.Observable.prototype.repeat = repeat_1.repeat; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/retry", ["rxjs/Observable", "rxjs/operator/retry"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var retry_1 = require("rxjs/operator/retry"); + Observable_1.Observable.prototype.retry = retry_1.retry; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/retryWhen", ["rxjs/Observable", "rxjs/operator/retryWhen"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var retryWhen_1 = require("rxjs/operator/retryWhen"); + Observable_1.Observable.prototype.retryWhen = retryWhen_1.retryWhen; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/sample", ["rxjs/Observable", "rxjs/operator/sample"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var sample_1 = require("rxjs/operator/sample"); + Observable_1.Observable.prototype.sample = sample_1.sample; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/sampleTime", ["rxjs/Observable", "rxjs/operator/sampleTime"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var sampleTime_1 = require("rxjs/operator/sampleTime"); + Observable_1.Observable.prototype.sampleTime = sampleTime_1.sampleTime; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/scan", ["rxjs/Observable", "rxjs/operator/scan"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var scan_1 = require("rxjs/operator/scan"); + Observable_1.Observable.prototype.scan = scan_1.scan; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/share", ["rxjs/Observable", "rxjs/operator/share"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var share_1 = require("rxjs/operator/share"); + Observable_1.Observable.prototype.share = share_1.share; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/single", ["rxjs/Observable", "rxjs/operator/single"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var single_1 = require("rxjs/operator/single"); + Observable_1.Observable.prototype.single = single_1.single; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/skip", ["rxjs/Observable", "rxjs/operator/skip"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var skip_1 = require("rxjs/operator/skip"); + Observable_1.Observable.prototype.skip = skip_1.skip; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/skipUntil", ["rxjs/Observable", "rxjs/operator/skipUntil"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var skipUntil_1 = require("rxjs/operator/skipUntil"); + Observable_1.Observable.prototype.skipUntil = skipUntil_1.skipUntil; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/skipWhile", ["rxjs/Observable", "rxjs/operator/skipWhile"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var skipWhile_1 = require("rxjs/operator/skipWhile"); + Observable_1.Observable.prototype.skipWhile = skipWhile_1.skipWhile; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/startWith", ["rxjs/Observable", "rxjs/operator/startWith"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var startWith_1 = require("rxjs/operator/startWith"); + Observable_1.Observable.prototype.startWith = startWith_1.startWith; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/subscribeOn", ["rxjs/observable/SubscribeOnObservable"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var SubscribeOnObservable_1 = require("rxjs/observable/SubscribeOnObservable"); + function subscribeOn(scheduler, delay) { + if (delay === void 0) { + delay = 0; + } + return new SubscribeOnObservable_1.SubscribeOnObservable(this, delay, scheduler); + } + exports.subscribeOn = subscribeOn; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/switch", ["rxjs/Observable", "rxjs/operator/switch"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var switch_1 = require("rxjs/operator/switch"); + Observable_1.Observable.prototype.switch = switch_1._switch; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/switchMap", ["rxjs/Observable", "rxjs/operator/switchMap"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var switchMap_1 = require("rxjs/operator/switchMap"); + Observable_1.Observable.prototype.switchMap = switchMap_1.switchMap; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/switchMapTo", ["rxjs/Observable", "rxjs/operator/switchMapTo"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var switchMapTo_1 = require("rxjs/operator/switchMapTo"); + Observable_1.Observable.prototype.switchMapTo = switchMapTo_1.switchMapTo; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/take", ["rxjs/Subscriber", "rxjs/util/ArgumentOutOfRangeError", "rxjs/observable/empty"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var ArgumentOutOfRangeError_1 = require("rxjs/util/ArgumentOutOfRangeError"); + var empty_1 = require("rxjs/observable/empty"); + function take(total) { + if (total === 0) { + return new empty_1.EmptyObservable(); + } else { + return this.lift(new TakeOperator(total)); + } + } + exports.take = take; + var TakeOperator = (function() { + function TakeOperator(total) { + this.total = total; + if (this.total < 0) { + throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError; + } + } + TakeOperator.prototype.call = function(subscriber) { + return new TakeSubscriber(subscriber, this.total); + }; + return TakeOperator; + })(); + var TakeSubscriber = (function(_super) { + __extends(TakeSubscriber, _super); + function TakeSubscriber(destination, total) { + _super.call(this, destination); + this.total = total; + this.count = 0; + } + TakeSubscriber.prototype._next = function(value) { + var total = this.total; + if (++this.count <= total) { + this.destination.next(value); + if (this.count === total) { + this.destination.complete(); + } + } + }; + return TakeSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/takeUntil", ["rxjs/Observable", "rxjs/operator/takeUntil"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var takeUntil_1 = require("rxjs/operator/takeUntil"); + Observable_1.Observable.prototype.takeUntil = takeUntil_1.takeUntil; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/takeWhile", ["rxjs/Observable", "rxjs/operator/takeWhile"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var takeWhile_1 = require("rxjs/operator/takeWhile"); + Observable_1.Observable.prototype.takeWhile = takeWhile_1.takeWhile; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/throttle", ["rxjs/Observable", "rxjs/operator/throttle"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var throttle_1 = require("rxjs/operator/throttle"); + Observable_1.Observable.prototype.throttle = throttle_1.throttle; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/throttleTime", ["rxjs/Observable", "rxjs/operator/throttleTime"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var throttleTime_1 = require("rxjs/operator/throttleTime"); + Observable_1.Observable.prototype.throttleTime = throttleTime_1.throttleTime; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/timeout", ["rxjs/Observable", "rxjs/operator/timeout"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var timeout_1 = require("rxjs/operator/timeout"); + Observable_1.Observable.prototype.timeout = timeout_1.timeout; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/timeoutWith", ["rxjs/Observable", "rxjs/operator/timeoutWith"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var timeoutWith_1 = require("rxjs/operator/timeoutWith"); + Observable_1.Observable.prototype.timeoutWith = timeoutWith_1.timeoutWith; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/toArray", ["rxjs/Observable", "rxjs/operator/toArray"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var toArray_1 = require("rxjs/operator/toArray"); + Observable_1.Observable.prototype.toArray = toArray_1.toArray; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/toPromise", ["rxjs/Observable", "rxjs/operator/toPromise"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var toPromise_1 = require("rxjs/operator/toPromise"); + Observable_1.Observable.prototype.toPromise = toPromise_1.toPromise; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/window", ["rxjs/Observable", "rxjs/operator/window"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var window_1 = require("rxjs/operator/window"); + Observable_1.Observable.prototype.window = window_1.window; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/windowCount", ["rxjs/Observable", "rxjs/operator/windowCount"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var windowCount_1 = require("rxjs/operator/windowCount"); + Observable_1.Observable.prototype.windowCount = windowCount_1.windowCount; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/windowTime", ["rxjs/Observable", "rxjs/operator/windowTime"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var windowTime_1 = require("rxjs/operator/windowTime"); + Observable_1.Observable.prototype.windowTime = windowTime_1.windowTime; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/windowToggle", ["rxjs/Observable", "rxjs/operator/windowToggle"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var windowToggle_1 = require("rxjs/operator/windowToggle"); + Observable_1.Observable.prototype.windowToggle = windowToggle_1.windowToggle; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/windowWhen", ["rxjs/Observable", "rxjs/operator/windowWhen"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var windowWhen_1 = require("rxjs/operator/windowWhen"); + Observable_1.Observable.prototype.windowWhen = windowWhen_1.windowWhen; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/withLatestFrom", ["rxjs/Observable", "rxjs/operator/withLatestFrom"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var withLatestFrom_1 = require("rxjs/operator/withLatestFrom"); + Observable_1.Observable.prototype.withLatestFrom = withLatestFrom_1.withLatestFrom; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/zip", ["rxjs/Observable", "rxjs/operator/zip"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var zip_1 = require("rxjs/operator/zip"); + Observable_1.Observable.prototype.zip = zip_1.zipProto; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/zipAll", ["rxjs/Observable", "rxjs/operator/zipAll"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var zipAll_1 = require("rxjs/operator/zipAll"); + Observable_1.Observable.prototype.zipAll = zipAll_1.zipAll; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/symbol/rxSubscriber", ["rxjs/util/SymbolShim"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var SymbolShim_1 = require("rxjs/util/SymbolShim"); + exports.rxSubscriber = SymbolShim_1.SymbolShim.for('rxSubscriber'); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/ScalarObservable", ["rxjs/Observable", "rxjs/util/tryCatch", "rxjs/util/errorObject", "rxjs/observable/throw", "rxjs/observable/empty"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Observable_1 = require("rxjs/Observable"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + var throw_1 = require("rxjs/observable/throw"); + var empty_1 = require("rxjs/observable/empty"); + var ScalarObservable = (function(_super) { + __extends(ScalarObservable, _super); + function ScalarObservable(value, scheduler) { + _super.call(this); + this.value = value; + this.scheduler = scheduler; + this._isScalar = true; + } + ScalarObservable.create = function(value, scheduler) { + return new ScalarObservable(value, scheduler); + }; + ScalarObservable.dispatch = function(state) { + var done = state.done, + value = state.value, + subscriber = state.subscriber; + if (done) { + subscriber.complete(); + return ; + } + subscriber.next(value); + if (subscriber.isUnsubscribed) { + return ; + } + state.done = true; + this.schedule(state); + }; + ScalarObservable.prototype._subscribe = function(subscriber) { + var value = this.value; + var scheduler = this.scheduler; + if (scheduler) { + subscriber.add(scheduler.schedule(ScalarObservable.dispatch, 0, { + done: false, + value: value, + subscriber: subscriber + })); + } else { + subscriber.next(value); + if (!subscriber.isUnsubscribed) { + subscriber.complete(); + } + } + }; + return ScalarObservable; + })(Observable_1.Observable); + exports.ScalarObservable = ScalarObservable; + var proto = ScalarObservable.prototype; + proto.map = function(project, thisArg) { + var result = tryCatch_1.tryCatch(project).call(thisArg || this, this.value, 0); + if (result === errorObject_1.errorObject) { + return new throw_1.ErrorObservable(errorObject_1.errorObject.e); + } else { + return new ScalarObservable(project.call(thisArg || this, this.value, 0)); + } + }; + proto.filter = function(select, thisArg) { + var result = tryCatch_1.tryCatch(select).call(thisArg || this, this.value, 0); + if (result === errorObject_1.errorObject) { + return new throw_1.ErrorObservable(errorObject_1.errorObject.e); + } else if (result) { + return this; + } else { + return new empty_1.EmptyObservable(); + } + }; + proto.reduce = function(project, seed) { + if (typeof seed === 'undefined') { + return this; + } + var result = tryCatch_1.tryCatch(project)(seed, this.value); + if (result === errorObject_1.errorObject) { + return new throw_1.ErrorObservable(errorObject_1.errorObject.e); + } else { + return new ScalarObservable(result); + } + }; + proto.scan = function(project, acc) { + return this.reduce(project, acc); + }; + proto.count = function(predicate) { + if (!predicate) { + return new ScalarObservable(1); + } else { + var result = tryCatch_1.tryCatch(predicate).call(this, this.value, 0, this); + if (result === errorObject_1.errorObject) { + return new throw_1.ErrorObservable(errorObject_1.errorObject.e); + } else { + return new ScalarObservable(result ? 1 : 0); + } + } + }; + proto.skip = function(count) { + if (count > 0) { + return new empty_1.EmptyObservable(); + } + return this; + }; + proto.take = function(count) { + if (count > 0) { + return this; + } + return new empty_1.EmptyObservable(); + }; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/combineLatest-support", ["rxjs/util/tryCatch", "rxjs/util/errorObject", "rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); + var CombineLatestOperator = (function() { + function CombineLatestOperator(project) { + this.project = project; + } + CombineLatestOperator.prototype.call = function(subscriber) { + return new CombineLatestSubscriber(subscriber, this.project); + }; + return CombineLatestOperator; + })(); + exports.CombineLatestOperator = CombineLatestOperator; + var CombineLatestSubscriber = (function(_super) { + __extends(CombineLatestSubscriber, _super); + function CombineLatestSubscriber(destination, project) { + _super.call(this, destination); + this.project = project; + this.active = 0; + this.values = []; + this.observables = []; + this.toRespond = []; + } + CombineLatestSubscriber.prototype._next = function(observable) { + var toRespond = this.toRespond; + toRespond.push(toRespond.length); + this.observables.push(observable); + }; + CombineLatestSubscriber.prototype._complete = function() { + var observables = this.observables; + var len = observables.length; + if (len === 0) { + this.destination.complete(); + } else { + this.active = len; + for (var i = 0; i < len; i++) { + var observable = observables[i]; + this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i)); + } + } + }; + CombineLatestSubscriber.prototype.notifyComplete = function(unused) { + if ((this.active -= 1) === 0) { + this.destination.complete(); + } + }; + CombineLatestSubscriber.prototype.notifyNext = function(observable, value, outerIndex, innerIndex) { + var values = this.values; + values[outerIndex] = value; + var toRespond = this.toRespond; + if (toRespond.length > 0) { + var found = toRespond.indexOf(outerIndex); + if (found !== -1) { + toRespond.splice(found, 1); + } + } + if (toRespond.length === 0) { + var project = this.project; + var destination = this.destination; + if (project) { + var result = tryCatch_1.tryCatch(project).apply(this, values); + if (result === errorObject_1.errorObject) { + destination.error(errorObject_1.errorObject.e); + } else { + destination.next(result); + } + } else { + destination.next(values); + } + } + }; + return CombineLatestSubscriber; + })(OuterSubscriber_1.OuterSubscriber); + exports.CombineLatestSubscriber = CombineLatestSubscriber; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/scheduler/queue", ["rxjs/scheduler/QueueScheduler"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var QueueScheduler_1 = require("rxjs/scheduler/QueueScheduler"); + exports.queue = new QueueScheduler_1.QueueScheduler(); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/observable/bindCallback", ["rxjs/Observable", "rxjs/observable/bindCallback"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var bindCallback_1 = require("rxjs/observable/bindCallback"); + Observable_1.Observable.bindCallback = bindCallback_1.BoundCallbackObservable.create; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/observable/forkJoin", ["rxjs/Observable", "rxjs/observable/forkJoin"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var forkJoin_1 = require("rxjs/observable/forkJoin"); + Observable_1.Observable.forkJoin = forkJoin_1.ForkJoinObservable.create; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/from", ["rxjs/observable/fromPromise", "rxjs/observable/IteratorObservable", "rxjs/observable/fromArray", "rxjs/util/SymbolShim", "rxjs/Observable", "rxjs/operator/observeOn-support", "rxjs/scheduler/queue"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var fromPromise_1 = require("rxjs/observable/fromPromise"); + var IteratorObservable_1 = require("rxjs/observable/IteratorObservable"); + var fromArray_1 = require("rxjs/observable/fromArray"); + var SymbolShim_1 = require("rxjs/util/SymbolShim"); + var Observable_1 = require("rxjs/Observable"); + var observeOn_support_1 = require("rxjs/operator/observeOn-support"); + var queue_1 = require("rxjs/scheduler/queue"); + var isArray = Array.isArray; + var FromObservable = (function(_super) { + __extends(FromObservable, _super); + function FromObservable(ish, scheduler) { + _super.call(this, null); + this.ish = ish; + this.scheduler = scheduler; + } + FromObservable.create = function(ish, scheduler) { + if (scheduler === void 0) { + scheduler = queue_1.queue; + } + if (ish) { + if (isArray(ish)) { + return new fromArray_1.ArrayObservable(ish, scheduler); + } else if (typeof ish.then === 'function') { + return new fromPromise_1.PromiseObservable(ish, scheduler); + } else if (typeof ish[SymbolShim_1.SymbolShim.observable] === 'function') { + if (ish instanceof Observable_1.Observable) { + return ish; + } + return new FromObservable(ish, scheduler); + } else if (typeof ish[SymbolShim_1.SymbolShim.iterator] === 'function') { + return new IteratorObservable_1.IteratorObservable(ish, null, null, scheduler); + } + } + throw new TypeError((typeof ish) + ' is not observable'); + }; + FromObservable.prototype._subscribe = function(subscriber) { + var ish = this.ish; + var scheduler = this.scheduler; + if (scheduler === queue_1.queue) { + return ish[SymbolShim_1.SymbolShim.observable]().subscribe(subscriber); + } else { + return ish[SymbolShim_1.SymbolShim.observable]().subscribe(new observeOn_support_1.ObserveOnSubscriber(subscriber, scheduler, 0)); + } + }; + return FromObservable; + })(Observable_1.Observable); + exports.FromObservable = FromObservable; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/scheduler/AsapScheduler", ["rxjs/scheduler/QueueScheduler", "rxjs/scheduler/AsapAction", "rxjs/scheduler/QueueAction"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var QueueScheduler_1 = require("rxjs/scheduler/QueueScheduler"); + var AsapAction_1 = require("rxjs/scheduler/AsapAction"); + var QueueAction_1 = require("rxjs/scheduler/QueueAction"); + var AsapScheduler = (function(_super) { + __extends(AsapScheduler, _super); + function AsapScheduler() { + _super.apply(this, arguments); + } + AsapScheduler.prototype.scheduleNow = function(work, state) { + return (this.scheduled ? new QueueAction_1.QueueAction(this, work) : new AsapAction_1.AsapAction(this, work)).schedule(state); + }; + return AsapScheduler; + })(QueueScheduler_1.QueueScheduler); + exports.AsapScheduler = AsapScheduler; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/observable/timer", ["rxjs/Observable", "rxjs/observable/timer"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var timer_1 = require("rxjs/observable/timer"); + Observable_1.Observable.timer = timer_1.TimerObservable.create; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/zip-static", ["rxjs/Observable", "rxjs/operator/zip-static"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var zip_static_1 = require("rxjs/operator/zip-static"); + Observable_1.Observable.zip = zip_static_1.zip; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/concatMap", ["rxjs/Observable", "rxjs/operator/concatMap"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var concatMap_1 = require("rxjs/operator/concatMap"); + Observable_1.Observable.prototype.concatMap = concatMap_1.concatMap; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/concatMapTo", ["rxjs/Observable", "rxjs/operator/concatMapTo"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var concatMapTo_1 = require("rxjs/operator/concatMapTo"); + Observable_1.Observable.prototype.concatMapTo = concatMapTo_1.concatMapTo; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/expand", ["rxjs/Observable", "rxjs/operator/expand"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var expand_1 = require("rxjs/operator/expand"); + Observable_1.Observable.prototype.expand = expand_1.expand; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/first", ["rxjs/Observable", "rxjs/operator/first"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var first_1 = require("rxjs/operator/first"); + Observable_1.Observable.prototype.first = first_1.first; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/groupBy", ["rxjs/Subscriber", "rxjs/Observable", "rxjs/Subject", "rxjs/util/Map", "rxjs/util/FastMap", "rxjs/operator/groupBy-support", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Subscriber_1 = require("rxjs/Subscriber"); + var Observable_1 = require("rxjs/Observable"); + var Subject_1 = require("rxjs/Subject"); + var Map_1 = require("rxjs/util/Map"); + var FastMap_1 = require("rxjs/util/FastMap"); + var groupBy_support_1 = require("rxjs/operator/groupBy-support"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + function groupBy(keySelector, elementSelector, durationSelector) { + return new GroupByObservable(this, keySelector, elementSelector, durationSelector); + } + exports.groupBy = groupBy; + var GroupByObservable = (function(_super) { + __extends(GroupByObservable, _super); + function GroupByObservable(source, keySelector, elementSelector, durationSelector) { + _super.call(this); + this.source = source; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.durationSelector = durationSelector; + } + GroupByObservable.prototype._subscribe = function(subscriber) { + var refCountSubscription = new groupBy_support_1.RefCountSubscription(); + var groupBySubscriber = new GroupBySubscriber(subscriber, refCountSubscription, this.keySelector, this.elementSelector, this.durationSelector); + refCountSubscription.setPrimary(this.source.subscribe(groupBySubscriber)); + return refCountSubscription; + }; + return GroupByObservable; + })(Observable_1.Observable); + exports.GroupByObservable = GroupByObservable; + var GroupBySubscriber = (function(_super) { + __extends(GroupBySubscriber, _super); + function GroupBySubscriber(destination, refCountSubscription, keySelector, elementSelector, durationSelector) { + _super.call(this); + this.refCountSubscription = refCountSubscription; + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.durationSelector = durationSelector; + this.groups = null; + this.destination = destination; + this.add(destination); + } + GroupBySubscriber.prototype._next = function(x) { + var key = tryCatch_1.tryCatch(this.keySelector)(x); + if (key === errorObject_1.errorObject) { + this.error(key.e); + } else { + var groups = this.groups; + var elementSelector = this.elementSelector; + var durationSelector = this.durationSelector; + if (!groups) { + groups = this.groups = typeof key === 'string' ? new FastMap_1.FastMap() : new Map_1.Map(); + } + var group = groups.get(key); + if (!group) { + groups.set(key, group = new Subject_1.Subject()); + var groupedObservable = new groupBy_support_1.GroupedObservable(key, group, this.refCountSubscription); + if (durationSelector) { + var duration = tryCatch_1.tryCatch(durationSelector)(new groupBy_support_1.GroupedObservable(key, group)); + if (duration === errorObject_1.errorObject) { + this.error(duration.e); + } else { + this.add(duration._subscribe(new GroupDurationSubscriber(key, group, this))); + } + } + this.destination.next(groupedObservable); + } + if (elementSelector) { + var value = tryCatch_1.tryCatch(elementSelector)(x); + if (value === errorObject_1.errorObject) { + this.error(value.e); + } else { + group.next(value); + } + } else { + group.next(x); + } + } + }; + GroupBySubscriber.prototype._error = function(err) { + var _this = this; + var groups = this.groups; + if (groups) { + groups.forEach(function(group, key) { + group.error(err); + _this.removeGroup(key); + }); + } + this.destination.error(err); + }; + GroupBySubscriber.prototype._complete = function() { + var _this = this; + var groups = this.groups; + if (groups) { + groups.forEach(function(group, key) { + group.complete(); + _this.removeGroup(group); + }); + } + this.destination.complete(); + }; + GroupBySubscriber.prototype.removeGroup = function(key) { + this.groups.delete(key); + }; + return GroupBySubscriber; + })(Subscriber_1.Subscriber); + var GroupDurationSubscriber = (function(_super) { + __extends(GroupDurationSubscriber, _super); + function GroupDurationSubscriber(key, group, parent) { + _super.call(this, null); + this.key = key; + this.group = group; + this.parent = parent; + } + GroupDurationSubscriber.prototype._next = function(value) { + this.group.complete(); + this.parent.removeGroup(this.key); + }; + GroupDurationSubscriber.prototype._error = function(err) { + this.group.error(err); + this.parent.removeGroup(this.key); + }; + GroupDurationSubscriber.prototype._complete = function() { + this.group.complete(); + this.parent.removeGroup(this.key); + }; + return GroupDurationSubscriber; + })(Subscriber_1.Subscriber); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/multicast", ["rxjs/Observable", "rxjs/operator/multicast"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var multicast_1 = require("rxjs/operator/multicast"); + Observable_1.Observable.prototype.multicast = multicast_1.multicast; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/partition", ["rxjs/Observable", "rxjs/operator/partition"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var partition_1 = require("rxjs/operator/partition"); + Observable_1.Observable.prototype.partition = partition_1.partition; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/publishBehavior", ["rxjs/subject/BehaviorSubject", "rxjs/operator/multicast"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var BehaviorSubject_1 = require("rxjs/subject/BehaviorSubject"); + var multicast_1 = require("rxjs/operator/multicast"); + function publishBehavior(value) { + return multicast_1.multicast.call(this, new BehaviorSubject_1.BehaviorSubject(value)); + } + exports.publishBehavior = publishBehavior; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/publishReplay", ["rxjs/Observable", "rxjs/operator/publishReplay"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var publishReplay_1 = require("rxjs/operator/publishReplay"); + Observable_1.Observable.prototype.publishReplay = publishReplay_1.publishReplay; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/reduce", ["rxjs/Observable", "rxjs/operator/reduce"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var reduce_1 = require("rxjs/operator/reduce"); + Observable_1.Observable.prototype.reduce = reduce_1.reduce; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/subscribeOn", ["rxjs/Observable", "rxjs/operator/subscribeOn"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var subscribeOn_1 = require("rxjs/operator/subscribeOn"); + Observable_1.Observable.prototype.subscribeOn = subscribeOn_1.subscribeOn; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/take", ["rxjs/Observable", "rxjs/operator/take"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var take_1 = require("rxjs/operator/take"); + Observable_1.Observable.prototype.take = take_1.take; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/Subscriber", ["rxjs/util/noop", "rxjs/util/throwError", "rxjs/util/tryOrOnError", "rxjs/Subscription", "rxjs/symbol/rxSubscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var noop_1 = require("rxjs/util/noop"); + var throwError_1 = require("rxjs/util/throwError"); + var tryOrOnError_1 = require("rxjs/util/tryOrOnError"); + var Subscription_1 = require("rxjs/Subscription"); + var rxSubscriber_1 = require("rxjs/symbol/rxSubscriber"); + var Subscriber = (function(_super) { + __extends(Subscriber, _super); + function Subscriber(destination) { + _super.call(this); + this.destination = destination; + this._isUnsubscribed = false; + if (!this.destination) { + return ; + } + var subscription = destination._subscription; + if (subscription) { + this._subscription = subscription; + } else if (destination instanceof Subscriber) { + this._subscription = destination; + } + } + Subscriber.prototype[rxSubscriber_1.rxSubscriber] = function() { + return this; + }; + Object.defineProperty(Subscriber.prototype, "isUnsubscribed", { + get: function() { + var subscription = this._subscription; + if (subscription) { + return this._isUnsubscribed || subscription.isUnsubscribed; + } else { + return this._isUnsubscribed; + } + }, + set: function(value) { + var subscription = this._subscription; + if (subscription) { + subscription.isUnsubscribed = Boolean(value); + } else { + this._isUnsubscribed = Boolean(value); + } + }, + enumerable: true, + configurable: true + }); + Subscriber.create = function(next, error, complete) { + var subscriber = new Subscriber(); + subscriber._next = (typeof next === 'function') && tryOrOnError_1.tryOrOnError(next) || noop_1.noop; + subscriber._error = (typeof error === 'function') && error || throwError_1.throwError; + subscriber._complete = (typeof complete === 'function') && complete || noop_1.noop; + return subscriber; + }; + Subscriber.prototype.add = function(sub) { + var _subscription = this._subscription; + if (_subscription) { + _subscription.add(sub); + } else { + _super.prototype.add.call(this, sub); + } + }; + Subscriber.prototype.remove = function(sub) { + if (this._subscription) { + this._subscription.remove(sub); + } else { + _super.prototype.remove.call(this, sub); + } + }; + Subscriber.prototype.unsubscribe = function() { + if (this._isUnsubscribed) { + return ; + } else if (this._subscription) { + this._isUnsubscribed = true; + } else { + _super.prototype.unsubscribe.call(this); + } + }; + Subscriber.prototype._next = function(value) { + var destination = this.destination; + if (destination.next) { + destination.next(value); + } + }; + Subscriber.prototype._error = function(err) { + var destination = this.destination; + if (destination.error) { + destination.error(err); + } + }; + Subscriber.prototype._complete = function() { + var destination = this.destination; + if (destination.complete) { + destination.complete(); + } + }; + Subscriber.prototype.next = function(value) { + if (!this.isUnsubscribed) { + this._next(value); + } + }; + Subscriber.prototype.error = function(err) { + if (!this.isUnsubscribed) { + this._error(err); + this.unsubscribe(); + } + }; + Subscriber.prototype.complete = function() { + if (!this.isUnsubscribed) { + this._complete(); + this.unsubscribe(); + } + }; + return Subscriber; + })(Subscription_1.Subscription); + exports.Subscriber = Subscriber; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/fromArray", ["rxjs/Observable", "rxjs/observable/ScalarObservable", "rxjs/observable/empty", "rxjs/util/isScheduler"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Observable_1 = require("rxjs/Observable"); + var ScalarObservable_1 = require("rxjs/observable/ScalarObservable"); + var empty_1 = require("rxjs/observable/empty"); + var isScheduler_1 = require("rxjs/util/isScheduler"); + var ArrayObservable = (function(_super) { + __extends(ArrayObservable, _super); + function ArrayObservable(array, scheduler) { + _super.call(this); + this.array = array; + this.scheduler = scheduler; + if (!scheduler && array.length === 1) { + this._isScalar = true; + this.value = array[0]; + } + } + ArrayObservable.create = function(array, scheduler) { + return new ArrayObservable(array, scheduler); + }; + ArrayObservable.of = function() { + var array = []; + for (var _i = 0; _i < arguments.length; _i++) { + array[_i - 0] = arguments[_i]; + } + var scheduler = array[array.length - 1]; + if (isScheduler_1.isScheduler(scheduler)) { + array.pop(); + } else { + scheduler = void 0; + } + var len = array.length; + if (len > 1) { + return new ArrayObservable(array, scheduler); + } else if (len === 1) { + return new ScalarObservable_1.ScalarObservable(array[0], scheduler); + } else { + return new empty_1.EmptyObservable(scheduler); + } + }; + ArrayObservable.dispatch = function(state) { + var array = state.array, + index = state.index, + count = state.count, + subscriber = state.subscriber; + if (index >= count) { + subscriber.complete(); + return ; + } + subscriber.next(array[index]); + if (subscriber.isUnsubscribed) { + return ; + } + state.index = index + 1; + this.schedule(state); + }; + ArrayObservable.prototype._subscribe = function(subscriber) { + var index = 0; + var array = this.array; + var count = array.length; + var scheduler = this.scheduler; + if (scheduler) { + subscriber.add(scheduler.schedule(ArrayObservable.dispatch, 0, { + array: array, + index: index, + count: count, + subscriber: subscriber + })); + } else { + for (var i = 0; i < count && !subscriber.isUnsubscribed; i++) { + subscriber.next(array[i]); + } + subscriber.complete(); + } + }; + return ArrayObservable; + })(Observable_1.Observable); + exports.ArrayObservable = ArrayObservable; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/concat-static", ["rxjs/scheduler/queue", "rxjs/operator/mergeAll-support", "rxjs/observable/fromArray", "rxjs/util/isScheduler"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var queue_1 = require("rxjs/scheduler/queue"); + var mergeAll_support_1 = require("rxjs/operator/mergeAll-support"); + var fromArray_1 = require("rxjs/observable/fromArray"); + var isScheduler_1 = require("rxjs/util/isScheduler"); + function concat() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; + } + var scheduler = queue_1.queue; + var args = observables; + if (isScheduler_1.isScheduler(args[observables.length - 1])) { + scheduler = args.pop(); + } + return new fromArray_1.ArrayObservable(observables, scheduler).lift(new mergeAll_support_1.MergeAllOperator(1)); + } + exports.concat = concat; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/observable/from", ["rxjs/Observable", "rxjs/observable/from"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var from_1 = require("rxjs/observable/from"); + Observable_1.Observable.from = from_1.FromObservable.create; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/scheduler/asap", ["rxjs/scheduler/AsapScheduler"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var AsapScheduler_1 = require("rxjs/scheduler/AsapScheduler"); + exports.asap = new AsapScheduler_1.AsapScheduler(); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/groupBy", ["rxjs/Observable", "rxjs/operator/groupBy"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var groupBy_1 = require("rxjs/operator/groupBy"); + Observable_1.Observable.prototype.groupBy = groupBy_1.groupBy; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/publishBehavior", ["rxjs/Observable", "rxjs/operator/publishBehavior"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var publishBehavior_1 = require("rxjs/operator/publishBehavior"); + Observable_1.Observable.prototype.publishBehavior = publishBehavior_1.publishBehavior; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/Observable", ["rxjs/Subscriber", "rxjs/util/root", "rxjs/util/SymbolShim", "rxjs/symbol/rxSubscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Subscriber_1 = require("rxjs/Subscriber"); + var root_1 = require("rxjs/util/root"); + var SymbolShim_1 = require("rxjs/util/SymbolShim"); + var rxSubscriber_1 = require("rxjs/symbol/rxSubscriber"); + var Observable = (function() { + function Observable(subscribe) { + this._isScalar = false; + if (subscribe) { + this._subscribe = subscribe; + } + } + Observable.prototype.lift = function(operator) { + var observable = new Observable(); + observable.source = this; + observable.operator = operator; + return observable; + }; + Observable.prototype[SymbolShim_1.SymbolShim.observable] = function() { + return this; + }; + Observable.prototype.subscribe = function(observerOrNext, error, complete) { + var subscriber; + if (observerOrNext && typeof observerOrNext === 'object') { + if (observerOrNext instanceof Subscriber_1.Subscriber) { + subscriber = observerOrNext; + } else if (observerOrNext[rxSubscriber_1.rxSubscriber]) { + subscriber = observerOrNext[rxSubscriber_1.rxSubscriber](); + } else { + subscriber = new Subscriber_1.Subscriber(observerOrNext); + } + } else { + var next = observerOrNext; + subscriber = Subscriber_1.Subscriber.create(next, error, complete); + } + subscriber.add(this._subscribe(subscriber)); + return subscriber; + }; + Observable.prototype.forEach = function(next, thisArg, PromiseCtor) { + if (!PromiseCtor) { + if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) { + PromiseCtor = root_1.root.Rx.config.Promise; + } else if (root_1.root.Promise) { + PromiseCtor = root_1.root.Promise; + } + } + if (!PromiseCtor) { + throw new Error('no Promise impl found'); + } + var nextHandler; + if (thisArg) { + nextHandler = function nextHandlerFn(value) { + var _a = nextHandlerFn, + thisArg = _a.thisArg, + next = _a.next; + return next.call(thisArg, value); + }; + nextHandler.thisArg = thisArg; + nextHandler.next = next; + } else { + nextHandler = next; + } + var promiseCallback = function promiseCallbackFn(resolve, reject) { + var _a = promiseCallbackFn, + source = _a.source, + nextHandler = _a.nextHandler; + source.subscribe(nextHandler, reject, resolve); + }; + promiseCallback.source = this; + promiseCallback.nextHandler = nextHandler; + return new PromiseCtor(promiseCallback); + }; + Observable.prototype._subscribe = function(subscriber) { + return this.source._subscribe(this.operator.call(subscriber)); + }; + Observable.create = function(subscribe) { + return new Observable(subscribe); + }; + return Observable; + })(); + exports.Observable = Observable; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/combineLatest-static", ["rxjs/observable/fromArray", "rxjs/operator/combineLatest-support", "rxjs/util/isScheduler", "rxjs/util/isArray"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var fromArray_1 = require("rxjs/observable/fromArray"); + var combineLatest_support_1 = require("rxjs/operator/combineLatest-support"); + var isScheduler_1 = require("rxjs/util/isScheduler"); + var isArray_1 = require("rxjs/util/isArray"); + function combineLatest() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; + } + var project = null; + var scheduler = null; + if (isScheduler_1.isScheduler(observables[observables.length - 1])) { + scheduler = observables.pop(); + } + if (typeof observables[observables.length - 1] === 'function') { + project = observables.pop(); + } + if (observables.length === 1 && isArray_1.isArray(observables[0])) { + observables = observables[0]; + } + return new fromArray_1.ArrayObservable(observables, scheduler).lift(new combineLatest_support_1.CombineLatestOperator(project)); + } + exports.combineLatest = combineLatest; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/concat-static", ["rxjs/Observable", "rxjs/operator/concat-static"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var concat_static_1 = require("rxjs/operator/concat-static"); + Observable_1.Observable.concat = concat_static_1.concat; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/interval", ["rxjs/util/isNumeric", "rxjs/Observable", "rxjs/scheduler/asap"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var isNumeric_1 = require("rxjs/util/isNumeric"); + var Observable_1 = require("rxjs/Observable"); + var asap_1 = require("rxjs/scheduler/asap"); + var IntervalObservable = (function(_super) { + __extends(IntervalObservable, _super); + function IntervalObservable(period, scheduler) { + if (period === void 0) { + period = 0; + } + if (scheduler === void 0) { + scheduler = asap_1.asap; + } + _super.call(this); + this.period = period; + this.scheduler = scheduler; + if (!isNumeric_1.isNumeric(period) || period < 0) { + this.period = 0; + } + if (!scheduler || typeof scheduler.schedule !== 'function') { + this.scheduler = asap_1.asap; + } + } + IntervalObservable.create = function(period, scheduler) { + if (period === void 0) { + period = 0; + } + if (scheduler === void 0) { + scheduler = asap_1.asap; + } + return new IntervalObservable(period, scheduler); + }; + IntervalObservable.dispatch = function(state) { + var index = state.index, + subscriber = state.subscriber, + period = state.period; + subscriber.next(index); + if (subscriber.isUnsubscribed) { + return ; + } + state.index += 1; + this.schedule(state, period); + }; + IntervalObservable.prototype._subscribe = function(subscriber) { + var index = 0; + var period = this.period; + var scheduler = this.scheduler; + subscriber.add(scheduler.schedule(IntervalObservable.dispatch, period, { + index: index, + subscriber: subscriber, + period: period + })); + }; + return IntervalObservable; + })(Observable_1.Observable); + exports.IntervalObservable = IntervalObservable; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/Subject", ["rxjs/Observable", "rxjs/Subscriber", "rxjs/Subscription", "rxjs/subject/SubjectSubscription", "rxjs/symbol/rxSubscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var __extends = (this && this.__extends) || function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) + d[p] = b[p]; + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var Observable_1 = require("rxjs/Observable"); + var Subscriber_1 = require("rxjs/Subscriber"); + var Subscription_1 = require("rxjs/Subscription"); + var SubjectSubscription_1 = require("rxjs/subject/SubjectSubscription"); + var rxSubscriber_1 = require("rxjs/symbol/rxSubscriber"); + var subscriptionAdd = Subscription_1.Subscription.prototype.add; + var subscriptionRemove = Subscription_1.Subscription.prototype.remove; + var subscriptionUnsubscribe = Subscription_1.Subscription.prototype.unsubscribe; + var subscriberNext = Subscriber_1.Subscriber.prototype.next; + var subscriberError = Subscriber_1.Subscriber.prototype.error; + var subscriberComplete = Subscriber_1.Subscriber.prototype.complete; + var _subscriberNext = Subscriber_1.Subscriber.prototype._next; + var _subscriberError = Subscriber_1.Subscriber.prototype._error; + var _subscriberComplete = Subscriber_1.Subscriber.prototype._complete; + var Subject = (function(_super) { + __extends(Subject, _super); + function Subject() { + _super.apply(this, arguments); + this.observers = []; + this.isUnsubscribed = false; + this.dispatching = false; + this.errorSignal = false; + this.completeSignal = false; + } + Subject.prototype[rxSubscriber_1.rxSubscriber] = function() { + return this; + }; + Subject.create = function(source, destination) { + return new BidirectionalSubject(source, destination); + }; + Subject.prototype.lift = function(operator) { + var subject = new BidirectionalSubject(this, this.destination || this); + subject.operator = operator; + return subject; + }; + Subject.prototype._subscribe = function(subscriber) { + if (subscriber.isUnsubscribed) { + return ; + } else if (this.errorSignal) { + subscriber.error(this.errorInstance); + return ; + } else if (this.completeSignal) { + subscriber.complete(); + return ; + } else if (this.isUnsubscribed) { + throw new Error('Cannot subscribe to a disposed Subject.'); + } + this.observers.push(subscriber); + return new SubjectSubscription_1.SubjectSubscription(this, subscriber); + }; + Subject.prototype.add = function(subscription) { + subscriptionAdd.call(this, subscription); + }; + Subject.prototype.remove = function(subscription) { + subscriptionRemove.call(this, subscription); + }; + Subject.prototype.unsubscribe = function() { + this.observers = void 0; + subscriptionUnsubscribe.call(this); + }; + Subject.prototype.next = function(value) { + if (this.isUnsubscribed) { + return ; + } + this.dispatching = true; + this._next(value); + this.dispatching = false; + if (this.errorSignal) { + this.error(this.errorInstance); + } else if (this.completeSignal) { + this.complete(); + } + }; + Subject.prototype.error = function(err) { + if (this.isUnsubscribed || this.completeSignal) { + return ; + } + this.errorSignal = true; + this.errorInstance = err; + if (this.dispatching) { + return ; + } + this._error(err); + this.unsubscribe(); + }; + Subject.prototype.complete = function() { + if (this.isUnsubscribed || this.errorSignal) { + return ; + } + this.completeSignal = true; + if (this.dispatching) { + return ; + } + this._complete(); + this.unsubscribe(); + }; + Subject.prototype._next = function(value) { + var index = -1; + var observers = this.observers.slice(0); + var len = observers.length; + while (++index < len) { + observers[index].next(value); + } + }; + Subject.prototype._error = function(err) { + var index = -1; + var observers = this.observers; + var len = observers.length; + this.observers = void 0; + this.isUnsubscribed = true; + while (++index < len) { + observers[index].error(err); + } + this.isUnsubscribed = false; + }; + Subject.prototype._complete = function() { + var index = -1; + var observers = this.observers; + var len = observers.length; + this.observers = void 0; + this.isUnsubscribed = true; + while (++index < len) { + observers[index].complete(); + } + this.isUnsubscribed = false; + }; + return Subject; + })(Observable_1.Observable); + exports.Subject = Subject; + var BidirectionalSubject = (function(_super) { + __extends(BidirectionalSubject, _super); + function BidirectionalSubject(source, destination) { + _super.call(this); + this.source = source; + this.destination = destination; + } + BidirectionalSubject.prototype._subscribe = function(subscriber) { + var operator = this.operator; + return this.source._subscribe.call(this.source, operator ? operator.call(subscriber) : subscriber); + }; + BidirectionalSubject.prototype.next = function(value) { + subscriberNext.call(this, value); + }; + BidirectionalSubject.prototype.error = function(err) { + subscriberError.call(this, err); + }; + BidirectionalSubject.prototype.complete = function() { + subscriberComplete.call(this); + }; + BidirectionalSubject.prototype._next = function(value) { + _subscriberNext.call(this, value); + }; + BidirectionalSubject.prototype._error = function(err) { + _subscriberError.call(this, err); + }; + BidirectionalSubject.prototype._complete = function() { + _subscriberComplete.call(this); + }; + return BidirectionalSubject; + })(Subject); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/combineLatest-static", ["rxjs/Observable", "rxjs/operator/combineLatest-static"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var combineLatest_static_1 = require("rxjs/operator/combineLatest-static"); + Observable_1.Observable.combineLatest = combineLatest_static_1.combineLatest; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/observable/interval", ["rxjs/Observable", "rxjs/observable/interval"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Observable_1 = require("rxjs/Observable"); + var interval_1 = require("rxjs/observable/interval"); + Observable_1.Observable.interval = interval_1.IntervalObservable.create; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/Rx", ["rxjs/Subject", "rxjs/Observable", "rxjs/add/operator/combineLatest-static", "rxjs/add/operator/concat-static", "rxjs/add/operator/merge-static", "rxjs/add/observable/bindCallback", "rxjs/add/observable/defer", "rxjs/add/observable/empty", "rxjs/add/observable/forkJoin", "rxjs/add/observable/from", "rxjs/add/observable/fromArray", "rxjs/add/observable/fromEvent", "rxjs/add/observable/fromEventPattern", "rxjs/add/observable/fromPromise", "rxjs/add/observable/interval", "rxjs/add/observable/never", "rxjs/add/observable/range", "rxjs/add/observable/throw", "rxjs/add/observable/timer", "rxjs/add/operator/zip-static", "rxjs/add/operator/buffer", "rxjs/add/operator/bufferCount", "rxjs/add/operator/bufferTime", "rxjs/add/operator/bufferToggle", "rxjs/add/operator/bufferWhen", "rxjs/add/operator/catch", "rxjs/add/operator/combineAll", "rxjs/add/operator/combineLatest", "rxjs/add/operator/concat", "rxjs/add/operator/concatAll", "rxjs/add/operator/concatMap", "rxjs/add/operator/concatMapTo", "rxjs/add/operator/count", "rxjs/add/operator/dematerialize", "rxjs/add/operator/debounce", "rxjs/add/operator/debounceTime", "rxjs/add/operator/defaultIfEmpty", "rxjs/add/operator/delay", "rxjs/add/operator/distinctUntilChanged", "rxjs/add/operator/do", "rxjs/add/operator/expand", "rxjs/add/operator/filter", "rxjs/add/operator/finally", "rxjs/add/operator/first", "rxjs/add/operator/groupBy", "rxjs/add/operator/ignoreElements", "rxjs/add/operator/every", "rxjs/add/operator/last", "rxjs/add/operator/map", "rxjs/add/operator/mapTo", "rxjs/add/operator/materialize", "rxjs/add/operator/merge", "rxjs/add/operator/mergeAll", "rxjs/add/operator/mergeMap", "rxjs/add/operator/mergeMapTo", "rxjs/add/operator/multicast", "rxjs/add/operator/observeOn", "rxjs/add/operator/partition", "rxjs/add/operator/publish", "rxjs/add/operator/publishBehavior", "rxjs/add/operator/publishReplay", "rxjs/add/operator/publishLast", "rxjs/add/operator/reduce", "rxjs/add/operator/repeat", "rxjs/add/operator/retry", "rxjs/add/operator/retryWhen", "rxjs/add/operator/sample", "rxjs/add/operator/sampleTime", "rxjs/add/operator/scan", "rxjs/add/operator/share", "rxjs/add/operator/single", "rxjs/add/operator/skip", "rxjs/add/operator/skipUntil", "rxjs/add/operator/skipWhile", "rxjs/add/operator/startWith", "rxjs/add/operator/subscribeOn", "rxjs/add/operator/switch", "rxjs/add/operator/switchMap", "rxjs/add/operator/switchMapTo", "rxjs/add/operator/take", "rxjs/add/operator/takeUntil", "rxjs/add/operator/takeWhile", "rxjs/add/operator/throttle", "rxjs/add/operator/throttleTime", "rxjs/add/operator/timeout", "rxjs/add/operator/timeoutWith", "rxjs/add/operator/toArray", "rxjs/add/operator/toPromise", "rxjs/add/operator/window", "rxjs/add/operator/windowCount", "rxjs/add/operator/windowTime", "rxjs/add/operator/windowToggle", "rxjs/add/operator/windowWhen", "rxjs/add/operator/withLatestFrom", "rxjs/add/operator/zip", "rxjs/add/operator/zipAll", "rxjs/Subscription", "rxjs/Subscriber", "rxjs/subject/AsyncSubject", "rxjs/subject/ReplaySubject", "rxjs/subject/BehaviorSubject", "rxjs/observable/ConnectableObservable", "rxjs/Notification", "rxjs/util/EmptyError", "rxjs/util/ArgumentOutOfRangeError", "rxjs/util/ObjectUnsubscribedError", "rxjs/scheduler/asap", "rxjs/scheduler/queue", "rxjs/symbol/rxSubscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var Subject_1 = require("rxjs/Subject"); + exports.Subject = Subject_1.Subject; + var Observable_1 = require("rxjs/Observable"); + exports.Observable = Observable_1.Observable; + require("rxjs/add/operator/combineLatest-static"); + require("rxjs/add/operator/concat-static"); + require("rxjs/add/operator/merge-static"); + require("rxjs/add/observable/bindCallback"); + require("rxjs/add/observable/defer"); + require("rxjs/add/observable/empty"); + require("rxjs/add/observable/forkJoin"); + require("rxjs/add/observable/from"); + require("rxjs/add/observable/fromArray"); + require("rxjs/add/observable/fromEvent"); + require("rxjs/add/observable/fromEventPattern"); + require("rxjs/add/observable/fromPromise"); + require("rxjs/add/observable/interval"); + require("rxjs/add/observable/never"); + require("rxjs/add/observable/range"); + require("rxjs/add/observable/throw"); + require("rxjs/add/observable/timer"); + require("rxjs/add/operator/zip-static"); + require("rxjs/add/operator/buffer"); + require("rxjs/add/operator/bufferCount"); + require("rxjs/add/operator/bufferTime"); + require("rxjs/add/operator/bufferToggle"); + require("rxjs/add/operator/bufferWhen"); + require("rxjs/add/operator/catch"); + require("rxjs/add/operator/combineAll"); + require("rxjs/add/operator/combineLatest"); + require("rxjs/add/operator/concat"); + require("rxjs/add/operator/concatAll"); + require("rxjs/add/operator/concatMap"); + require("rxjs/add/operator/concatMapTo"); + require("rxjs/add/operator/count"); + require("rxjs/add/operator/dematerialize"); + require("rxjs/add/operator/debounce"); + require("rxjs/add/operator/debounceTime"); + require("rxjs/add/operator/defaultIfEmpty"); + require("rxjs/add/operator/delay"); + require("rxjs/add/operator/distinctUntilChanged"); + require("rxjs/add/operator/do"); + require("rxjs/add/operator/expand"); + require("rxjs/add/operator/filter"); + require("rxjs/add/operator/finally"); + require("rxjs/add/operator/first"); + require("rxjs/add/operator/groupBy"); + require("rxjs/add/operator/ignoreElements"); + require("rxjs/add/operator/every"); + require("rxjs/add/operator/last"); + require("rxjs/add/operator/map"); + require("rxjs/add/operator/mapTo"); + require("rxjs/add/operator/materialize"); + require("rxjs/add/operator/merge"); + require("rxjs/add/operator/mergeAll"); + require("rxjs/add/operator/mergeMap"); + require("rxjs/add/operator/mergeMapTo"); + require("rxjs/add/operator/multicast"); + require("rxjs/add/operator/observeOn"); + require("rxjs/add/operator/partition"); + require("rxjs/add/operator/publish"); + require("rxjs/add/operator/publishBehavior"); + require("rxjs/add/operator/publishReplay"); + require("rxjs/add/operator/publishLast"); + require("rxjs/add/operator/reduce"); + require("rxjs/add/operator/repeat"); + require("rxjs/add/operator/retry"); + require("rxjs/add/operator/retryWhen"); + require("rxjs/add/operator/sample"); + require("rxjs/add/operator/sampleTime"); + require("rxjs/add/operator/scan"); + require("rxjs/add/operator/share"); + require("rxjs/add/operator/single"); + require("rxjs/add/operator/skip"); + require("rxjs/add/operator/skipUntil"); + require("rxjs/add/operator/skipWhile"); + require("rxjs/add/operator/startWith"); + require("rxjs/add/operator/subscribeOn"); + require("rxjs/add/operator/switch"); + require("rxjs/add/operator/switchMap"); + require("rxjs/add/operator/switchMapTo"); + require("rxjs/add/operator/take"); + require("rxjs/add/operator/takeUntil"); + require("rxjs/add/operator/takeWhile"); + require("rxjs/add/operator/throttle"); + require("rxjs/add/operator/throttleTime"); + require("rxjs/add/operator/timeout"); + require("rxjs/add/operator/timeoutWith"); + require("rxjs/add/operator/toArray"); + require("rxjs/add/operator/toPromise"); + require("rxjs/add/operator/window"); + require("rxjs/add/operator/windowCount"); + require("rxjs/add/operator/windowTime"); + require("rxjs/add/operator/windowToggle"); + require("rxjs/add/operator/windowWhen"); + require("rxjs/add/operator/withLatestFrom"); + require("rxjs/add/operator/zip"); + require("rxjs/add/operator/zipAll"); + var Subscription_1 = require("rxjs/Subscription"); + exports.Subscription = Subscription_1.Subscription; + var Subscriber_1 = require("rxjs/Subscriber"); + exports.Subscriber = Subscriber_1.Subscriber; + var AsyncSubject_1 = require("rxjs/subject/AsyncSubject"); + exports.AsyncSubject = AsyncSubject_1.AsyncSubject; + var ReplaySubject_1 = require("rxjs/subject/ReplaySubject"); + exports.ReplaySubject = ReplaySubject_1.ReplaySubject; + var BehaviorSubject_1 = require("rxjs/subject/BehaviorSubject"); + exports.BehaviorSubject = BehaviorSubject_1.BehaviorSubject; + var ConnectableObservable_1 = require("rxjs/observable/ConnectableObservable"); + exports.ConnectableObservable = ConnectableObservable_1.ConnectableObservable; + var Notification_1 = require("rxjs/Notification"); + exports.Notification = Notification_1.Notification; + var EmptyError_1 = require("rxjs/util/EmptyError"); + exports.EmptyError = EmptyError_1.EmptyError; + var ArgumentOutOfRangeError_1 = require("rxjs/util/ArgumentOutOfRangeError"); + exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError_1.ArgumentOutOfRangeError; + var ObjectUnsubscribedError_1 = require("rxjs/util/ObjectUnsubscribedError"); + exports.ObjectUnsubscribedError = ObjectUnsubscribedError_1.ObjectUnsubscribedError; + var asap_1 = require("rxjs/scheduler/asap"); + var queue_1 = require("rxjs/scheduler/queue"); + var rxSubscriber_1 = require("rxjs/symbol/rxSubscriber"); + var Scheduler = { + asap: asap_1.asap, + queue: queue_1.queue + }; + exports.Scheduler = Scheduler; + var Symbol = {rxSubscriber: rxSubscriber_1.rxSubscriber}; + exports.Symbol = Symbol; + global.define = __define; + return module.exports; +}); diff --git a/testapp/ng2/lib/systemjs/dist/system-polyfills.js b/testapp/ng2/lib/systemjs/dist/system-polyfills.js new file mode 100644 index 000000000..b055c60e1 --- /dev/null +++ b/testapp/ng2/lib/systemjs/dist/system-polyfills.js @@ -0,0 +1,5 @@ +/* + * SystemJS Polyfills for URL and Promise providing IE8+ Support + */ +!function(t){!function(t){function e(t,n){if("string"!=typeof t)throw new TypeError("URL must be a string");var o=String(t).replace(/^\s+|\s+$/g,"").match(/^([^:\/?#]+:)?(?:\/\/(?:([^:@\/?#]*)(?::([^:@\/?#]*))?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);if(!o)throw new RangeError;var r=o[1]||"",i=o[2]||"",u=o[3]||"",c=o[4]||"",s=o[5]||"",f=o[6]||"",a=o[7]||"",h=o[8]||"",p=o[9]||"";if(void 0!==n){var l=n instanceof e?n:new e(n),d=""===r&&""===c&&""===i;d&&""===a&&""===h&&(h=l.search),d&&"/"!==a.charAt(0)&&(a=""!==a?(""===l.host&&""===l.username||""!==l.pathname?"":"/")+l.pathname.slice(0,l.pathname.lastIndexOf("/")+1)+a:l.pathname);var y=[];a.replace(/^(\.\.?(\/|$))+/,"").replace(/\/(\.(\/|$))+/g,"/").replace(/\/\.\.$/,"/../").replace(/\/?[^\/]*/g,function(t){"/.."===t?y.pop():y.push(t)}),a=y.join("").replace(/^\//,"/"===a.charAt(0)?"/":""),d&&(f=l.port,s=l.hostname,c=l.host,u=l.password,i=l.username),""===r&&(r=l.protocol)}"file:"==r&&(a=a.replace(/\\/g,"/")),this.origin=r+(""!==r||""!==c?"//":"")+c,this.href=r+(""!==r||""!==c?"//":"")+(""!==i?i+(""!==u?":"+u:"")+"@":"")+c+a+h+p,this.protocol=r,this.username=i,this.password=u,this.host=c,this.hostname=s,this.port=f,this.pathname=a,this.search=h,this.hash=p}t.URLPolyfill=e}("undefined"!=typeof self?self:global),!function(e){"object"==typeof exports?module.exports=e():"function"==typeof t&&t.amd?t(e):"undefined"!=typeof window?window.Promise=e():"undefined"!=typeof global?global.Promise=e():"undefined"!=typeof self&&(self.Promise=e())}(function(){var t;return function e(t,n,o){function r(u,c){if(!n[u]){if(!t[u]){var s="function"==typeof require&&require;if(!c&&s)return s(u,!0);if(i)return i(u,!0);throw new Error("Cannot find module '"+u+"'")}var f=n[u]={exports:{}};t[u][0].call(f.exports,function(e){var n=t[u][1][e];return r(n?n:e)},f,f.exports,e,t,n,o)}return n[u].exports}for(var i="function"==typeof require&&require,u=0;u=0&&(l.splice(e,1),h("Handled previous rejection ["+t.id+"] "+r.formatObject(t.value)))}function c(t,e){p.push(t,e),null===d&&(d=o(s,0))}function s(){for(d=null;p.length>0;)p.shift()(p.shift())}var f,a=n,h=n;"undefined"!=typeof console&&(f=console,a="undefined"!=typeof f.error?function(t){f.error(t)}:function(t){f.log(t)},h="undefined"!=typeof f.info?function(t){f.info(t)}:function(t){f.log(t)}),t.onPotentiallyUnhandledRejection=function(t){c(i,t)},t.onPotentiallyUnhandledRejectionHandled=function(t){c(u,t)},t.onFatalRejection=function(t){c(e,t.value)};var p=[],l=[],d=null;return t}})}("function"==typeof t&&t.amd?t:function(t){n.exports=t(e)})},{"../env":5,"../format":6}],5:[function(e,n,o){!function(t){"use strict";t(function(t){function e(){return"undefined"!=typeof process&&null!==process&&"function"==typeof process.nextTick}function n(){return"function"==typeof MutationObserver&&MutationObserver||"function"==typeof WebKitMutationObserver&&WebKitMutationObserver}function o(t){function e(){var t=n;n=void 0,t()}var n,o=document.createTextNode(""),r=new t(e);r.observe(o,{characterData:!0});var i=0;return function(t){n=t,o.data=i^=1}}var r,i="undefined"!=typeof setTimeout&&setTimeout,u=function(t,e){return setTimeout(t,e)},c=function(t){return clearTimeout(t)},s=function(t){return i(t,0)};if(e())s=function(t){return process.nextTick(t)};else if(r=n())s=o(r);else if(!i){var f=t,a=f("vertx");u=function(t,e){return a.setTimer(e,t)},c=a.cancelTimer,s=a.runOnLoop||a.runOnContext}return{setTimer:u,clearTimer:c,asap:s}})}("function"==typeof t&&t.amd?t:function(t){n.exports=t(e)})},{}],6:[function(e,n,o){!function(t){"use strict";t(function(){function t(t){var n="object"==typeof t&&null!==t&&t.stack?t.stack:e(t);return t instanceof Error?n:n+" (WARNING: non-Error used)"}function e(t){var e=String(t);return"[object Object]"===e&&"undefined"!=typeof JSON&&(e=n(t,e)),e}function n(t,e){try{return JSON.stringify(t)}catch(n){return e}}return{formatError:t,formatObject:e,tryStringify:n}})}("function"==typeof t&&t.amd?t:function(t){n.exports=t()})},{}],7:[function(e,n,o){!function(t){"use strict";t(function(){return function(t){function e(t,e){this._handler=t===j?e:n(t)}function n(t){function e(t){r.resolve(t)}function n(t){r.reject(t)}function o(t){r.notify(t)}var r=new b;try{t(e,n,o)}catch(i){n(i)}return r}function o(t){return k(t)?t:new e(j,new x(v(t)))}function r(t){return new e(j,new x(new q(t)))}function i(){return Z}function u(){return new e(j,new b)}function c(t,e){var n=new b(t.receiver,t.join().context);return new e(j,n)}function s(t){return a(z,null,t)}function f(t,e){return a(J,t,e)}function a(t,n,o){function r(e,r,u){u.resolved||h(o,i,e,t(n,r,e),u)}function i(t,e,n){a[t]=e,0===--f&&n.become(new R(a))}for(var u,c="function"==typeof n?r:i,s=new b,f=o.length>>>0,a=new Array(f),p=0;p0?e(n,i.value,r):(r.become(i),p(t,n+1,i))}else e(n,o,r)}function p(t,e,n){for(var o=e;on&&t._unreport()}}function d(t){return"object"!=typeof t||null===t?r(new TypeError("non-iterable passed to race()")):0===t.length?i():1===t.length?o(t[0]):y(t)}function y(t){var n,o,r,i=new b;for(n=0;n0||"function"!=typeof e&&0>r)return new this.constructor(j,o);var i=this._beget(),u=i._handler;return o.chain(u,o.receiver,t,e,n),i},e.prototype["catch"]=function(t){return this.then(void 0,t)},e.prototype._beget=function(){return c(this._handler,this.constructor)},e.all=s,e.race=d,e._traverse=f,e._visitRemaining=p,j.prototype.when=j.prototype.become=j.prototype.notify=j.prototype.fail=j.prototype._unreport=j.prototype._report=B,j.prototype._state=0,j.prototype.state=function(){return this._state},j.prototype.join=function(){for(var t=this;void 0!==t.handler;)t=t.handler;return t},j.prototype.chain=function(t,e,n,o,r){this.when({resolver:t,receiver:e,fulfilled:n,rejected:o,progress:r})},j.prototype.visit=function(t,e,n,o){this.chain(V,t,e,n,o)},j.prototype.fold=function(t,e,n,o){this.when(new S(t,e,n,o))},W(j,_),_.prototype.become=function(t){t.fail()};var V=new _;W(j,b),b.prototype._state=0,b.prototype.resolve=function(t){this.become(v(t))},b.prototype.reject=function(t){this.resolved||this.become(new q(t))},b.prototype.join=function(){if(!this.resolved)return this;for(var t=this;void 0!==t.handler;)if(t=t.handler,t===this)return this.handler=T();return t},b.prototype.run=function(){var t=this.consumers,e=this.handler;this.handler=this.handler.join(),this.consumers=void 0;for(var n=0;n2)throw new TypeError("Only one wildcard in a path is permitted");if(1==s.length){if(t==o){r=o;break}}else{var i=s[0].length;i>=a&&t.substr(0,s[0].length)==s[0]&&t.substr(t.length-s[1].length)==s[1]&&(a=i,r=o,n=t.substr(s[0].length,t.length-s[1].length-s[0].length))}}var l=e[r]||t;return"string"==typeof n&&(l=l.replace("*",n)),l}function i(){}function l(){o.call(this),N.call(this)}function u(){}function d(e,t){l.prototype[e]=t(l.prototype[e]||function(){})}function c(e){N=e(N||function(){})}function f(e){for(var t=[],n=[],r=0,a=e.length;a>r;r++){var o=O.call(t,e[r]);-1===o?(t.push(e[r]),n.push([r])):n[o].push(r)}return{names:t,indices:n}}function m(e){var t={};if("object"==typeof e||"function"==typeof e)if(q){var n;for(var r in e)(n=Object.getOwnPropertyDescriptor(e,r))&&M(t,r,n)}else{var a=e&&e.hasOwnProperty;for(var r in e)(!a||e.hasOwnProperty(r))&&(t[r]=e[r])}return t["default"]=e,M(t,"__useDefault",{value:!0}),t}function p(e,t,n){for(var r in t)n&&r in e||(e[r]=t[r]);return e}function h(e,t,n){for(var r in t){var a=t[r];r in e?a instanceof Array&&e[r]instanceof Array?e[r]=[].concat(n?a:e[r]).concat(n?e[r]:a):"object"==typeof a&&"object"==typeof e[r]?e[r]=p(p({},e[r]),a,n):n||(e[r]=a):e[r]=a}}function g(e){this.warnings&&"undefined"!=typeof console&&console.warn}function v(e,t){for(var n=e.split(".");n.length;)t=t[n.shift()];return t}function y(){if(B[this.baseURL])return B[this.baseURL];"/"!=this.baseURL[this.baseURL.length-1]&&(this.baseURL+="/");var e=new L(this.baseURL,z);return this.baseURL=e.href,B[this.baseURL]=e}function b(){return{name:null,deps:null,declare:null,execute:null,executingRequire:!1,declarative:!1,normalizedDeps:null,groupIndex:null,evaluated:!1,module:null,esModule:null,esmExports:!1}}function w(e){var t,n,r,r="~"==e[0],a=e.lastIndexOf("|");return-1!=a?(t=e.substr(a+1),n=e.substr(r,a-r)||"@system-env"):(t=null,n=e.substr(r)),{module:n,prop:t,negate:r}}function x(e){return(e.negate?"~":"")+e.module+(e.prop?"|"+e.prop:"")}function S(e,t,n){return this["import"](e.module,t).then(function(t){return e.prop?t=v(e.prop,t):"object"==typeof t&&t+""=="Module"&&(t=t["default"]),e.negate?!t:t})}function E(e,t){var n=e.match(X);if(!n)return Promise.resolve(e);var r=w(n[0].substr(2,n[0].length-3));return this.builder?this.normalize(r.module,t).then(function(t){return r.module=t,e.replace(X,"#{"+x(r)+"}")}):S.call(this,r,t,!1).then(function(n){if("string"!=typeof n)throw new TypeError("The condition value for "+e+" doesn't resolve to a string.");if(-1!=n.indexOf("/"))throw new TypeError("Unabled to interpolate conditional "+e+(t?" in "+t:"")+"\n The condition value "+n+' cannot contain a "/" separator.');return e.replace(X,n)})}function k(e,t){var n=e.lastIndexOf("#?");if(-1==n)return Promise.resolve(e);var r=w(e.substr(n+2));return this.builder?this.normalize(r.module,t).then(function(t){return r.module=t,e.substr(0,n)+"#?"+x(r)}):S.call(this,r,t,!0).then(function(t){return t?e.substr(0,n):"@empty"})}function _(e,t){for(var n in e.loadedBundles_)if(-1!=O.call(e.bundles[n],t))return Promise.resolve(n);for(var n in e.bundles)if(-1!=O.call(e.bundles[n],t))return e.normalize(n).then(function(t){return e.bundles[t]=e.bundles[n],e.loadedBundles_[t]=!0,t});return Promise.resolve()}var R="undefined"==typeof window&&"undefined"!=typeof self&&"undefined"!=typeof importScripts,P="undefined"!=typeof window&&"undefined"!=typeof document,j="undefined"!=typeof process&&!!process.platform.match(/^win/);e.console||(e.console={assert:function(){}});var M,O=Array.prototype.indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(this[t]===e)return t;return-1};!function(){try{Object.defineProperty({},"a",{})&&(M=Object.defineProperty)}catch(e){M=function(e,t,n){try{e[t]=n.value||n.get.call(e)}catch(r){}}}}();var z;if("undefined"!=typeof document&&document.getElementsByTagName){if(z=document.baseURI,!z){var T=document.getElementsByTagName("base");z=T[0]&&T[0].href||window.location.href}z=z.split("#")[0].split("?")[0],z=z.substr(0,z.lastIndexOf("/")+1)}else if("undefined"!=typeof process&&process.cwd)z="file://"+(j?"/":"")+process.cwd()+"/",j&&(z=z.replace(/\\/g,"/"));else{if("undefined"==typeof location)throw new TypeError("No environment baseURI");z=e.location.href}var L=e.URLPolyfill||e.URL;M(r.prototype,"toString",{value:function(){return"Module"}}),function(){function o(e){return{status:"loading",name:e,linkSets:[],dependencies:[],metadata:{}}}function s(e,t,n){return new Promise(c({step:n.address?"fetch":"locate",loader:e,moduleName:t,moduleMetadata:n&&n.metadata||{},moduleSource:n.source,moduleAddress:n.address}))}function i(e,t,n,r){return new Promise(function(a,o){a(e.loaderObj.normalize(t,n,r))}).then(function(t){var n;if(e.modules[t])return n=o(t),n.status="linked",n.module=e.modules[t],n;for(var r=0,a=e.loads.length;a>r;r++)if(n=e.loads[r],n.name==t)return n;return n=o(t),e.loads.push(n),l(e,n),n})}function l(e,t){u(e,t,Promise.resolve().then(function(){return e.loaderObj.locate({name:t.name,metadata:t.metadata})}))}function u(e,t,n){d(e,t,n.then(function(n){return"loading"==t.status?(t.address=n,e.loaderObj.fetch({name:t.name,metadata:t.metadata,address:n})):void 0}))}function d(t,r,a){a.then(function(a){return"loading"==r.status?Promise.resolve(t.loaderObj.translate({name:r.name,metadata:r.metadata,address:r.address,source:a})).then(function(e){return r.source=e,t.loaderObj.instantiate({name:r.name,metadata:r.metadata,address:r.address,source:e})}).then(function(a){if(void 0===a)return r.address=r.address||"",r.isDeclarative=!0,E.call(t.loaderObj,r).then(function(t){var a=e.System,o=a.register;a.register=function(e,t,n){"string"!=typeof e&&(n=t,t=e),r.declare=n,r.depsList=t},n(t,r.address,{}),a.register=o});if("object"!=typeof a)throw TypeError("Invalid instantiate return value");r.depsList=a.deps||[],r.execute=a.execute,r.isDeclarative=!1}).then(function(){r.dependencies=[];for(var e=r.depsList,n=[],a=0,o=e.length;o>a;a++)(function(e,a){n.push(i(t,e,r.name,r.address).then(function(t){if(r.dependencies[a]={key:e,value:t.name},"linked"!=t.status)for(var n=r.linkSets.concat([]),o=0,s=n.length;s>o;o++)m(n[o],t)}))})(e[a],a);return Promise.all(n)}).then(function(){r.status="loaded";for(var e=r.linkSets.concat([]),t=0,n=e.length;n>t;t++)h(e[t],r)}):void 0})["catch"](function(e){r.status="failed",r.exception=e;for(var t=r.linkSets.concat([]),n=0,a=t.length;a>n;n++)g(t[n],r,e)})}function c(e){return function(t,n){var r=e.loader,a=e.moduleName,s=e.step;if(r.modules[a])throw new TypeError('"'+a+'" already exists in the module table');for(var i,c=0,m=r.loads.length;m>c;c++)if(r.loads[c].name==a&&(i=r.loads[c],"translate"!=s||i.source||(i.address=e.moduleAddress,d(r,i,Promise.resolve(e.moduleSource))),i.linkSets.length))return i.linkSets[0].done.then(function(){t(i)});var p=i||o(a);p.metadata=e.moduleMetadata;var h=f(r,p);r.loads.push(p),t(h.done),"locate"==s?l(r,p):"fetch"==s?u(r,p,Promise.resolve(e.moduleAddress)):(p.address=e.moduleAddress,d(r,p,Promise.resolve(e.moduleSource)))}}function f(e,t){var n={loader:e,loads:[],startingLoad:t,loadingCount:0};return n.done=new Promise(function(e,t){n.resolve=e,n.reject=t}),m(n,t),n}function m(e,t){if("failed"!=t.status){for(var n=0,r=e.loads.length;r>n;n++)if(e.loads[n]==t)return;e.loads.push(t),t.linkSets.push(e),"loaded"!=t.status&&e.loadingCount++;for(var a=e.loader,n=0,r=t.dependencies.length;r>n;n++)if(t.dependencies[n]){var o=t.dependencies[n].value;if(!a.modules[o])for(var s=0,i=a.loads.length;i>s;s++)if(a.loads[s].name==o){m(e,a.loads[s]);break}}}}function p(e){var t=!1;try{w(e,function(n,r){g(e,n,r),t=!0})}catch(n){g(e,null,n),t=!0}return t}function h(e,t){if(e.loadingCount--,!(e.loadingCount>0)){var n=e.startingLoad;if(e.loader.loaderObj.execute===!1){for(var r=[].concat(e.loads),a=0,o=r.length;o>a;a++){var t=r[a];t.module=t.isDeclarative?{name:t.name,module:_({}),evaluated:!0}:{module:_({})},t.status="linked",v(e.loader,t)}return e.resolve(n)}var s=p(e);s||e.resolve(n)}}function g(e,n,r){var a=e.loader;e:if(n)if(e.loads[0].name==n.name)r=t(r,"Error loading "+n.name);else{for(var o=0;oo;o++){var n=u[o];a.loaderObj.failed=a.loaderObj.failed||[],-1==O.call(a.loaderObj.failed,n)&&a.loaderObj.failed.push(n);var c=O.call(n.linkSets,e);if(n.linkSets.splice(c,1),0==n.linkSets.length){var f=O.call(e.loader.loads,n);-1!=f&&e.loader.loads.splice(f,1)}}e.reject(r)}function v(e,t){if(e.loaderObj.trace){e.loaderObj.loads||(e.loaderObj.loads={});var n={};t.dependencies.forEach(function(e){n[e.key]=e.value}),e.loaderObj.loads[t.name]={name:t.name,deps:t.dependencies.map(function(e){return e.key}),depMap:n,address:t.address,metadata:t.metadata,source:t.source,kind:t.isDeclarative?"declarative":"dynamic"}}t.name&&(e.modules[t.name]=t.module);var r=O.call(e.loads,t);-1!=r&&e.loads.splice(r,1);for(var a=0,o=t.linkSets.length;o>a;a++)r=O.call(t.linkSets[a].loads,t),-1!=r&&t.linkSets[a].loads.splice(r,1);t.linkSets.splice(0,t.linkSets.length)}function y(e,t,n){try{var a=t.execute()}catch(o){return void n(t,o)}return a&&a instanceof r?a:void n(t,new TypeError("Execution must define a Module instance"))}function b(e,t,n){var r=e._loader.importPromises;return r[t]=n.then(function(e){return r[t]=void 0,e},function(e){throw r[t]=void 0,e})}function w(e,t){var n=e.loader;if(e.loads.length)for(var r=e.loads.concat([]),a=0;ar&&(t=a,r=n));return t}function t(e,t){var n,r=0;for(var a in e)if(t.substr(0,a.length)==a&&(t.length==a.length||"/"==t[a.length])){var o=a.split("/").length;if(r>=o)continue;n=a,r=o}return n}function n(e){var t=e.basePath&&"."!=e.basePath?e.basePath:"";return t&&("./"==t.substr(0,2)&&(t=t.substr(2)),"/"!=t[t.length-1]&&(t+="/")),t}function r(e,t,n,r,o,s,i){var l=!(!i&&-1==o.indexOf("#?")&&!o.match(X));!l&&n.modules&&f(n.modules,t,o,function(e,t,n){(0==n||e.lastIndexOf("*")!=e.length-1)&&(l=!0)});var u=t+"/"+r+o+(l?"":a(n,o));return s?u:k.call(e,u,t+"/").then(function(n){return E.call(e,n,t+"/")})}function a(e,t){if("/"!=t[t.length-1]&&e.defaultExtension!==!1){var n="."+(e.defaultExtension||"js");if(t.substr(t.length-n.length)!=n)return n}return""}function o(e,o,s,i,l){function u(e){return"."==e?o:"./"==e.substr(0,2)?r(d,o,s,c,e.substr(2),i,l):(i?d.normalizeSync:d.normalize).call(d,e)}var d=this,c=n(s);if(o===e&&s.main&&(e+="/"+("./"==s.main.substr(0,2)?s.main.substr(2):s.main)),e.length==o.length+1&&"/"==e[o.length])return e;if(e.length==o.length)return e+(d.defaultJSExtensions&&".js"!=e.substr(e.length-3,3)?".js":"");if(s.map)var f="."+e.substr(o.length),m=t(s.map,f)||!l&&t(s.map,f+=a(s,f.substr(2))),p=s.map[m];return"string"==typeof p?u(p+f.substr(m.length)):i||!p?r(d,o,s,c,e.substr(o.length+1),i,l):d.builder?o+"#:"+m.substr(2):d["import"](s.map["@env"]||"@system-env",o).then(function(e){for(var t in p){var n="~"==t[0],r=v(n?t.substr(1):t,e);if(!n&&r||n&&!r)return p[t]+f.substr(m.length)}}).then(function(t){return t?u(t):r(d,o,s,c,e.substr(o.length+1),i,l)})}function s(r,a){return function(s,l,d){function c(t,n,r){n=n||e.call(b,t);var r=r||n&&b.packages[n];return r?o.call(b,t,n,r,a,d):t+(v?".js":"")}if(d=d===!0,l)var f=e.call(this,l)||this.defaultJSExtensions&&".js"==l.substr(l.length-3,3)&&e.call(this,l.substr(0,l.length-3));if(f){var p=n(this.packages[f]);if(p&&l.substr(f.length+1,p.length)==p&&(l=f+l.substr(f.length+p.length)),"."!==s[0]){var h=this.packages[f].map;if(h){var g=t(h,s);g&&(s=h[g]+s.substr(g.length),"."===s[0]&&(l=f+"/"))}}}var v=this.defaultJSExtensions&&".js"!=s.substr(s.length-3,3),y=r.call(this,s,l);v&&".js"!=y.substr(y.length-3,3)&&(v=!1),v&&(y=y.substr(0,y.length-3)),f&&"."==s[0]&&y==f+"/"&&(y=f);var b=this;if(a)return c(y);var w=e.call(this,y),x=w&&this.packages[w];if(x&&x.configured)return c(y,w,x);var S=i(b,y);return S.pkgName?Promise.resolve(_(b,y)).then(function(e){if(e||m[S.pkgName]){var t=m[S.pkgName]=m[S.pkgName]||{bundles:[],promise:Promise.resolve()};return e&&-1==O.call(t.bundles,e)&&(t.bundles.push(e),t.promise=Promise.all([t.promise,b.load(e)])),t.promise}}).then(function(){return c(y,S.pkgName)}).then(function(e){return e in b.defined?e:u(b,S).then(function(){return c(y)})}):c(y,w,x)}}function i(e,t){for(var n,r=[],a=0;ap&&(p=n),h(m,t,n&&p>n)}),m.alias&&"./"==m.alias.substr(0,2)&&(m.alias=o+m.alias.substr(1)),m.loader&&"./"==m.loader.substr(0,2)&&(m.loader=o+m.loader.substr(1)),h(r.metadata,m)}}return t})}})}(),function(){function t(){if(o&&"interactive"===o.script.readyState)return o.load;for(var e=0;ea;a++){var s=e.normalizedDeps[a],i=n.defined[s];if(i&&!i.evaluated){var l=e.groupIndex+(i.declarative!=e.declarative);if(null===i.groupIndex||i.groupIndex=0;l--){for(var u=a[l],d=0;dr;r++){var o=s.importers[r];if(!o.locked){var l=O.call(o.dependencies,s);o.setters[l](i)}}return s.locked=!1,t});if(s.setters=l.setters,s.execute=l.execute,!s.setters||!s.execute)throw new TypeError("Invalid System.register form for "+t.name);for(var u=0,d=t.normalizedDeps.length;d>u;u++){var c,f=t.normalizedDeps[u],m=n.defined[f],p=r[f];p?c=p.exports:m&&!m.declarative?c=m.esModule:m?(o(m,n),p=m.module,c=p.exports):c=n.get(f),p&&p.importers?(p.importers.push(s),s.dependencies.push(p)):s.dependencies.push(null);for(var h=t.originalIndices[u],g=0,v=h.length;v>g;++g){var y=h[g];s.setters[y]&&s.setters[y](c)}}}}function s(e,t){var n,r=t.defined[e];if(r)r.declarative?u(e,[],t):r.evaluated||i(r,t),n=r.module.exports;else if(n=t.get(e),!n)throw new Error("Unable to load dependency "+e+".");return(!r||r.declarative)&&n&&n.__useDefault?n["default"]:n}function i(t,n){if(!t.module){var r={},a=t.module={exports:r,id:t.name};if(!t.executingRequire)for(var o=0,l=t.normalizedDeps.length;l>o;o++){var u=t.normalizedDeps[o],d=n.defined[u];d&&i(d,n)}t.evaluated=!0;var c=t.execute.call(e,function(e){for(var r=0,a=t.deps.length;a>r;r++)if(t.deps[r]==e)return s(t.normalizedDeps[r],n);throw new Error("Module "+e+" not declared as a dependency.")},r,a);c&&(a.exports=c),r=a.exports,r&&r.__esModule?t.esModule=r:t.esmExports&&r!==e?t.esModule=m(r):t.esModule={"default":r}}}function u(t,n,r){var a=r.defined[t];if(a&&!a.evaluated&&a.declarative){n.push(t);for(var o=0,s=a.normalizedDeps.length;s>o;o++){var i=a.normalizedDeps[o]; +-1==O.call(n,i)&&(r.defined[i]?u(i,n,r):r.get(i))}a.evaluated||(a.evaluated=!0,a.module.execute.call(e))}}function p(e){var t=e.match(h);return t&&"System.register"==e.substr(t[0].length,15)}l.prototype.register=function(e,t,n){if("string"!=typeof e&&(n=t,t=e,e=null),"boolean"==typeof n)return this.registerDynamic.apply(this,arguments);var r=b();r.name=e&&(this.normalizeSync||this.normalize).call(this,e),r.declarative=!0,r.deps=t,r.declare=n,this.pushRegister_({amd:!1,entry:r})},l.prototype.registerDynamic=function(e,t,n,r){"string"!=typeof e&&(r=n,n=t,t=e,e=null);var a=b();a.name=e&&(this.normalizeSync||this.normalize).call(this,e),a.deps=t,a.execute=r,a.executingRequire=n,this.pushRegister_({amd:!1,entry:a})},d("reduceRegister_",function(){return function(e,t){if(t){var n=t.entry,r=e&&e.metadata;if(n.name&&(n.name in this.defined||(this.defined[n.name]=n),r&&(r.bundle=!0)),!n.name||e&&n.name==e.name){if(!r)throw new TypeError("Unexpected anonymous System.register call.");if(r.entry)throw"register"==r.format?new Error("Multiple anonymous System.register calls in module "+e.name+". If loading a bundle, ensure all the System.register calls are named."):new Error("Module "+e.name+" interpreted as "+r.format+" module format, but called System.register.");r.format||(r.format="register"),r.entry=n}}}}),c(function(e){return function(){e.call(this),this.defined={},this._loader.moduleRecords={}}}),M(r,"toString",{value:function(){return"Module"}}),d("delete",function(e){return function(t){return delete this._loader.moduleRecords[t],delete this.defined[t],e.call(this,t)}});var h=/^\s*(\/\*[^\*]*(\*(?!\/)[^\*]*)*\*\/|\s*\/\/[^\n]*|\s*"[^"]+"\s*;?|\s*'[^']+'\s*;?)*\s*/;d("fetch",function(e){return function(t){return this.defined[t.name]?(t.metadata.format="defined",""):("register"!=t.metadata.format||t.metadata.authorization||t.metadata.scriptLoad===!1||(t.metadata.scriptLoad=!0),t.metadata.deps=t.metadata.deps||[],e.call(this,t))}}),d("translate",function(e){return function(t){return t.metadata.deps=t.metadata.deps||[],Promise.resolve(e.call(this,t)).then(function(e){return("register"==t.metadata.format||!t.metadata.format&&p(t.source))&&(t.metadata.format="register"),e})}}),d("instantiate",function(e){return function(e){var t,r=this;if(r.defined[e.name])t=r.defined[e.name],t.deps=t.deps.concat(e.metadata.deps);else if(e.metadata.entry)t=e.metadata.entry,t.deps=t.deps.concat(e.metadata.deps);else if(!(r.builder&&e.metadata.bundle||"register"!=e.metadata.format&&"esm"!=e.metadata.format&&"es6"!=e.metadata.format)){if("undefined"!=typeof U&&U.call(r,e),!e.metadata.entry&&!e.metadata.bundle)throw new Error(e.name+" detected as "+e.metadata.format+" but didn't execute.");t=e.metadata.entry,t&&e.metadata.deps&&(t.deps=t.deps.concat(e.metadata.deps))}t||(t=b(),t.deps=e.metadata.deps,t.execute=function(){}),r.defined[e.name]=t;var a=f(t.deps);t.deps=a.names,t.originalIndices=a.indices,t.name=e.name,t.esmExports=e.metadata.esmExports!==!1;for(var o=[],s=0,i=t.deps.length;i>s;s++)o.push(Promise.resolve(r.normalize(t.deps[s],e.name)));return Promise.all(o).then(function(a){return t.normalizedDeps=a,{deps:t.deps,execute:function(){return n(e.name,r),u(e.name,[],r),r.defined[e.name]=void 0,r.newModule(t.declarative?t.module.exports:t.esModule)}}})}})}(),function(){var t=/(^\s*|[}\);\n]\s*)(import\s+(['"]|(\*\s+as\s+)?[^"'\(\)\n;]+\s+from\s+['"]|\{)|export\s+\*\s+from\s+["']|export\s+(\{|default|function|class|var|const|let|async\s+function))/,n=/\$traceurRuntime\s*\./,r=/babelHelpers\s*\./;d("translate",function(a){return function(o){var s=this;return a.call(s,o).then(function(a){if("esm"==o.metadata.format||"es6"==o.metadata.format||!o.metadata.format&&a.match(t)){if("es6"==o.metadata.format&&g.call(s,"Module "+o.name+' has metadata setting its format to "es6", which is deprecated.\nThis should be updated to "esm".'),o.metadata.format="esm",s.transpiler===!1)throw new TypeError("Unable to dynamically transpile ES module as System.transpiler set to false.");return s.loadedTranspiler_=s.loadedTranspiler_||!1,s.pluginLoader&&(s.pluginLoader.loadedTranspiler_=s.loadedTranspiler_||!1),s.builder&&(o.metadata.originalSource=o.source),C.call(s,o).then(function(e){return o.metadata.sourceMap=void 0,e})}if(s.loadedTranspiler_===!1&&o.name==s.normalizeSync(s.transpiler)&&(g.call(s,"Note that internal transpilation via System.transpiler has been deprecated for transpiler plugins."),a.length>100&&(o.metadata.format=o.metadata.format||"global","traceur"===s.transpiler&&(o.metadata.exports="traceur"),"typescript"===s.transpiler&&(o.metadata.exports="ts")),s.loadedTranspiler_=!0),s.loadedTranspilerRuntime_===!1&&(o.name==s.normalizeSync("traceur-runtime")||o.name==s.normalizeSync("babel/external-helpers*"))&&(a.length>100&&(o.metadata.format=o.metadata.format||"global"),s.loadedTranspilerRuntime_=!0),("register"==o.metadata.format||o.metadata.bundle)&&s.loadedTranspilerRuntime_!==!0){if(!e.$traceurRuntime&&o.source.match(n))return s.loadedTranspilerRuntime_=s.loadedTranspilerRuntime_||!1,s["import"]("traceur-runtime").then(function(){return a});if(!e.babelHelpers&&o.source.match(r))return s.loadedTranspilerRuntime_=s.loadedTranspilerRuntime_||!1,s["import"]("babel/external-helpers").then(function(){return a})}return a})}})}();var W="undefined"!=typeof self?"self":"global";d("reduceRegister_",function(t){return function(n,r){if(r)return t.call(this,n,r);n.metadata.format="global";var a=n.metadata.entry=b(),o=v(n.metadata.exports,e);a.execute=function(){return o}}}),d("fetch",function(e){return function(t){return t.metadata.exports&&!t.metadata.format&&(t.metadata.format="global"),"global"!=t.metadata.format||t.metadata.authorization||!t.metadata.exports||t.metadata.globals||t.metadata.deps&&0!=t.metadata.deps.length||t.metadata.scriptLoad===!1||(t.metadata.scriptLoad=!0),e.call(this,t)}}),d("instantiate",function(e){return function(t){var n=this;if(t.metadata.format||(t.metadata.format="global"),t.metadata.globals&&t.metadata.globals instanceof Array){for(var r={},a=0;at.index+(n?0:t[0].length))return!0;return!1}r.lastIndex=a.lastIndex=o.lastIndex=0;var n,s=[],i=[],l=[];if(e.length/e.split("\n").length<200){for(;n=o.exec(e);)i.push([n.index,n.index+n[0].length]);for(;n=a.exec(e);)t(i,n,!0)||l.push([n.index,n.index+n[0].length])}for(;n=r.exec(e);)t(i,n)||t(l,n)||s.push(n[1].substr(1,n[1].length-2));return s}var n=/(?:^\uFEFF?|[^$_a-zA-Z\xA0-\uFFFF.]|module\.)exports\s*(\[['"]|\.)|(?:^\uFEFF?|[^$_a-zA-Z\xA0-\uFFFF.])module\.exports\s*[=,]/,r=/(?:^\uFEFF?|[^$_a-zA-Z\xA0-\uFFFF."'])require\s*\(\s*("[^"\\]*(?:\\.[^"\\]*)*"|'[^'\\]*(?:\\.[^'\\]*)*')\s*\)/g,a=/(^|[^\\])(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/gm,o=/(?:"[^"\\\n\r]*(?:\\.[^"\\\n\r]*)*"|'[^'\\\n\r]*(?:\\.[^'\\\n\r]*)*')/g;if("undefined"!=typeof window&&"undefined"!=typeof document&&window.location)var s=location.protocol+"//"+location.hostname+(location.port?":"+location.port:"");"undefined"!=typeof require&&require.resolve&&"undefined"!=typeof process&&(l.prototype._nodeRequire=require);var i=["assert","buffer","child_process","cluster","console","constants","crypto","dgram","dns","domain","events","fs","http","https","module","net","os","path","process","punycode","querystring","readline","repl","stream","string_decoder","sys","timers","tls","tty","url","util","vm","zlib"];d("normalize",function(e){return function(t,n){if("@node/"==t.substr(0,6)&&-1!=i.indexOf(t.substr(6))){if(!this._nodeRequire)throw new TypeError("Can only load node core modules in Node.");this.set(t,this.newModule(m(this._nodeRequire(t.substr(6)))))}return e.apply(this,arguments)}}),d("instantiate",function(a){return function(o){var i=this;if(o.metadata.format||(n.lastIndex=0,r.lastIndex=0,(r.exec(o.source)||n.exec(o.source))&&(o.metadata.format="cjs")),"cjs"==o.metadata.format){var l=o.metadata.deps,u=t(o.source);for(var d in o.metadata.globals)u.push(o.metadata.globals[d]);var c=b();o.metadata.entry=c,c.deps=u,c.executingRequire=!0,c.execute=function(t,n,r){for(var a=0;a1;)r=a.shift(),e=e[r]=e[r]||{};r=a.shift(),r in e||(e[r]=n)}c(function(e){return function(){this.meta={},e.call(this)}}),d("locate",function(e){return function(t){var n,r=this.meta,a=t.name,o=0;for(var s in r)if(n=s.indexOf("*"),-1!==n&&s.substr(0,n)===a.substr(0,n)&&s.substr(n+1)===a.substr(a.length-s.length+n+1)){var i=s.split("/").length;i>o&&(o=i),h(t.metadata,r[s],o!=i)}return r[a]&&h(t.metadata,r[a]),e.call(this,t)}});var t=/^(\s*\/\*[^\*]*(\*(?!\/)[^\*]*)*\*\/|\s*\/\/[^\n]*|\s*"[^"]+"\s*;?|\s*'[^']+'\s*;?)+/,n=/\/\*[^\*]*(\*(?!\/)[^\*]*)*\*\/|\/\/[^\n]*|"[^"]+"\s*;?|'[^']+'\s*;?/g;d("translate",function(r){return function(a){var o=a.source.match(t);if(o)for(var s=o[0].match(n),i=0;i')}else if("undefined"!=typeof importScripts){var o="";try{throw new Error("_")}catch(n){n.stack.replace(/(?:at|@).*(http.+):[\d]+:[\d]+/,function(e,t){o=t.replace(/\/[^\/]*$/,"/")})}importScripts(o+"system-polyfills.js"),e()}else e()}(); +//# sourceMappingURL=system.js.map diff --git a/testapp/ng2/lib/typescript/lib/typescript.js b/testapp/ng2/lib/typescript/lib/typescript.js new file mode 100644 index 000000000..f8e546dcb --- /dev/null +++ b/testapp/ng2/lib/typescript/lib/typescript.js @@ -0,0 +1,50335 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +var ts; +(function (ts) { + // token > SyntaxKind.Identifer => token is a keyword + // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; + SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken"; + SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia"; + SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia"; + SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia"; + SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia"; + // We detect and preserve #! on the first line + SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia"; + // We detect and provide better error recovery when we encounter a git merge marker. This + // allows us to edit files with git-conflict markers in them in a much more pleasant manner. + SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia"; + // Literals + SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 10] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 11] = "NoSubstitutionTemplateLiteral"; + // Pseudo-literals + SyntaxKind[SyntaxKind["TemplateHead"] = 12] = "TemplateHead"; + SyntaxKind[SyntaxKind["TemplateMiddle"] = 13] = "TemplateMiddle"; + SyntaxKind[SyntaxKind["TemplateTail"] = 14] = "TemplateTail"; + // Punctuation + SyntaxKind[SyntaxKind["OpenBraceToken"] = 15] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 16] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 17] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 18] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 19] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 20] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 21] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 22] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 23] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 24] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 25] = "LessThanToken"; + SyntaxKind[SyntaxKind["LessThanSlashToken"] = 26] = "LessThanSlashToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 27] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 28] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 29] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 30] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 31] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 32] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 33] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 34] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 35] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 36] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 37] = "AsteriskToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 38] = "AsteriskAsteriskToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 39] = "SlashToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 40] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 41] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 42] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 43] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 44] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 45] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 46] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 47] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 48] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 49] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 50] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 51] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 52] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 53] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 54] = "ColonToken"; + SyntaxKind[SyntaxKind["AtToken"] = 55] = "AtToken"; + // Assignments + SyntaxKind[SyntaxKind["EqualsToken"] = 56] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 57] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 58] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 59] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 60] = "AsteriskAsteriskEqualsToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 61] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 62] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 63] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 64] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 65] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 66] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 67] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 68] = "CaretEqualsToken"; + // Identifiers + SyntaxKind[SyntaxKind["Identifier"] = 69] = "Identifier"; + // Reserved words + SyntaxKind[SyntaxKind["BreakKeyword"] = 70] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 71] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 72] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 73] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 74] = "ConstKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 75] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 76] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 77] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 78] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 79] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 80] = "ElseKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 81] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 82] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 83] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 84] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 85] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 86] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 87] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 88] = "IfKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 89] = "ImportKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 90] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 91] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 92] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 93] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 94] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 95] = "SuperKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 96] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 97] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 98] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 99] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 100] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 101] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 102] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 103] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 104] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 105] = "WithKeyword"; + // Strict mode reserved words + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 106] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 107] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 108] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 109] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 110] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 111] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 112] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 113] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 114] = "YieldKeyword"; + // Contextual keywords + SyntaxKind[SyntaxKind["AbstractKeyword"] = 115] = "AbstractKeyword"; + SyntaxKind[SyntaxKind["AsKeyword"] = 116] = "AsKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 117] = "AnyKeyword"; + SyntaxKind[SyntaxKind["AsyncKeyword"] = 118] = "AsyncKeyword"; + SyntaxKind[SyntaxKind["AwaitKeyword"] = 119] = "AwaitKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 120] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 121] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 122] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 123] = "GetKeyword"; + SyntaxKind[SyntaxKind["IsKeyword"] = 124] = "IsKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 125] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["NamespaceKeyword"] = 126] = "NamespaceKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 127] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 128] = "NumberKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 129] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 130] = "StringKeyword"; + SyntaxKind[SyntaxKind["SymbolKeyword"] = 131] = "SymbolKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 132] = "TypeKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 133] = "FromKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 134] = "OfKeyword"; + // Parse tree nodes + // Names + SyntaxKind[SyntaxKind["QualifiedName"] = 135] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 136] = "ComputedPropertyName"; + // Signature elements + SyntaxKind[SyntaxKind["TypeParameter"] = 137] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 138] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 139] = "Decorator"; + // TypeMember + SyntaxKind[SyntaxKind["PropertySignature"] = 140] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 141] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 142] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 143] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 144] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 145] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 146] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 147] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 148] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 149] = "IndexSignature"; + // Type + SyntaxKind[SyntaxKind["TypePredicate"] = 150] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 151] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 152] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 153] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 154] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 155] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 156] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 157] = "TupleType"; + SyntaxKind[SyntaxKind["UnionType"] = 158] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 159] = "IntersectionType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 160] = "ParenthesizedType"; + // Binding patterns + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 161] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 162] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 163] = "BindingElement"; + // Expression + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 164] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 165] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 166] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 167] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 168] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 169] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 170] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 171] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 172] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 173] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 174] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 175] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 176] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 177] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 178] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 179] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 180] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 181] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 182] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 183] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 184] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElementExpression"] = 185] = "SpreadElementExpression"; + SyntaxKind[SyntaxKind["ClassExpression"] = 186] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 187] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 188] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 189] = "AsExpression"; + // Misc + SyntaxKind[SyntaxKind["TemplateSpan"] = 190] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 191] = "SemicolonClassElement"; + // Element + SyntaxKind[SyntaxKind["Block"] = 192] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 193] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 194] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 195] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 196] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 197] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 198] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 199] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 200] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 201] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 202] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 203] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 204] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 205] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 206] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 207] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 208] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 209] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 210] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 211] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 212] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 213] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 214] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 215] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 216] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 217] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 218] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 219] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 220] = "CaseBlock"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 221] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 222] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 223] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 224] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 225] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 226] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 227] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 228] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 229] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 230] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 231] = "MissingDeclaration"; + // Module references + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 232] = "ExternalModuleReference"; + // JSX + SyntaxKind[SyntaxKind["JsxElement"] = 233] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 234] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 235] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxText"] = 236] = "JsxText"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 237] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 238] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 239] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 240] = "JsxExpression"; + // Clauses + SyntaxKind[SyntaxKind["CaseClause"] = 241] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 242] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 243] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 244] = "CatchClause"; + // Property assignments + SyntaxKind[SyntaxKind["PropertyAssignment"] = 245] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 246] = "ShorthandPropertyAssignment"; + // Enum + SyntaxKind[SyntaxKind["EnumMember"] = 247] = "EnumMember"; + // Top-level nodes + SyntaxKind[SyntaxKind["SourceFile"] = 248] = "SourceFile"; + // JSDoc nodes. + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 249] = "JSDocTypeExpression"; + // The * type. + SyntaxKind[SyntaxKind["JSDocAllType"] = 250] = "JSDocAllType"; + // The ? type. + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 251] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocArrayType"] = 252] = "JSDocArrayType"; + SyntaxKind[SyntaxKind["JSDocUnionType"] = 253] = "JSDocUnionType"; + SyntaxKind[SyntaxKind["JSDocTupleType"] = 254] = "JSDocTupleType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 255] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 256] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocRecordType"] = 257] = "JSDocRecordType"; + SyntaxKind[SyntaxKind["JSDocRecordMember"] = 258] = "JSDocRecordMember"; + SyntaxKind[SyntaxKind["JSDocTypeReference"] = 259] = "JSDocTypeReference"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 260] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 261] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 262] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocConstructorType"] = 263] = "JSDocConstructorType"; + SyntaxKind[SyntaxKind["JSDocThisType"] = 264] = "JSDocThisType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 265] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 266] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 267] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 268] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 269] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 270] = "JSDocTemplateTag"; + // Synthesized list + SyntaxKind[SyntaxKind["SyntaxList"] = 271] = "SyntaxList"; + // Enum value count + SyntaxKind[SyntaxKind["Count"] = 272] = "Count"; + // Markers + SyntaxKind[SyntaxKind["FirstAssignment"] = 56] = "FirstAssignment"; + SyntaxKind[SyntaxKind["LastAssignment"] = 68] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstReservedWord"] = 70] = "FirstReservedWord"; + SyntaxKind[SyntaxKind["LastReservedWord"] = 105] = "LastReservedWord"; + SyntaxKind[SyntaxKind["FirstKeyword"] = 70] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 134] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 106] = "FirstFutureReservedWord"; + SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 114] = "LastFutureReservedWord"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 151] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 160] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstPunctuation"] = 15] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = 68] = "LastPunctuation"; + SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; + SyntaxKind[SyntaxKind["LastToken"] = 134] = "LastToken"; + SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; + SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; + SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; + SyntaxKind[SyntaxKind["LastLiteralToken"] = 11] = "LastLiteralToken"; + SyntaxKind[SyntaxKind["FirstTemplateToken"] = 11] = "FirstTemplateToken"; + SyntaxKind[SyntaxKind["LastTemplateToken"] = 14] = "LastTemplateToken"; + SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 25] = "FirstBinaryOperator"; + SyntaxKind[SyntaxKind["LastBinaryOperator"] = 68] = "LastBinaryOperator"; + SyntaxKind[SyntaxKind["FirstNode"] = 135] = "FirstNode"; + })(ts.SyntaxKind || (ts.SyntaxKind = {})); + var SyntaxKind = ts.SyntaxKind; + (function (NodeFlags) { + NodeFlags[NodeFlags["Export"] = 1] = "Export"; + NodeFlags[NodeFlags["Ambient"] = 2] = "Ambient"; + NodeFlags[NodeFlags["Public"] = 16] = "Public"; + NodeFlags[NodeFlags["Private"] = 32] = "Private"; + NodeFlags[NodeFlags["Protected"] = 64] = "Protected"; + NodeFlags[NodeFlags["Static"] = 128] = "Static"; + NodeFlags[NodeFlags["Abstract"] = 256] = "Abstract"; + NodeFlags[NodeFlags["Async"] = 512] = "Async"; + NodeFlags[NodeFlags["Default"] = 1024] = "Default"; + NodeFlags[NodeFlags["MultiLine"] = 2048] = "MultiLine"; + NodeFlags[NodeFlags["Synthetic"] = 4096] = "Synthetic"; + NodeFlags[NodeFlags["DeclarationFile"] = 8192] = "DeclarationFile"; + NodeFlags[NodeFlags["Let"] = 16384] = "Let"; + NodeFlags[NodeFlags["Const"] = 32768] = "Const"; + NodeFlags[NodeFlags["OctalLiteral"] = 65536] = "OctalLiteral"; + NodeFlags[NodeFlags["Namespace"] = 131072] = "Namespace"; + NodeFlags[NodeFlags["ExportContext"] = 262144] = "ExportContext"; + NodeFlags[NodeFlags["ContainsThis"] = 524288] = "ContainsThis"; + NodeFlags[NodeFlags["Modifier"] = 2035] = "Modifier"; + NodeFlags[NodeFlags["AccessibilityModifier"] = 112] = "AccessibilityModifier"; + NodeFlags[NodeFlags["BlockScoped"] = 49152] = "BlockScoped"; + })(ts.NodeFlags || (ts.NodeFlags = {})); + var NodeFlags = ts.NodeFlags; + /* @internal */ + (function (ParserContextFlags) { + ParserContextFlags[ParserContextFlags["None"] = 0] = "None"; + // If this node was parsed in a context where 'in-expressions' are not allowed. + ParserContextFlags[ParserContextFlags["DisallowIn"] = 1] = "DisallowIn"; + // If this node was parsed in the 'yield' context created when parsing a generator. + ParserContextFlags[ParserContextFlags["Yield"] = 2] = "Yield"; + // If this node was parsed as part of a decorator + ParserContextFlags[ParserContextFlags["Decorator"] = 4] = "Decorator"; + // If this node was parsed in the 'await' context created when parsing an async function. + ParserContextFlags[ParserContextFlags["Await"] = 8] = "Await"; + // If the parser encountered an error when parsing the code that created this node. Note + // the parser only sets this directly on the node it creates right after encountering the + // error. + ParserContextFlags[ParserContextFlags["ThisNodeHasError"] = 16] = "ThisNodeHasError"; + // This node was parsed in a JavaScript file and can be processed differently. For example + // its type can be specified usign a JSDoc comment. + ParserContextFlags[ParserContextFlags["JavaScriptFile"] = 32] = "JavaScriptFile"; + // Context flags set directly by the parser. + ParserContextFlags[ParserContextFlags["ParserGeneratedFlags"] = 31] = "ParserGeneratedFlags"; + // Exclude these flags when parsing a Type + ParserContextFlags[ParserContextFlags["TypeExcludesFlags"] = 10] = "TypeExcludesFlags"; + // Context flags computed by aggregating child flags upwards. + // Used during incremental parsing to determine if this node or any of its children had an + // error. Computed only once and then cached. + ParserContextFlags[ParserContextFlags["ThisNodeOrAnySubNodesHasError"] = 64] = "ThisNodeOrAnySubNodesHasError"; + // Used to know if we've computed data from children and cached it in this node. + ParserContextFlags[ParserContextFlags["HasAggregatedChildData"] = 128] = "HasAggregatedChildData"; + })(ts.ParserContextFlags || (ts.ParserContextFlags = {})); + var ParserContextFlags = ts.ParserContextFlags; + (function (JsxFlags) { + JsxFlags[JsxFlags["None"] = 0] = "None"; + JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; + JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; + JsxFlags[JsxFlags["ClassElement"] = 4] = "ClassElement"; + JsxFlags[JsxFlags["UnknownElement"] = 8] = "UnknownElement"; + JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; + })(ts.JsxFlags || (ts.JsxFlags = {})); + var JsxFlags = ts.JsxFlags; + /* @internal */ + (function (RelationComparisonResult) { + RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded"; + RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; + RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; + })(ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); + var RelationComparisonResult = ts.RelationComparisonResult; + var OperationCanceledException = (function () { + function OperationCanceledException() { + } + return OperationCanceledException; + })(); + ts.OperationCanceledException = OperationCanceledException; + /** Return code used by getEmitOutput function to indicate status of the function */ + (function (ExitStatus) { + // Compiler ran successfully. Either this was a simple do-nothing compilation (for example, + // when -version or -help was provided, or this was a normal compilation, no diagnostics + // were produced, and all outputs were generated successfully. + ExitStatus[ExitStatus["Success"] = 0] = "Success"; + // Diagnostics were produced and because of them no code was generated. + ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; + // Diagnostics were produced and outputs were generated in spite of them. + ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; + })(ts.ExitStatus || (ts.ExitStatus = {})); + var ExitStatus = ts.ExitStatus; + (function (TypeFormatFlags) { + TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 1] = "WriteArrayAsGenericType"; + TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 2] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 4] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 8] = "WriteArrowStyleSignature"; + TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 16] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 64] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 128] = "UseFullyQualifiedType"; + })(ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); + var TypeFormatFlags = ts.TypeFormatFlags; + (function (SymbolFormatFlags) { + SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; + // Write symbols's type argument if it is instantiated symbol + // eg. class C { p: T } <-- Show p as C.p here + // var a: C; + // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p + SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; + // Use only external alias information to get the symbol name in the given context + // eg. module m { export class c { } } import x = m.c; + // When this flag is specified m.c will be used to refer to the class instead of alias symbol x + SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; + })(ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); + var SymbolFormatFlags = ts.SymbolFormatFlags; + /* @internal */ + (function (SymbolAccessibility) { + SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible"; + SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible"; + SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; + })(ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); + var SymbolAccessibility = ts.SymbolAccessibility; + /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator + * metadata */ + /* @internal */ + (function (TypeReferenceSerializationKind) { + TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; + // should be emitted using a safe fallback. + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue"; + // function that can be reached at runtime (e.g. a `class` + // declaration or a `var` declaration for the static side + // of a type, such as the global `Promise` type in lib.d.ts). + TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidType"] = 2] = "VoidType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 4] = "StringLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 5] = "BooleanType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 6] = "ArrayLikeType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 7] = "ESSymbolType"; + TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 8] = "TypeWithCallSignature"; + // with call signatures. + TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 9] = "ObjectType"; + })(ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {})); + var TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind; + (function (SymbolFlags) { + SymbolFlags[SymbolFlags["None"] = 0] = "None"; + SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; + SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable"; + SymbolFlags[SymbolFlags["Property"] = 4] = "Property"; + SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember"; + SymbolFlags[SymbolFlags["Function"] = 16] = "Function"; + SymbolFlags[SymbolFlags["Class"] = 32] = "Class"; + SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface"; + SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum"; + SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum"; + SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule"; + SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule"; + SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral"; + SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral"; + SymbolFlags[SymbolFlags["Method"] = 8192] = "Method"; + SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor"; + SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor"; + SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor"; + SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature"; + SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter"; + SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias"; + SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue"; + SymbolFlags[SymbolFlags["ExportType"] = 2097152] = "ExportType"; + SymbolFlags[SymbolFlags["ExportNamespace"] = 4194304] = "ExportNamespace"; + SymbolFlags[SymbolFlags["Alias"] = 8388608] = "Alias"; + SymbolFlags[SymbolFlags["Instantiated"] = 16777216] = "Instantiated"; + SymbolFlags[SymbolFlags["Merged"] = 33554432] = "Merged"; + SymbolFlags[SymbolFlags["Transient"] = 67108864] = "Transient"; + SymbolFlags[SymbolFlags["Prototype"] = 134217728] = "Prototype"; + SymbolFlags[SymbolFlags["SyntheticProperty"] = 268435456] = "SyntheticProperty"; + SymbolFlags[SymbolFlags["Optional"] = 536870912] = "Optional"; + SymbolFlags[SymbolFlags["ExportStar"] = 1073741824] = "ExportStar"; + SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; + SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; + SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 793056] = "Type"; + SymbolFlags[SymbolFlags["Namespace"] = 1536] = "Namespace"; + SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; + SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; + // Variables can be redeclared, but can not redeclare a block-scoped declaration with the + // same name, or any other value that is not a variable, e.g. ValueModule or Class + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 107454] = "FunctionScopedVariableExcludes"; + // Block-scoped declarations are not allowed to be re-declared + // they can not merge with anything in the value space + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 107455] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 107455] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["PropertyExcludes"] = 107455] = "PropertyExcludes"; + SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 107455] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 106927] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["ClassExcludes"] = 899519] = "ClassExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 792960] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes"; + SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 106639] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 99263] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 41919] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 74687] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530912] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793056] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["AliasExcludes"] = 8388608] = "AliasExcludes"; + SymbolFlags[SymbolFlags["ModuleMember"] = 8914931] = "ModuleMember"; + SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; + SymbolFlags[SymbolFlags["HasExports"] = 1952] = "HasExports"; + SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers"; + SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; + SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; + SymbolFlags[SymbolFlags["Export"] = 7340032] = "Export"; + /* @internal */ + // The set of things we consider semantically classifiable. Used to speed up the LS during + // classification. + SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; + })(ts.SymbolFlags || (ts.SymbolFlags = {})); + var SymbolFlags = ts.SymbolFlags; + /* @internal */ + (function (NodeCheckFlags) { + NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; + NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; + NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis"; + NodeCheckFlags[NodeCheckFlags["EmitExtends"] = 8] = "EmitExtends"; + NodeCheckFlags[NodeCheckFlags["EmitDecorate"] = 16] = "EmitDecorate"; + NodeCheckFlags[NodeCheckFlags["EmitParam"] = 32] = "EmitParam"; + NodeCheckFlags[NodeCheckFlags["EmitAwaiter"] = 64] = "EmitAwaiter"; + NodeCheckFlags[NodeCheckFlags["EmitGenerator"] = 128] = "EmitGenerator"; + NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; + NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; + NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; + NodeCheckFlags[NodeCheckFlags["LexicalArguments"] = 2048] = "LexicalArguments"; + NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 4096] = "CaptureArguments"; + // Values for enum members have been computed, and any errors have been reported for them. + NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 8192] = "EnumValuesComputed"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 16384] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; + })(ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); + var NodeCheckFlags = ts.NodeCheckFlags; + (function (TypeFlags) { + TypeFlags[TypeFlags["Any"] = 1] = "Any"; + TypeFlags[TypeFlags["String"] = 2] = "String"; + TypeFlags[TypeFlags["Number"] = 4] = "Number"; + TypeFlags[TypeFlags["Boolean"] = 8] = "Boolean"; + TypeFlags[TypeFlags["Void"] = 16] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 32] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 64] = "Null"; + TypeFlags[TypeFlags["Enum"] = 128] = "Enum"; + TypeFlags[TypeFlags["StringLiteral"] = 256] = "StringLiteral"; + TypeFlags[TypeFlags["TypeParameter"] = 512] = "TypeParameter"; + TypeFlags[TypeFlags["Class"] = 1024] = "Class"; + TypeFlags[TypeFlags["Interface"] = 2048] = "Interface"; + TypeFlags[TypeFlags["Reference"] = 4096] = "Reference"; + TypeFlags[TypeFlags["Tuple"] = 8192] = "Tuple"; + TypeFlags[TypeFlags["Union"] = 16384] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 32768] = "Intersection"; + TypeFlags[TypeFlags["Anonymous"] = 65536] = "Anonymous"; + TypeFlags[TypeFlags["Instantiated"] = 131072] = "Instantiated"; + /* @internal */ + TypeFlags[TypeFlags["FromSignature"] = 262144] = "FromSignature"; + TypeFlags[TypeFlags["ObjectLiteral"] = 524288] = "ObjectLiteral"; + /* @internal */ + TypeFlags[TypeFlags["FreshObjectLiteral"] = 1048576] = "FreshObjectLiteral"; + /* @internal */ + TypeFlags[TypeFlags["ContainsUndefinedOrNull"] = 2097152] = "ContainsUndefinedOrNull"; + /* @internal */ + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 4194304] = "ContainsObjectLiteral"; + /* @internal */ + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; + TypeFlags[TypeFlags["ESSymbol"] = 16777216] = "ESSymbol"; + TypeFlags[TypeFlags["ThisType"] = 33554432] = "ThisType"; + /* @internal */ + TypeFlags[TypeFlags["Intrinsic"] = 16777343] = "Intrinsic"; + /* @internal */ + TypeFlags[TypeFlags["Primitive"] = 16777726] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 258] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 132] = "NumberLike"; + TypeFlags[TypeFlags["ObjectType"] = 80896] = "ObjectType"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 49152] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 130048] = "StructuredType"; + /* @internal */ + TypeFlags[TypeFlags["RequiresWidening"] = 6291456] = "RequiresWidening"; + /* @internal */ + TypeFlags[TypeFlags["PropagatingFlags"] = 14680064] = "PropagatingFlags"; + })(ts.TypeFlags || (ts.TypeFlags = {})); + var TypeFlags = ts.TypeFlags; + (function (SignatureKind) { + SignatureKind[SignatureKind["Call"] = 0] = "Call"; + SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; + })(ts.SignatureKind || (ts.SignatureKind = {})); + var SignatureKind = ts.SignatureKind; + (function (IndexKind) { + IndexKind[IndexKind["String"] = 0] = "String"; + IndexKind[IndexKind["Number"] = 1] = "Number"; + })(ts.IndexKind || (ts.IndexKind = {})); + var IndexKind = ts.IndexKind; + (function (DiagnosticCategory) { + DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; + DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; + DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; + })(ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); + var DiagnosticCategory = ts.DiagnosticCategory; + (function (ModuleResolutionKind) { + ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic"; + ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs"; + })(ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {})); + var ModuleResolutionKind = ts.ModuleResolutionKind; + (function (ModuleKind) { + ModuleKind[ModuleKind["None"] = 0] = "None"; + ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS"; + ModuleKind[ModuleKind["AMD"] = 2] = "AMD"; + ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; + ModuleKind[ModuleKind["System"] = 4] = "System"; + ModuleKind[ModuleKind["ES6"] = 5] = "ES6"; + ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; + })(ts.ModuleKind || (ts.ModuleKind = {})); + var ModuleKind = ts.ModuleKind; + (function (JsxEmit) { + JsxEmit[JsxEmit["None"] = 0] = "None"; + JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve"; + JsxEmit[JsxEmit["React"] = 2] = "React"; + })(ts.JsxEmit || (ts.JsxEmit = {})); + var JsxEmit = ts.JsxEmit; + (function (NewLineKind) { + NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; + NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; + })(ts.NewLineKind || (ts.NewLineKind = {})); + var NewLineKind = ts.NewLineKind; + (function (ScriptTarget) { + ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; + ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; + ScriptTarget[ScriptTarget["ES6"] = 2] = "ES6"; + ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015"; + ScriptTarget[ScriptTarget["Latest"] = 2] = "Latest"; + })(ts.ScriptTarget || (ts.ScriptTarget = {})); + var ScriptTarget = ts.ScriptTarget; + (function (LanguageVariant) { + LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard"; + LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX"; + })(ts.LanguageVariant || (ts.LanguageVariant = {})); + var LanguageVariant = ts.LanguageVariant; + /* @internal */ + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; + CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator"; + CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator"; + CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine"; + // Unicode 3.0 space characters + CharacterCodes[CharacterCodes["space"] = 32] = "space"; + CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace"; + CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad"; + CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad"; + CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace"; + CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace"; + CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace"; + CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace"; + CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace"; + CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace"; + CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace"; + CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace"; + CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace"; + CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace"; + CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace"; + CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace"; + CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace"; + CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham"; + CharacterCodes[CharacterCodes["_"] = 95] = "_"; + CharacterCodes[CharacterCodes["$"] = 36] = "$"; + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; + CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; + CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; + CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; + CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; + CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["j"] = 106] = "j"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["B"] = 66] = "B"; + CharacterCodes[CharacterCodes["C"] = 67] = "C"; + CharacterCodes[CharacterCodes["D"] = 68] = "D"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["G"] = 71] = "G"; + CharacterCodes[CharacterCodes["H"] = 72] = "H"; + CharacterCodes[CharacterCodes["I"] = 73] = "I"; + CharacterCodes[CharacterCodes["J"] = 74] = "J"; + CharacterCodes[CharacterCodes["K"] = 75] = "K"; + CharacterCodes[CharacterCodes["L"] = 76] = "L"; + CharacterCodes[CharacterCodes["M"] = 77] = "M"; + CharacterCodes[CharacterCodes["N"] = 78] = "N"; + CharacterCodes[CharacterCodes["O"] = 79] = "O"; + CharacterCodes[CharacterCodes["P"] = 80] = "P"; + CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; + CharacterCodes[CharacterCodes["R"] = 82] = "R"; + CharacterCodes[CharacterCodes["S"] = 83] = "S"; + CharacterCodes[CharacterCodes["T"] = 84] = "T"; + CharacterCodes[CharacterCodes["U"] = 85] = "U"; + CharacterCodes[CharacterCodes["V"] = 86] = "V"; + CharacterCodes[CharacterCodes["W"] = 87] = "W"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["at"] = 64] = "at"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick"; + CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; + CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; + CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; + CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; + CharacterCodes[CharacterCodes["hash"] = 35] = "hash"; + CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; + CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["question"] = 63] = "question"; + CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; + CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; + CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; + CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; + })(ts.CharacterCodes || (ts.CharacterCodes = {})); + var CharacterCodes = ts.CharacterCodes; +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + /** + * Ternary values are defined such that + * x & y is False if either x or y is False. + * x & y is Maybe if either x or y is Maybe, but neither x or y is False. + * x & y is True if both x and y are True. + * x | y is False if both x and y are False. + * x | y is Maybe if either x or y is Maybe, but neither x or y is True. + * x | y is True if either x or y is True. + */ + (function (Ternary) { + Ternary[Ternary["False"] = 0] = "False"; + Ternary[Ternary["Maybe"] = 1] = "Maybe"; + Ternary[Ternary["True"] = -1] = "True"; + })(ts.Ternary || (ts.Ternary = {})); + var Ternary = ts.Ternary; + function createFileMap(getCanonicalFileName) { + var files = {}; + return { + get: get, + set: set, + contains: contains, + remove: remove, + clear: clear, + forEachValue: forEachValueInMap + }; + function set(fileName, value) { + files[normalizeKey(fileName)] = value; + } + function get(fileName) { + return files[normalizeKey(fileName)]; + } + function contains(fileName) { + return hasProperty(files, normalizeKey(fileName)); + } + function remove(fileName) { + var key = normalizeKey(fileName); + delete files[key]; + } + function forEachValueInMap(f) { + forEachValue(files, f); + } + function normalizeKey(key) { + return getCanonicalFileName(normalizeSlashes(key)); + } + function clear() { + files = {}; + } + } + ts.createFileMap = createFileMap; + (function (Comparison) { + Comparison[Comparison["LessThan"] = -1] = "LessThan"; + Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; + Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; + })(ts.Comparison || (ts.Comparison = {})); + var Comparison = ts.Comparison; + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEach(array, callback) { + if (array) { + for (var i = 0, len = array.length; i < len; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + return undefined; + } + ts.forEach = forEach; + function contains(array, value) { + if (array) { + for (var _i = 0; _i < array.length; _i++) { + var v = array[_i]; + if (v === value) { + return true; + } + } + } + return false; + } + ts.contains = contains; + function indexOf(array, value) { + if (array) { + for (var i = 0, len = array.length; i < len; i++) { + if (array[i] === value) { + return i; + } + } + } + return -1; + } + ts.indexOf = indexOf; + function countWhere(array, predicate) { + var count = 0; + if (array) { + for (var _i = 0; _i < array.length; _i++) { + var v = array[_i]; + if (predicate(v)) { + count++; + } + } + } + return count; + } + ts.countWhere = countWhere; + function filter(array, f) { + var result; + if (array) { + result = []; + for (var _i = 0; _i < array.length; _i++) { + var item = array[_i]; + if (f(item)) { + result.push(item); + } + } + } + return result; + } + ts.filter = filter; + function map(array, f) { + var result; + if (array) { + result = []; + for (var _i = 0; _i < array.length; _i++) { + var v = array[_i]; + result.push(f(v)); + } + } + return result; + } + ts.map = map; + function concatenate(array1, array2) { + if (!array2 || !array2.length) + return array1; + if (!array1 || !array1.length) + return array2; + return array1.concat(array2); + } + ts.concatenate = concatenate; + function deduplicate(array) { + var result; + if (array) { + result = []; + for (var _i = 0; _i < array.length; _i++) { + var item = array[_i]; + if (!contains(result, item)) { + result.push(item); + } + } + } + return result; + } + ts.deduplicate = deduplicate; + function sum(array, prop) { + var result = 0; + for (var _i = 0; _i < array.length; _i++) { + var v = array[_i]; + result += v[prop]; + } + return result; + } + ts.sum = sum; + function addRange(to, from) { + if (to && from) { + for (var _i = 0; _i < from.length; _i++) { + var v = from[_i]; + to.push(v); + } + } + } + ts.addRange = addRange; + function rangeEquals(array1, array2, pos, end) { + while (pos < end) { + if (array1[pos] !== array2[pos]) { + return false; + } + pos++; + } + return true; + } + ts.rangeEquals = rangeEquals; + /** + * Returns the last element of an array if non-empty, undefined otherwise. + */ + function lastOrUndefined(array) { + if (array.length === 0) { + return undefined; + } + return array[array.length - 1]; + } + ts.lastOrUndefined = lastOrUndefined; + /** + * Performs a binary search, finding the index at which 'value' occurs in 'array'. + * If no such index is found, returns the 2's-complement of first index at which + * number[index] exceeds number. + * @param array A sorted array whose first element must be no larger than number + * @param number The value to be searched for in the array. + */ + function binarySearch(array, value) { + var low = 0; + var high = array.length - 1; + while (low <= high) { + var middle = low + ((high - low) >> 1); + var midValue = array[middle]; + if (midValue === value) { + return middle; + } + else if (midValue > value) { + high = middle - 1; + } + else { + low = middle + 1; + } + } + return ~low; + } + ts.binarySearch = binarySearch; + function reduceLeft(array, f, initial) { + if (array) { + var count = array.length; + if (count > 0) { + var pos = 0; + var result = arguments.length <= 2 ? array[pos++] : initial; + while (pos < count) { + result = f(result, array[pos++]); + } + return result; + } + } + return initial; + } + ts.reduceLeft = reduceLeft; + function reduceRight(array, f, initial) { + if (array) { + var pos = array.length - 1; + if (pos >= 0) { + var result = arguments.length <= 2 ? array[pos--] : initial; + while (pos >= 0) { + result = f(result, array[pos--]); + } + return result; + } + } + return initial; + } + ts.reduceRight = reduceRight; + var hasOwnProperty = Object.prototype.hasOwnProperty; + function hasProperty(map, key) { + return hasOwnProperty.call(map, key); + } + ts.hasProperty = hasProperty; + function getProperty(map, key) { + return hasOwnProperty.call(map, key) ? map[key] : undefined; + } + ts.getProperty = getProperty; + function isEmpty(map) { + for (var id in map) { + if (hasProperty(map, id)) { + return false; + } + } + return true; + } + ts.isEmpty = isEmpty; + function clone(object) { + var result = {}; + for (var id in object) { + result[id] = object[id]; + } + return result; + } + ts.clone = clone; + function extend(first, second) { + var result = {}; + for (var id in first) { + result[id] = first[id]; + } + for (var id in second) { + if (!hasProperty(result, id)) { + result[id] = second[id]; + } + } + return result; + } + ts.extend = extend; + function forEachValue(map, callback) { + var result; + for (var id in map) { + if (result = callback(map[id])) + break; + } + return result; + } + ts.forEachValue = forEachValue; + function forEachKey(map, callback) { + var result; + for (var id in map) { + if (result = callback(id)) + break; + } + return result; + } + ts.forEachKey = forEachKey; + function lookUp(map, key) { + return hasProperty(map, key) ? map[key] : undefined; + } + ts.lookUp = lookUp; + function copyMap(source, target) { + for (var p in source) { + target[p] = source[p]; + } + } + ts.copyMap = copyMap; + /** + * Creates a map from the elements of an array. + * + * @param array the array of input elements. + * @param makeKey a function that produces a key for a given element. + * + * This function makes no effort to avoid collisions; if any two elements produce + * the same key with the given 'makeKey' function, then the element with the higher + * index in the array will be the one associated with the produced key. + */ + function arrayToMap(array, makeKey) { + var result = {}; + forEach(array, function (value) { + result[makeKey(value)] = value; + }); + return result; + } + ts.arrayToMap = arrayToMap; + function memoize(callback) { + var value; + return function () { + if (callback) { + value = callback(); + callback = undefined; + } + return value; + }; + } + ts.memoize = memoize; + function formatStringFromArgs(text, args, baseIndex) { + baseIndex = baseIndex || 0; + return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); + } + ts.localizedDiagnosticMessages = undefined; + function getLocaleSpecificMessage(message) { + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message] + ? ts.localizedDiagnosticMessages[message] + : message; + } + ts.getLocaleSpecificMessage = getLocaleSpecificMessage; + function createFileDiagnostic(file, start, length, message) { + var end = start + length; + Debug.assert(start >= 0, "start must be non-negative, is " + start); + Debug.assert(length >= 0, "length must be non-negative, is " + length); + if (file) { + Debug.assert(start <= file.text.length, "start must be within the bounds of the file. " + start + " > " + file.text.length); + Debug.assert(end <= file.text.length, "end must be the bounds of the file. " + end + " > " + file.text.length); + } + var text = getLocaleSpecificMessage(message.key); + if (arguments.length > 4) { + text = formatStringFromArgs(text, arguments, 4); + } + return { + file: file, + start: start, + length: length, + messageText: text, + category: message.category, + code: message.code + }; + } + ts.createFileDiagnostic = createFileDiagnostic; + function createCompilerDiagnostic(message) { + var text = getLocaleSpecificMessage(message.key); + if (arguments.length > 1) { + text = formatStringFromArgs(text, arguments, 1); + } + return { + file: undefined, + start: undefined, + length: undefined, + messageText: text, + category: message.category, + code: message.code + }; + } + ts.createCompilerDiagnostic = createCompilerDiagnostic; + function chainDiagnosticMessages(details, message) { + var text = getLocaleSpecificMessage(message.key); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return { + messageText: text, + category: message.category, + code: message.code, + next: details + }; + } + ts.chainDiagnosticMessages = chainDiagnosticMessages; + function concatenateDiagnosticMessageChains(headChain, tailChain) { + var lastChain = headChain; + while (lastChain.next) { + lastChain = lastChain.next; + } + lastChain.next = tailChain; + return headChain; + } + ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains; + function compareValues(a, b) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + return a < b ? -1 /* LessThan */ : 1 /* GreaterThan */; + } + ts.compareValues = compareValues; + function getDiagnosticFileName(diagnostic) { + return diagnostic.file ? diagnostic.file.fileName : undefined; + } + function compareDiagnostics(d1, d2) { + return compareValues(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || + compareValues(d1.start, d2.start) || + compareValues(d1.length, d2.length) || + compareValues(d1.code, d2.code) || + compareMessageText(d1.messageText, d2.messageText) || + 0 /* EqualTo */; + } + ts.compareDiagnostics = compareDiagnostics; + function compareMessageText(text1, text2) { + while (text1 && text2) { + // We still have both chains. + var string1 = typeof text1 === "string" ? text1 : text1.messageText; + var string2 = typeof text2 === "string" ? text2 : text2.messageText; + var res = compareValues(string1, string2); + if (res) { + return res; + } + text1 = typeof text1 === "string" ? undefined : text1.next; + text2 = typeof text2 === "string" ? undefined : text2.next; + } + if (!text1 && !text2) { + // if the chains are done, then these messages are the same. + return 0 /* EqualTo */; + } + // We still have one chain remaining. The shorter chain should come first. + return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */; + } + function sortAndDeduplicateDiagnostics(diagnostics) { + return deduplicateSortedDiagnostics(diagnostics.sort(compareDiagnostics)); + } + ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; + function deduplicateSortedDiagnostics(diagnostics) { + if (diagnostics.length < 2) { + return diagnostics; + } + var newDiagnostics = [diagnostics[0]]; + var previousDiagnostic = diagnostics[0]; + for (var i = 1; i < diagnostics.length; i++) { + var currentDiagnostic = diagnostics[i]; + var isDupe = compareDiagnostics(currentDiagnostic, previousDiagnostic) === 0 /* EqualTo */; + if (!isDupe) { + newDiagnostics.push(currentDiagnostic); + previousDiagnostic = currentDiagnostic; + } + } + return newDiagnostics; + } + ts.deduplicateSortedDiagnostics = deduplicateSortedDiagnostics; + function normalizeSlashes(path) { + return path.replace(/\\/g, "/"); + } + ts.normalizeSlashes = normalizeSlashes; + // Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files") + function getRootLength(path) { + if (path.charCodeAt(0) === 47 /* slash */) { + if (path.charCodeAt(1) !== 47 /* slash */) + return 1; + var p1 = path.indexOf("/", 2); + if (p1 < 0) + return 2; + var p2 = path.indexOf("/", p1 + 1); + if (p2 < 0) + return p1 + 1; + return p2 + 1; + } + if (path.charCodeAt(1) === 58 /* colon */) { + if (path.charCodeAt(2) === 47 /* slash */) + return 3; + return 2; + } + // Per RFC 1738 'file' URI schema has the shape file:/// + // if is omitted then it is assumed that host value is 'localhost', + // however slash after the omitted is not removed. + // file:///folder1/file1 - this is a correct URI + // file://folder2/file2 - this is an incorrect URI + if (path.lastIndexOf("file:///", 0) === 0) { + return "file:///".length; + } + var idx = path.indexOf("://"); + if (idx !== -1) { + return idx + "://".length; + } + return 0; + } + ts.getRootLength = getRootLength; + ts.directorySeparator = "/"; + function getNormalizedParts(normalizedSlashedPath, rootLength) { + var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); + var normalized = []; + for (var _i = 0; _i < parts.length; _i++) { + var part = parts[_i]; + if (part !== ".") { + if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { + normalized.pop(); + } + else { + // A part may be an empty string (which is 'falsy') if the path had consecutive slashes, + // e.g. "path//file.ts". Drop these before re-joining the parts. + if (part) { + normalized.push(part); + } + } + } + } + return normalized; + } + function normalizePath(path) { + path = normalizeSlashes(path); + var rootLength = getRootLength(path); + var normalized = getNormalizedParts(path, rootLength); + return path.substr(0, rootLength) + normalized.join(ts.directorySeparator); + } + ts.normalizePath = normalizePath; + function getDirectoryPath(path) { + return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function isUrl(path) { + return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; + } + ts.isUrl = isUrl; + function isRootedDiskPath(path) { + return getRootLength(path) !== 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + function normalizedPathComponents(path, rootLength) { + var normalizedParts = getNormalizedParts(path, rootLength); + return [path.substr(0, rootLength)].concat(normalizedParts); + } + function getNormalizedPathComponents(path, currentDirectory) { + path = normalizeSlashes(path); + var rootLength = getRootLength(path); + if (rootLength === 0) { + // If the path is not rooted it is relative to current directory + path = combinePaths(normalizeSlashes(currentDirectory), path); + rootLength = getRootLength(path); + } + return normalizedPathComponents(path, rootLength); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getNormalizedPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + function getNormalizedPathFromPathComponents(pathComponents) { + if (pathComponents && pathComponents.length) { + return pathComponents[0] + pathComponents.slice(1).join(ts.directorySeparator); + } + } + ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents; + function getNormalizedPathComponentsOfUrl(url) { + // Get root length of http://www.website.com/folder1/foler2/ + // In this example the root is: http://www.website.com/ + // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] + var urlLength = url.length; + // Initial root length is http:// part + var rootLength = url.indexOf("://") + "://".length; + while (rootLength < urlLength) { + // Consume all immediate slashes in the protocol + // eg.initial rootlength is just file:// but it needs to consume another "/" in file:/// + if (url.charCodeAt(rootLength) === 47 /* slash */) { + rootLength++; + } + else { + // non slash character means we continue proceeding to next component of root search + break; + } + } + // there are no parts after http:// just return current string as the pathComponent + if (rootLength === urlLength) { + return [url]; + } + // Find the index of "/" after website.com so the root can be http://www.website.com/ (from existing http://) + var indexOfNextSlash = url.indexOf(ts.directorySeparator, rootLength); + if (indexOfNextSlash !== -1) { + // Found the "/" after the website.com so the root is length of http://www.website.com/ + // and get components afetr the root normally like any other folder components + rootLength = indexOfNextSlash + 1; + return normalizedPathComponents(url, rootLength); + } + else { + // Can't find the host assume the rest of the string as component + // but make sure we append "/" to it as root is not joined using "/" + // eg. if url passed in was http://website.com we want to use root as [http://website.com/] + // so that other path manipulations will be correct and it can be merged with relative paths correctly + return [url + ts.directorySeparator]; + } + } + function getNormalizedPathOrUrlComponents(pathOrUrl, currentDirectory) { + if (isUrl(pathOrUrl)) { + return getNormalizedPathComponentsOfUrl(pathOrUrl); + } + else { + return getNormalizedPathComponents(pathOrUrl, currentDirectory); + } + } + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); + var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); + if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { + // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name + // that is ["test", "cases", ""] needs to be actually ["test", "cases"] + directoryComponents.length--; + } + // Find the component that differs + for (var joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { + if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) { + break; + } + } + // Get the relative path + if (joinStartIndex) { + var relativePath = ""; + var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length); + for (; joinStartIndex < directoryComponents.length; joinStartIndex++) { + if (directoryComponents[joinStartIndex] !== "") { + relativePath = relativePath + ".." + ts.directorySeparator; + } + } + return relativePath + relativePathComponents.join(ts.directorySeparator); + } + // Cant find the relative path, get the absolute path + var absolutePath = getNormalizedPathFromPathComponents(pathComponents); + if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) { + absolutePath = "file:///" + absolutePath; + } + return absolutePath; + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + function getBaseFileName(path) { + if (!path) { + return undefined; + } + var i = path.lastIndexOf(ts.directorySeparator); + return i < 0 ? path : path.substring(i + 1); + } + ts.getBaseFileName = getBaseFileName; + function combinePaths(path1, path2) { + if (!(path1 && path1.length)) + return path2; + if (!(path2 && path2.length)) + return path1; + if (getRootLength(path2) !== 0) + return path2; + if (path1.charAt(path1.length - 1) === ts.directorySeparator) + return path1 + path2; + return path1 + ts.directorySeparator + path2; + } + ts.combinePaths = combinePaths; + function fileExtensionIs(path, extension) { + var pathLen = path.length; + var extLen = extension.length; + return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; + } + ts.fileExtensionIs = fileExtensionIs; + /** + * List of supported extensions in order of file resolution precedence. + */ + ts.supportedExtensions = [".ts", ".tsx", ".d.ts"]; + /** + * List of extensions that will be used to look for external modules. + * This list is kept separate from supportedExtensions to for cases when we'll allow to include .js files in compilation, + * but still would like to load only TypeScript files as modules + */ + ts.moduleFileExtensions = ts.supportedExtensions; + function isSupportedSourceFileName(fileName) { + if (!fileName) { + return false; + } + for (var _i = 0; _i < ts.supportedExtensions.length; _i++) { + var extension = ts.supportedExtensions[_i]; + if (fileExtensionIs(fileName, extension)) { + return true; + } + } + return false; + } + ts.isSupportedSourceFileName = isSupportedSourceFileName; + var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; + function removeFileExtension(path) { + for (var _i = 0; _i < extensionsToRemove.length; _i++) { + var ext = extensionsToRemove[_i]; + if (fileExtensionIs(path, ext)) { + return path.substr(0, path.length - ext.length); + } + } + return path; + } + ts.removeFileExtension = removeFileExtension; + var backslashOrDoubleQuote = /[\"\\]/g; + var escapedCharsRegExp = /[\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var escapedCharsMap = { + "\0": "\\0", + "\t": "\\t", + "\v": "\\v", + "\f": "\\f", + "\b": "\\b", + "\r": "\\r", + "\n": "\\n", + "\\": "\\\\", + "\"": "\\\"", + "\u2028": "\\u2028", + "\u2029": "\\u2029", + "\u0085": "\\u0085" // nextLine + }; + function Symbol(flags, name) { + this.flags = flags; + this.name = name; + this.declarations = undefined; + } + function Type(checker, flags) { + this.flags = flags; + } + function Signature(checker) { + } + ts.objectAllocator = { + getNodeConstructor: function (kind) { + function Node() { + } + Node.prototype = { + kind: kind, + pos: -1, + end: -1, + flags: 0, + parent: undefined + }; + return Node; + }, + getSymbolConstructor: function () { return Symbol; }, + getTypeConstructor: function () { return Type; }, + getSignatureConstructor: function () { return Signature; } + }; + (function (AssertionLevel) { + AssertionLevel[AssertionLevel["None"] = 0] = "None"; + AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; + AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; + AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; + })(ts.AssertionLevel || (ts.AssertionLevel = {})); + var AssertionLevel = ts.AssertionLevel; + var Debug; + (function (Debug) { + var currentAssertionLevel = 0 /* None */; + function shouldAssert(level) { + return currentAssertionLevel >= level; + } + Debug.shouldAssert = shouldAssert; + function assert(expression, message, verboseDebugInfo) { + if (!expression) { + var verboseDebugString = ""; + if (verboseDebugInfo) { + verboseDebugString = "\r\nVerbose Debug Information: " + verboseDebugInfo(); + } + throw new Error("Debug Failure. False expression: " + (message || "") + verboseDebugString); + } + } + Debug.assert = assert; + function fail(message) { + Debug.assert(false, message); + } + Debug.fail = fail; + })(Debug = ts.Debug || (ts.Debug = {})); + function copyListRemovingItem(item, list) { + var copiedList = []; + for (var i = 0, len = list.length; i < len; i++) { + if (list[i] !== item) { + copiedList.push(list[i]); + } + } + return copiedList; + } + ts.copyListRemovingItem = copyListRemovingItem; +})(ts || (ts = {})); +/// +var ts; +(function (ts) { + ts.sys = (function () { + function getWScriptSystem() { + var fso = new ActiveXObject("Scripting.FileSystemObject"); + var fileStream = new ActiveXObject("ADODB.Stream"); + fileStream.Type = 2 /*text*/; + var binaryStream = new ActiveXObject("ADODB.Stream"); + binaryStream.Type = 1 /*binary*/; + var args = []; + for (var i = 0; i < WScript.Arguments.length; i++) { + args[i] = WScript.Arguments.Item(i); + } + function readFile(fileName, encoding) { + if (!fso.FileExists(fileName)) { + return undefined; + } + fileStream.Open(); + try { + if (encoding) { + fileStream.Charset = encoding; + fileStream.LoadFromFile(fileName); + } + else { + // Load file and read the first two bytes into a string with no interpretation + fileStream.Charset = "x-ansi"; + fileStream.LoadFromFile(fileName); + var bom = fileStream.ReadText(2) || ""; + // Position must be at 0 before encoding can be changed + fileStream.Position = 0; + // [0xFF,0xFE] and [0xFE,0xFF] mean utf-16 (little or big endian), otherwise default to utf-8 + fileStream.Charset = bom.length >= 2 && (bom.charCodeAt(0) === 0xFF && bom.charCodeAt(1) === 0xFE || bom.charCodeAt(0) === 0xFE && bom.charCodeAt(1) === 0xFF) ? "unicode" : "utf-8"; + } + // ReadText method always strips byte order mark from resulting string + return fileStream.ReadText(); + } + catch (e) { + throw e; + } + finally { + fileStream.Close(); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + fileStream.Open(); + binaryStream.Open(); + try { + // Write characters in UTF-8 encoding + fileStream.Charset = "utf-8"; + fileStream.WriteText(data); + // If we don't want the BOM, then skip it by setting the starting location to 3 (size of BOM). + // If not, start from position 0, as the BOM will be added automatically when charset==utf8. + if (writeByteOrderMark) { + fileStream.Position = 0; + } + else { + fileStream.Position = 3; + } + fileStream.CopyTo(binaryStream); + binaryStream.SaveToFile(fileName, 2 /*overwrite*/); + } + finally { + binaryStream.Close(); + fileStream.Close(); + } + } + function getCanonicalPath(path) { + return path.toLowerCase(); + } + function getNames(collection) { + var result = []; + for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { + result.push(e.item().Name); + } + return result.sort(); + } + function readDirectory(path, extension, exclude) { + var result = []; + exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); + visitDirectory(path); + return result; + function visitDirectory(path) { + var folder = fso.GetFolder(path || "."); + var files = getNames(folder.files); + for (var _i = 0; _i < files.length; _i++) { + var current = files[_i]; + var name_1 = ts.combinePaths(path, current); + if ((!extension || ts.fileExtensionIs(name_1, extension)) && !ts.contains(exclude, getCanonicalPath(name_1))) { + result.push(name_1); + } + } + var subfolders = getNames(folder.subfolders); + for (var _a = 0; _a < subfolders.length; _a++) { + var current = subfolders[_a]; + var name_2 = ts.combinePaths(path, current); + if (!ts.contains(exclude, getCanonicalPath(name_2))) { + visitDirectory(name_2); + } + } + } + } + return { + args: args, + newLine: "\r\n", + useCaseSensitiveFileNames: false, + write: function (s) { + WScript.StdOut.Write(s); + }, + readFile: readFile, + writeFile: writeFile, + resolvePath: function (path) { + return fso.GetAbsolutePathName(path); + }, + fileExists: function (path) { + return fso.FileExists(path); + }, + directoryExists: function (path) { + return fso.FolderExists(path); + }, + createDirectory: function (directoryName) { + if (!this.directoryExists(directoryName)) { + fso.CreateFolder(directoryName); + } + }, + getExecutingFilePath: function () { + return WScript.ScriptFullName; + }, + getCurrentDirectory: function () { + return new ActiveXObject("WScript.Shell").CurrentDirectory; + }, + readDirectory: readDirectory, + exit: function (exitCode) { + try { + WScript.Quit(exitCode); + } + catch (e) { + } + } + }; + } + function getNodeSystem() { + var _fs = require("fs"); + var _path = require("path"); + var _os = require("os"); + // average async stat takes about 30 microseconds + // set chunk size to do 30 files in < 1 millisecond + function createWatchedFileSet(interval, chunkSize) { + if (interval === void 0) { interval = 2500; } + if (chunkSize === void 0) { chunkSize = 30; } + var watchedFiles = []; + var nextFileToCheck = 0; + var watchTimer; + function getModifiedTime(fileName) { + return _fs.statSync(fileName).mtime; + } + function poll(checkedIndex) { + var watchedFile = watchedFiles[checkedIndex]; + if (!watchedFile) { + return; + } + _fs.stat(watchedFile.fileName, function (err, stats) { + if (err) { + watchedFile.callback(watchedFile.fileName); + } + else if (watchedFile.mtime.getTime() !== stats.mtime.getTime()) { + watchedFile.mtime = getModifiedTime(watchedFile.fileName); + watchedFile.callback(watchedFile.fileName, watchedFile.mtime.getTime() === 0); + } + }); + } + // this implementation uses polling and + // stat due to inconsistencies of fs.watch + // and efficiency of stat on modern filesystems + function startWatchTimer() { + watchTimer = setInterval(function () { + var count = 0; + var nextToCheck = nextFileToCheck; + var firstCheck = -1; + while ((count < chunkSize) && (nextToCheck !== firstCheck)) { + poll(nextToCheck); + if (firstCheck < 0) { + firstCheck = nextToCheck; + } + nextToCheck++; + if (nextToCheck === watchedFiles.length) { + nextToCheck = 0; + } + count++; + } + nextFileToCheck = nextToCheck; + }, interval); + } + function addFile(fileName, callback) { + var file = { + fileName: fileName, + callback: callback, + mtime: getModifiedTime(fileName) + }; + watchedFiles.push(file); + if (watchedFiles.length === 1) { + startWatchTimer(); + } + return file; + } + function removeFile(file) { + watchedFiles = ts.copyListRemovingItem(file, watchedFiles); + } + return { + getModifiedTime: getModifiedTime, + poll: poll, + startWatchTimer: startWatchTimer, + addFile: addFile, + removeFile: removeFile + }; + } + // REVIEW: for now this implementation uses polling. + // The advantage of polling is that it works reliably + // on all os and with network mounted files. + // For 90 referenced files, the average time to detect + // changes is 2*msInterval (by default 5 seconds). + // The overhead of this is .04 percent (1/2500) with + // average pause of < 1 millisecond (and max + // pause less than 1.5 milliseconds); question is + // do we anticipate reference sets in the 100s and + // do we care about waiting 10-20 seconds to detect + // changes for large reference sets? If so, do we want + // to increase the chunk size or decrease the interval + // time dynamically to match the large reference set? + var watchedFileSet = createWatchedFileSet(); + function isNode4OrLater() { + return parseInt(process.version.charAt(1)) >= 4; + } + var platform = _os.platform(); + // win32\win64 are case insensitive platforms, MacOS (darwin) by default is also case insensitive + var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; + function readFile(fileName, encoding) { + if (!_fs.existsSync(fileName)) { + return undefined; + } + var buffer = _fs.readFileSync(fileName); + var len = buffer.length; + if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { + // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js, + // flip all byte pairs and treat as little endian. + len &= ~1; + for (var i = 0; i < len; i += 2) { + var temp = buffer[i]; + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + } + return buffer.toString("utf16le", 2); + } + if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) { + // Little endian UTF-16 byte order mark detected + return buffer.toString("utf16le", 2); + } + if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + // UTF-8 byte order mark detected + return buffer.toString("utf8", 3); + } + // Default is UTF-8 with no byte order mark + return buffer.toString("utf8"); + } + function writeFile(fileName, data, writeByteOrderMark) { + // If a BOM is required, emit one + if (writeByteOrderMark) { + data = "\uFEFF" + data; + } + _fs.writeFileSync(fileName, data, "utf8"); + } + function getCanonicalPath(path) { + return useCaseSensitiveFileNames ? path.toLowerCase() : path; + } + function readDirectory(path, extension, exclude) { + var result = []; + exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); + visitDirectory(path); + return result; + function visitDirectory(path) { + var files = _fs.readdirSync(path || ".").sort(); + var directories = []; + for (var _i = 0; _i < files.length; _i++) { + var current = files[_i]; + var name_3 = ts.combinePaths(path, current); + if (!ts.contains(exclude, getCanonicalPath(name_3))) { + var stat = _fs.statSync(name_3); + if (stat.isFile()) { + if (!extension || ts.fileExtensionIs(name_3, extension)) { + result.push(name_3); + } + } + else if (stat.isDirectory()) { + directories.push(name_3); + } + } + } + for (var _a = 0; _a < directories.length; _a++) { + var current = directories[_a]; + visitDirectory(current); + } + } + } + return { + args: process.argv.slice(2), + newLine: _os.EOL, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + write: function (s) { + var buffer = new Buffer(s, "utf8"); + var offset = 0; + var toWrite = buffer.length; + var written = 0; + // 1 is a standard descriptor for stdout + while ((written = _fs.writeSync(1, buffer, offset, toWrite)) < toWrite) { + offset += written; + toWrite -= written; + } + }, + readFile: readFile, + writeFile: writeFile, + watchFile: function (fileName, callback) { + // Node 4.0 stablized the `fs.watch` function on Windows which avoids polling + // and is more efficient than `fs.watchFile` (ref: https://github.com/nodejs/node/pull/2649 + // and https://github.com/Microsoft/TypeScript/issues/4643), therefore + // if the current node.js version is newer than 4, use `fs.watch` instead. + var watchedFile = watchedFileSet.addFile(fileName, callback); + return { + close: function () { return watchedFileSet.removeFile(watchedFile); } + }; + }, + watchDirectory: function (path, callback, recursive) { + // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) + return _fs.watch(path, { persisten: true, recursive: !!recursive }, function (eventName, relativeFileName) { + // In watchDirectory we only care about adding and removing files (when event name is + // "rename"); changes made within files are handled by corresponding fileWatchers (when + // event name is "change") + if (eventName === "rename") { + // When deleting a file, the passed baseFileName is null + callback(!relativeFileName ? relativeFileName : ts.normalizePath(ts.combinePaths(path, relativeFileName))); + } + ; + }); + }, + resolvePath: function (path) { + return _path.resolve(path); + }, + fileExists: function (path) { + return _fs.existsSync(path); + }, + directoryExists: function (path) { + return _fs.existsSync(path) && _fs.statSync(path).isDirectory(); + }, + createDirectory: function (directoryName) { + if (!this.directoryExists(directoryName)) { + _fs.mkdirSync(directoryName); + } + }, + getExecutingFilePath: function () { + return __filename; + }, + getCurrentDirectory: function () { + return process.cwd(); + }, + readDirectory: readDirectory, + getMemoryUsage: function () { + if (global.gc) { + global.gc(); + } + return process.memoryUsage().heapUsed; + }, + exit: function (exitCode) { + process.exit(exitCode); + } + }; + } + if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { + return getWScriptSystem(); + } + else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { + // process and process.nextTick checks if current environment is node-like + // process.browser check excludes webpack and browserify + return getNodeSystem(); + } + else { + return undefined; // Unsupported host + } + })(); +})(ts || (ts = {})); +// +/// +/* @internal */ +var ts; +(function (ts) { + ts.Diagnostics = { + Unterminated_string_literal: { code: 1002, category: ts.DiagnosticCategory.Error, key: "Unterminated string literal." }, + Identifier_expected: { code: 1003, category: ts.DiagnosticCategory.Error, key: "Identifier expected." }, + _0_expected: { code: 1005, category: ts.DiagnosticCategory.Error, key: "'{0}' expected." }, + A_file_cannot_have_a_reference_to_itself: { code: 1006, category: ts.DiagnosticCategory.Error, key: "A file cannot have a reference to itself." }, + Trailing_comma_not_allowed: { code: 1009, category: ts.DiagnosticCategory.Error, key: "Trailing comma not allowed." }, + Asterisk_Slash_expected: { code: 1010, category: ts.DiagnosticCategory.Error, key: "'*/' expected." }, + Unexpected_token: { code: 1012, category: ts.DiagnosticCategory.Error, key: "Unexpected token." }, + A_rest_parameter_must_be_last_in_a_parameter_list: { code: 1014, category: ts.DiagnosticCategory.Error, key: "A rest parameter must be last in a parameter list." }, + Parameter_cannot_have_question_mark_and_initializer: { code: 1015, category: ts.DiagnosticCategory.Error, key: "Parameter cannot have question mark and initializer." }, + A_required_parameter_cannot_follow_an_optional_parameter: { code: 1016, category: ts.DiagnosticCategory.Error, key: "A required parameter cannot follow an optional parameter." }, + An_index_signature_cannot_have_a_rest_parameter: { code: 1017, category: ts.DiagnosticCategory.Error, key: "An index signature cannot have a rest parameter." }, + An_index_signature_parameter_cannot_have_an_accessibility_modifier: { code: 1018, category: ts.DiagnosticCategory.Error, key: "An index signature parameter cannot have an accessibility modifier." }, + An_index_signature_parameter_cannot_have_a_question_mark: { code: 1019, category: ts.DiagnosticCategory.Error, key: "An index signature parameter cannot have a question mark." }, + An_index_signature_parameter_cannot_have_an_initializer: { code: 1020, category: ts.DiagnosticCategory.Error, key: "An index signature parameter cannot have an initializer." }, + An_index_signature_must_have_a_type_annotation: { code: 1021, category: ts.DiagnosticCategory.Error, key: "An index signature must have a type annotation." }, + An_index_signature_parameter_must_have_a_type_annotation: { code: 1022, category: ts.DiagnosticCategory.Error, key: "An index signature parameter must have a type annotation." }, + An_index_signature_parameter_type_must_be_string_or_number: { code: 1023, category: ts.DiagnosticCategory.Error, key: "An index signature parameter type must be 'string' or 'number'." }, + Accessibility_modifier_already_seen: { code: 1028, category: ts.DiagnosticCategory.Error, key: "Accessibility modifier already seen." }, + _0_modifier_must_precede_1_modifier: { code: 1029, category: ts.DiagnosticCategory.Error, key: "'{0}' modifier must precede '{1}' modifier." }, + _0_modifier_already_seen: { code: 1030, category: ts.DiagnosticCategory.Error, key: "'{0}' modifier already seen." }, + _0_modifier_cannot_appear_on_a_class_element: { code: 1031, category: ts.DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a class element." }, + super_must_be_followed_by_an_argument_list_or_member_access: { code: 1034, category: ts.DiagnosticCategory.Error, key: "'super' must be followed by an argument list or member access." }, + Only_ambient_modules_can_use_quoted_names: { code: 1035, category: ts.DiagnosticCategory.Error, key: "Only ambient modules can use quoted names." }, + Statements_are_not_allowed_in_ambient_contexts: { code: 1036, category: ts.DiagnosticCategory.Error, key: "Statements are not allowed in ambient contexts." }, + A_declare_modifier_cannot_be_used_in_an_already_ambient_context: { code: 1038, category: ts.DiagnosticCategory.Error, key: "A 'declare' modifier cannot be used in an already ambient context." }, + Initializers_are_not_allowed_in_ambient_contexts: { code: 1039, category: ts.DiagnosticCategory.Error, key: "Initializers are not allowed in ambient contexts." }, + _0_modifier_cannot_be_used_in_an_ambient_context: { code: 1040, category: ts.DiagnosticCategory.Error, key: "'{0}' modifier cannot be used in an ambient context." }, + _0_modifier_cannot_be_used_with_a_class_declaration: { code: 1041, category: ts.DiagnosticCategory.Error, key: "'{0}' modifier cannot be used with a class declaration." }, + _0_modifier_cannot_be_used_here: { code: 1042, category: ts.DiagnosticCategory.Error, key: "'{0}' modifier cannot be used here." }, + _0_modifier_cannot_appear_on_a_data_property: { code: 1043, category: ts.DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a data property." }, + _0_modifier_cannot_appear_on_a_module_element: { code: 1044, category: ts.DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a module element." }, + A_0_modifier_cannot_be_used_with_an_interface_declaration: { code: 1045, category: ts.DiagnosticCategory.Error, key: "A '{0}' modifier cannot be used with an interface declaration." }, + A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: { code: 1046, category: ts.DiagnosticCategory.Error, key: "A 'declare' modifier is required for a top level declaration in a .d.ts file." }, + A_rest_parameter_cannot_be_optional: { code: 1047, category: ts.DiagnosticCategory.Error, key: "A rest parameter cannot be optional." }, + A_rest_parameter_cannot_have_an_initializer: { code: 1048, category: ts.DiagnosticCategory.Error, key: "A rest parameter cannot have an initializer." }, + A_set_accessor_must_have_exactly_one_parameter: { code: 1049, category: ts.DiagnosticCategory.Error, key: "A 'set' accessor must have exactly one parameter." }, + A_set_accessor_cannot_have_an_optional_parameter: { code: 1051, category: ts.DiagnosticCategory.Error, key: "A 'set' accessor cannot have an optional parameter." }, + A_set_accessor_parameter_cannot_have_an_initializer: { code: 1052, category: ts.DiagnosticCategory.Error, key: "A 'set' accessor parameter cannot have an initializer." }, + A_set_accessor_cannot_have_rest_parameter: { code: 1053, category: ts.DiagnosticCategory.Error, key: "A 'set' accessor cannot have rest parameter." }, + A_get_accessor_cannot_have_parameters: { code: 1054, category: ts.DiagnosticCategory.Error, key: "A 'get' accessor cannot have parameters." }, + Type_0_is_not_a_valid_async_function_return_type: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type '{0}' is not a valid async function return type." }, + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: ts.DiagnosticCategory.Error, key: "Accessors are only available when targeting ECMAScript 5 and higher." }, + An_async_function_or_method_must_have_a_valid_awaitable_return_type: { code: 1057, category: ts.DiagnosticCategory.Error, key: "An async function or method must have a valid awaitable return type." }, + Operand_for_await_does_not_have_a_valid_callable_then_member: { code: 1058, category: ts.DiagnosticCategory.Error, key: "Operand for 'await' does not have a valid callable 'then' member." }, + Return_expression_in_async_function_does_not_have_a_valid_callable_then_member: { code: 1059, category: ts.DiagnosticCategory.Error, key: "Return expression in async function does not have a valid callable 'then' member." }, + Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member: { code: 1060, category: ts.DiagnosticCategory.Error, key: "Expression body for async arrow function does not have a valid callable 'then' member." }, + Enum_member_must_have_initializer: { code: 1061, category: ts.DiagnosticCategory.Error, key: "Enum member must have initializer." }, + _0_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: { code: 1062, category: ts.DiagnosticCategory.Error, key: "{0} is referenced directly or indirectly in the fulfillment callback of its own 'then' method." }, + An_export_assignment_cannot_be_used_in_a_namespace: { code: 1063, category: ts.DiagnosticCategory.Error, key: "An export assignment cannot be used in a namespace." }, + In_ambient_enum_declarations_member_initializer_must_be_constant_expression: { code: 1066, category: ts.DiagnosticCategory.Error, key: "In ambient enum declarations member initializer must be constant expression." }, + Unexpected_token_A_constructor_method_accessor_or_property_was_expected: { code: 1068, category: ts.DiagnosticCategory.Error, key: "Unexpected token. A constructor, method, accessor, or property was expected." }, + A_0_modifier_cannot_be_used_with_an_import_declaration: { code: 1079, category: ts.DiagnosticCategory.Error, key: "A '{0}' modifier cannot be used with an import declaration." }, + Invalid_reference_directive_syntax: { code: 1084, category: ts.DiagnosticCategory.Error, key: "Invalid 'reference' directive syntax." }, + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: { code: 1085, category: ts.DiagnosticCategory.Error, key: "Octal literals are not available when targeting ECMAScript 5 and higher." }, + An_accessor_cannot_be_declared_in_an_ambient_context: { code: 1086, category: ts.DiagnosticCategory.Error, key: "An accessor cannot be declared in an ambient context." }, + _0_modifier_cannot_appear_on_a_constructor_declaration: { code: 1089, category: ts.DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a constructor declaration." }, + _0_modifier_cannot_appear_on_a_parameter: { code: 1090, category: ts.DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a parameter." }, + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: { code: 1091, category: ts.DiagnosticCategory.Error, key: "Only a single variable declaration is allowed in a 'for...in' statement." }, + Type_parameters_cannot_appear_on_a_constructor_declaration: { code: 1092, category: ts.DiagnosticCategory.Error, key: "Type parameters cannot appear on a constructor declaration." }, + Type_annotation_cannot_appear_on_a_constructor_declaration: { code: 1093, category: ts.DiagnosticCategory.Error, key: "Type annotation cannot appear on a constructor declaration." }, + An_accessor_cannot_have_type_parameters: { code: 1094, category: ts.DiagnosticCategory.Error, key: "An accessor cannot have type parameters." }, + A_set_accessor_cannot_have_a_return_type_annotation: { code: 1095, category: ts.DiagnosticCategory.Error, key: "A 'set' accessor cannot have a return type annotation." }, + An_index_signature_must_have_exactly_one_parameter: { code: 1096, category: ts.DiagnosticCategory.Error, key: "An index signature must have exactly one parameter." }, + _0_list_cannot_be_empty: { code: 1097, category: ts.DiagnosticCategory.Error, key: "'{0}' list cannot be empty." }, + Type_parameter_list_cannot_be_empty: { code: 1098, category: ts.DiagnosticCategory.Error, key: "Type parameter list cannot be empty." }, + Type_argument_list_cannot_be_empty: { code: 1099, category: ts.DiagnosticCategory.Error, key: "Type argument list cannot be empty." }, + Invalid_use_of_0_in_strict_mode: { code: 1100, category: ts.DiagnosticCategory.Error, key: "Invalid use of '{0}' in strict mode." }, + with_statements_are_not_allowed_in_strict_mode: { code: 1101, category: ts.DiagnosticCategory.Error, key: "'with' statements are not allowed in strict mode." }, + delete_cannot_be_called_on_an_identifier_in_strict_mode: { code: 1102, category: ts.DiagnosticCategory.Error, key: "'delete' cannot be called on an identifier in strict mode." }, + A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: { code: 1104, category: ts.DiagnosticCategory.Error, key: "A 'continue' statement can only be used within an enclosing iteration statement." }, + A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: { code: 1105, category: ts.DiagnosticCategory.Error, key: "A 'break' statement can only be used within an enclosing iteration or switch statement." }, + Jump_target_cannot_cross_function_boundary: { code: 1107, category: ts.DiagnosticCategory.Error, key: "Jump target cannot cross function boundary." }, + A_return_statement_can_only_be_used_within_a_function_body: { code: 1108, category: ts.DiagnosticCategory.Error, key: "A 'return' statement can only be used within a function body." }, + Expression_expected: { code: 1109, category: ts.DiagnosticCategory.Error, key: "Expression expected." }, + Type_expected: { code: 1110, category: ts.DiagnosticCategory.Error, key: "Type expected." }, + A_class_member_cannot_be_declared_optional: { code: 1112, category: ts.DiagnosticCategory.Error, key: "A class member cannot be declared optional." }, + A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: { code: 1113, category: ts.DiagnosticCategory.Error, key: "A 'default' clause cannot appear more than once in a 'switch' statement." }, + Duplicate_label_0: { code: 1114, category: ts.DiagnosticCategory.Error, key: "Duplicate label '{0}'" }, + A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: { code: 1115, category: ts.DiagnosticCategory.Error, key: "A 'continue' statement can only jump to a label of an enclosing iteration statement." }, + A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: { code: 1116, category: ts.DiagnosticCategory.Error, key: "A 'break' statement can only jump to a label of an enclosing statement." }, + An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: { code: 1117, category: ts.DiagnosticCategory.Error, key: "An object literal cannot have multiple properties with the same name in strict mode." }, + An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: { code: 1118, category: ts.DiagnosticCategory.Error, key: "An object literal cannot have multiple get/set accessors with the same name." }, + An_object_literal_cannot_have_property_and_accessor_with_the_same_name: { code: 1119, category: ts.DiagnosticCategory.Error, key: "An object literal cannot have property and accessor with the same name." }, + An_export_assignment_cannot_have_modifiers: { code: 1120, category: ts.DiagnosticCategory.Error, key: "An export assignment cannot have modifiers." }, + Octal_literals_are_not_allowed_in_strict_mode: { code: 1121, category: ts.DiagnosticCategory.Error, key: "Octal literals are not allowed in strict mode." }, + A_tuple_type_element_list_cannot_be_empty: { code: 1122, category: ts.DiagnosticCategory.Error, key: "A tuple type element list cannot be empty." }, + Variable_declaration_list_cannot_be_empty: { code: 1123, category: ts.DiagnosticCategory.Error, key: "Variable declaration list cannot be empty." }, + Digit_expected: { code: 1124, category: ts.DiagnosticCategory.Error, key: "Digit expected." }, + Hexadecimal_digit_expected: { code: 1125, category: ts.DiagnosticCategory.Error, key: "Hexadecimal digit expected." }, + Unexpected_end_of_text: { code: 1126, category: ts.DiagnosticCategory.Error, key: "Unexpected end of text." }, + Invalid_character: { code: 1127, category: ts.DiagnosticCategory.Error, key: "Invalid character." }, + Declaration_or_statement_expected: { code: 1128, category: ts.DiagnosticCategory.Error, key: "Declaration or statement expected." }, + Statement_expected: { code: 1129, category: ts.DiagnosticCategory.Error, key: "Statement expected." }, + case_or_default_expected: { code: 1130, category: ts.DiagnosticCategory.Error, key: "'case' or 'default' expected." }, + Property_or_signature_expected: { code: 1131, category: ts.DiagnosticCategory.Error, key: "Property or signature expected." }, + Enum_member_expected: { code: 1132, category: ts.DiagnosticCategory.Error, key: "Enum member expected." }, + Variable_declaration_expected: { code: 1134, category: ts.DiagnosticCategory.Error, key: "Variable declaration expected." }, + Argument_expression_expected: { code: 1135, category: ts.DiagnosticCategory.Error, key: "Argument expression expected." }, + Property_assignment_expected: { code: 1136, category: ts.DiagnosticCategory.Error, key: "Property assignment expected." }, + Expression_or_comma_expected: { code: 1137, category: ts.DiagnosticCategory.Error, key: "Expression or comma expected." }, + Parameter_declaration_expected: { code: 1138, category: ts.DiagnosticCategory.Error, key: "Parameter declaration expected." }, + Type_parameter_declaration_expected: { code: 1139, category: ts.DiagnosticCategory.Error, key: "Type parameter declaration expected." }, + Type_argument_expected: { code: 1140, category: ts.DiagnosticCategory.Error, key: "Type argument expected." }, + String_literal_expected: { code: 1141, category: ts.DiagnosticCategory.Error, key: "String literal expected." }, + Line_break_not_permitted_here: { code: 1142, category: ts.DiagnosticCategory.Error, key: "Line break not permitted here." }, + or_expected: { code: 1144, category: ts.DiagnosticCategory.Error, key: "'{' or ';' expected." }, + Modifiers_not_permitted_on_index_signature_members: { code: 1145, category: ts.DiagnosticCategory.Error, key: "Modifiers not permitted on index signature members." }, + Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration expected." }, + Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import declarations in a namespace cannot reference a module." }, + Cannot_compile_modules_unless_the_module_flag_is_provided: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot compile modules unless the '--module' flag is provided." }, + File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File name '{0}' differs from already included file name '{1}' only in casing" }, + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, + const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "'const' declarations must be initialized" }, + const_declarations_can_only_be_declared_inside_a_block: { code: 1156, category: ts.DiagnosticCategory.Error, key: "'const' declarations can only be declared inside a block." }, + let_declarations_can_only_be_declared_inside_a_block: { code: 1157, category: ts.DiagnosticCategory.Error, key: "'let' declarations can only be declared inside a block." }, + Unterminated_template_literal: { code: 1160, category: ts.DiagnosticCategory.Error, key: "Unterminated template literal." }, + Unterminated_regular_expression_literal: { code: 1161, category: ts.DiagnosticCategory.Error, key: "Unterminated regular expression literal." }, + An_object_member_cannot_be_declared_optional: { code: 1162, category: ts.DiagnosticCategory.Error, key: "An object member cannot be declared optional." }, + A_yield_expression_is_only_allowed_in_a_generator_body: { code: 1163, category: ts.DiagnosticCategory.Error, key: "A 'yield' expression is only allowed in a generator body." }, + Computed_property_names_are_not_allowed_in_enums: { code: 1164, category: ts.DiagnosticCategory.Error, key: "Computed property names are not allowed in enums." }, + A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: { code: 1165, category: ts.DiagnosticCategory.Error, key: "A computed property name in an ambient context must directly refer to a built-in symbol." }, + A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: { code: 1166, category: ts.DiagnosticCategory.Error, key: "A computed property name in a class property declaration must directly refer to a built-in symbol." }, + A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: { code: 1168, category: ts.DiagnosticCategory.Error, key: "A computed property name in a method overload must directly refer to a built-in symbol." }, + A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: { code: 1169, category: ts.DiagnosticCategory.Error, key: "A computed property name in an interface must directly refer to a built-in symbol." }, + A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: { code: 1170, category: ts.DiagnosticCategory.Error, key: "A computed property name in a type literal must directly refer to a built-in symbol." }, + A_comma_expression_is_not_allowed_in_a_computed_property_name: { code: 1171, category: ts.DiagnosticCategory.Error, key: "A comma expression is not allowed in a computed property name." }, + extends_clause_already_seen: { code: 1172, category: ts.DiagnosticCategory.Error, key: "'extends' clause already seen." }, + extends_clause_must_precede_implements_clause: { code: 1173, category: ts.DiagnosticCategory.Error, key: "'extends' clause must precede 'implements' clause." }, + Classes_can_only_extend_a_single_class: { code: 1174, category: ts.DiagnosticCategory.Error, key: "Classes can only extend a single class." }, + implements_clause_already_seen: { code: 1175, category: ts.DiagnosticCategory.Error, key: "'implements' clause already seen." }, + Interface_declaration_cannot_have_implements_clause: { code: 1176, category: ts.DiagnosticCategory.Error, key: "Interface declaration cannot have 'implements' clause." }, + Binary_digit_expected: { code: 1177, category: ts.DiagnosticCategory.Error, key: "Binary digit expected." }, + Octal_digit_expected: { code: 1178, category: ts.DiagnosticCategory.Error, key: "Octal digit expected." }, + Unexpected_token_expected: { code: 1179, category: ts.DiagnosticCategory.Error, key: "Unexpected token. '{' expected." }, + Property_destructuring_pattern_expected: { code: 1180, category: ts.DiagnosticCategory.Error, key: "Property destructuring pattern expected." }, + Array_element_destructuring_pattern_expected: { code: 1181, category: ts.DiagnosticCategory.Error, key: "Array element destructuring pattern expected." }, + A_destructuring_declaration_must_have_an_initializer: { code: 1182, category: ts.DiagnosticCategory.Error, key: "A destructuring declaration must have an initializer." }, + An_implementation_cannot_be_declared_in_ambient_contexts: { code: 1183, category: ts.DiagnosticCategory.Error, key: "An implementation cannot be declared in ambient contexts." }, + Modifiers_cannot_appear_here: { code: 1184, category: ts.DiagnosticCategory.Error, key: "Modifiers cannot appear here." }, + Merge_conflict_marker_encountered: { code: 1185, category: ts.DiagnosticCategory.Error, key: "Merge conflict marker encountered." }, + A_rest_element_cannot_have_an_initializer: { code: 1186, category: ts.DiagnosticCategory.Error, key: "A rest element cannot have an initializer." }, + A_parameter_property_may_not_be_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A parameter property may not be a binding pattern." }, + Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: { code: 1188, category: ts.DiagnosticCategory.Error, key: "Only a single variable declaration is allowed in a 'for...of' statement." }, + The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: { code: 1189, category: ts.DiagnosticCategory.Error, key: "The variable declaration of a 'for...in' statement cannot have an initializer." }, + The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: { code: 1190, category: ts.DiagnosticCategory.Error, key: "The variable declaration of a 'for...of' statement cannot have an initializer." }, + An_import_declaration_cannot_have_modifiers: { code: 1191, category: ts.DiagnosticCategory.Error, key: "An import declaration cannot have modifiers." }, + Module_0_has_no_default_export: { code: 1192, category: ts.DiagnosticCategory.Error, key: "Module '{0}' has no default export." }, + An_export_declaration_cannot_have_modifiers: { code: 1193, category: ts.DiagnosticCategory.Error, key: "An export declaration cannot have modifiers." }, + Export_declarations_are_not_permitted_in_a_namespace: { code: 1194, category: ts.DiagnosticCategory.Error, key: "Export declarations are not permitted in a namespace." }, + Catch_clause_variable_name_must_be_an_identifier: { code: 1195, category: ts.DiagnosticCategory.Error, key: "Catch clause variable name must be an identifier." }, + Catch_clause_variable_cannot_have_a_type_annotation: { code: 1196, category: ts.DiagnosticCategory.Error, key: "Catch clause variable cannot have a type annotation." }, + Catch_clause_variable_cannot_have_an_initializer: { code: 1197, category: ts.DiagnosticCategory.Error, key: "Catch clause variable cannot have an initializer." }, + An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: { code: 1198, category: ts.DiagnosticCategory.Error, key: "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive." }, + Unterminated_Unicode_escape_sequence: { code: 1199, category: ts.DiagnosticCategory.Error, key: "Unterminated Unicode escape sequence." }, + Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line terminator not permitted before arrow." }, + Import_assignment_cannot_be_used_when_targeting_ECMAScript_6_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import assignment cannot be used when targeting ECMAScript 6 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, + Export_assignment_cannot_be_used_when_targeting_ECMAScript_6_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export assignment cannot be used when targeting ECMAScript 6 modules. Consider using 'export default' or another module format instead." }, + Cannot_compile_modules_into_es6_when_targeting_ES5_or_lower: { code: 1204, category: ts.DiagnosticCategory.Error, key: "Cannot compile modules into 'es6' when targeting 'ES5' or lower." }, + Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators are not valid here." }, + Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators cannot be applied to multiple get/set accessors of the same name." }, + Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, + Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: { code: 1209, category: ts.DiagnosticCategory.Error, key: "Ambient const enums are not allowed when the '--isolatedModules' flag is provided." }, + Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: { code: 1210, category: ts.DiagnosticCategory.Error, key: "Invalid use of '{0}'. Class definitions are automatically in strict mode." }, + A_class_declaration_without_the_default_modifier_must_have_a_name: { code: 1211, category: ts.DiagnosticCategory.Error, key: "A class declaration without the 'default' modifier must have a name" }, + Identifier_expected_0_is_a_reserved_word_in_strict_mode: { code: 1212, category: ts.DiagnosticCategory.Error, key: "Identifier expected. '{0}' is a reserved word in strict mode" }, + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1213, category: ts.DiagnosticCategory.Error, key: "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." }, + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: { code: 1214, category: ts.DiagnosticCategory.Error, key: "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode." }, + Invalid_use_of_0_Modules_are_automatically_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Invalid use of '{0}'. Modules are automatically in strict mode." }, + Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: ts.DiagnosticCategory.Error, key: "Export assignment is not supported when '--module' flag is 'system'." }, + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Specify_experimentalDecorators_to_remove_this_warning: { code: 1219, category: ts.DiagnosticCategory.Error, key: "Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning." }, + Generators_are_only_available_when_targeting_ECMAScript_6_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators are only available when targeting ECMAScript 6 or higher." }, + Generators_are_not_allowed_in_an_ambient_context: { code: 1221, category: ts.DiagnosticCategory.Error, key: "Generators are not allowed in an ambient context." }, + An_overload_signature_cannot_be_declared_as_a_generator: { code: 1222, category: ts.DiagnosticCategory.Error, key: "An overload signature cannot be declared as a generator." }, + _0_tag_already_specified: { code: 1223, category: ts.DiagnosticCategory.Error, key: "'{0}' tag already specified." }, + Signature_0_must_have_a_type_predicate: { code: 1224, category: ts.DiagnosticCategory.Error, key: "Signature '{0}' must have a type predicate." }, + Cannot_find_parameter_0: { code: 1225, category: ts.DiagnosticCategory.Error, key: "Cannot find parameter '{0}'." }, + Type_predicate_0_is_not_assignable_to_1: { code: 1226, category: ts.DiagnosticCategory.Error, key: "Type predicate '{0}' is not assignable to '{1}'." }, + Parameter_0_is_not_in_the_same_position_as_parameter_1: { code: 1227, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' is not in the same position as parameter '{1}'." }, + A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: { code: 1228, category: ts.DiagnosticCategory.Error, key: "A type predicate is only allowed in return type position for functions and methods." }, + A_type_predicate_cannot_reference_a_rest_parameter: { code: 1229, category: ts.DiagnosticCategory.Error, key: "A type predicate cannot reference a rest parameter." }, + A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: { code: 1230, category: ts.DiagnosticCategory.Error, key: "A type predicate cannot reference element '{0}' in a binding pattern." }, + An_export_assignment_can_only_be_used_in_a_module: { code: 1231, category: ts.DiagnosticCategory.Error, key: "An export assignment can only be used in a module." }, + An_import_declaration_can_only_be_used_in_a_namespace_or_module: { code: 1232, category: ts.DiagnosticCategory.Error, key: "An import declaration can only be used in a namespace or module." }, + An_export_declaration_can_only_be_used_in_a_module: { code: 1233, category: ts.DiagnosticCategory.Error, key: "An export declaration can only be used in a module." }, + An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: { code: 1234, category: ts.DiagnosticCategory.Error, key: "An ambient module declaration is only allowed at the top level in a file." }, + A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: { code: 1235, category: ts.DiagnosticCategory.Error, key: "A namespace declaration is only allowed in a namespace or module." }, + The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: { code: 1236, category: ts.DiagnosticCategory.Error, key: "The return type of a property decorator function must be either 'void' or 'any'." }, + The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: { code: 1237, category: ts.DiagnosticCategory.Error, key: "The return type of a parameter decorator function must be either 'void' or 'any'." }, + Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: { code: 1238, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of class decorator when called as an expression." }, + Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: { code: 1239, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of parameter decorator when called as an expression." }, + Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: { code: 1240, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of property decorator when called as an expression." }, + Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: { code: 1241, category: ts.DiagnosticCategory.Error, key: "Unable to resolve signature of method decorator when called as an expression." }, + abstract_modifier_can_only_appear_on_a_class_or_method_declaration: { code: 1242, category: ts.DiagnosticCategory.Error, key: "'abstract' modifier can only appear on a class or method declaration." }, + _0_modifier_cannot_be_used_with_1_modifier: { code: 1243, category: ts.DiagnosticCategory.Error, key: "'{0}' modifier cannot be used with '{1}' modifier." }, + Abstract_methods_can_only_appear_within_an_abstract_class: { code: 1244, category: ts.DiagnosticCategory.Error, key: "Abstract methods can only appear within an abstract class." }, + Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: { code: 1245, category: ts.DiagnosticCategory.Error, key: "Method '{0}' cannot have an implementation because it is marked abstract." }, + with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "'with' statements are not allowed in an async function block." }, + await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "'await' expression is only allowed within an async function." }, + Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1311, category: ts.DiagnosticCategory.Error, key: "Async functions are only available when targeting ECMAScript 6 and higher." }, + can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: { code: 1312, category: ts.DiagnosticCategory.Error, key: "'=' can only be used in an object literal property inside a destructuring assignment." }, + Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate identifier '{0}'." }, + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, + Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." }, + Circular_definition_of_import_alias_0: { code: 2303, category: ts.DiagnosticCategory.Error, key: "Circular definition of import alias '{0}'." }, + Cannot_find_name_0: { code: 2304, category: ts.DiagnosticCategory.Error, key: "Cannot find name '{0}'." }, + Module_0_has_no_exported_member_1: { code: 2305, category: ts.DiagnosticCategory.Error, key: "Module '{0}' has no exported member '{1}'." }, + File_0_is_not_a_module: { code: 2306, category: ts.DiagnosticCategory.Error, key: "File '{0}' is not a module." }, + Cannot_find_module_0: { code: 2307, category: ts.DiagnosticCategory.Error, key: "Cannot find module '{0}'." }, + An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: ts.DiagnosticCategory.Error, key: "An export assignment cannot be used in a module with other exported elements." }, + Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: ts.DiagnosticCategory.Error, key: "Type '{0}' recursively references itself as a base type." }, + A_class_may_only_extend_another_class: { code: 2311, category: ts.DiagnosticCategory.Error, key: "A class may only extend another class." }, + An_interface_may_only_extend_a_class_or_another_interface: { code: 2312, category: ts.DiagnosticCategory.Error, key: "An interface may only extend a class or another interface." }, + Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Constraint of a type parameter cannot reference any type parameter from the same type parameter list." }, + Generic_type_0_requires_1_type_argument_s: { code: 2314, category: ts.DiagnosticCategory.Error, key: "Generic type '{0}' requires {1} type argument(s)." }, + Type_0_is_not_generic: { code: 2315, category: ts.DiagnosticCategory.Error, key: "Type '{0}' is not generic." }, + Global_type_0_must_be_a_class_or_interface_type: { code: 2316, category: ts.DiagnosticCategory.Error, key: "Global type '{0}' must be a class or interface type." }, + Global_type_0_must_have_1_type_parameter_s: { code: 2317, category: ts.DiagnosticCategory.Error, key: "Global type '{0}' must have {1} type parameter(s)." }, + Cannot_find_global_type_0: { code: 2318, category: ts.DiagnosticCategory.Error, key: "Cannot find global type '{0}'." }, + Named_property_0_of_types_1_and_2_are_not_identical: { code: 2319, category: ts.DiagnosticCategory.Error, key: "Named property '{0}' of types '{1}' and '{2}' are not identical." }, + Interface_0_cannot_simultaneously_extend_types_1_and_2: { code: 2320, category: ts.DiagnosticCategory.Error, key: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'." }, + Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: ts.DiagnosticCategory.Error, key: "Excessive stack depth comparing types '{0}' and '{1}'." }, + Type_0_is_not_assignable_to_type_1: { code: 2322, category: ts.DiagnosticCategory.Error, key: "Type '{0}' is not assignable to type '{1}'." }, + Property_0_is_missing_in_type_1: { code: 2324, category: ts.DiagnosticCategory.Error, key: "Property '{0}' is missing in type '{1}'." }, + Property_0_is_private_in_type_1_but_not_in_type_2: { code: 2325, category: ts.DiagnosticCategory.Error, key: "Property '{0}' is private in type '{1}' but not in type '{2}'." }, + Types_of_property_0_are_incompatible: { code: 2326, category: ts.DiagnosticCategory.Error, key: "Types of property '{0}' are incompatible." }, + Property_0_is_optional_in_type_1_but_required_in_type_2: { code: 2327, category: ts.DiagnosticCategory.Error, key: "Property '{0}' is optional in type '{1}' but required in type '{2}'." }, + Types_of_parameters_0_and_1_are_incompatible: { code: 2328, category: ts.DiagnosticCategory.Error, key: "Types of parameters '{0}' and '{1}' are incompatible." }, + Index_signature_is_missing_in_type_0: { code: 2329, category: ts.DiagnosticCategory.Error, key: "Index signature is missing in type '{0}'." }, + Index_signatures_are_incompatible: { code: 2330, category: ts.DiagnosticCategory.Error, key: "Index signatures are incompatible." }, + this_cannot_be_referenced_in_a_module_or_namespace_body: { code: 2331, category: ts.DiagnosticCategory.Error, key: "'this' cannot be referenced in a module or namespace body." }, + this_cannot_be_referenced_in_current_location: { code: 2332, category: ts.DiagnosticCategory.Error, key: "'this' cannot be referenced in current location." }, + this_cannot_be_referenced_in_constructor_arguments: { code: 2333, category: ts.DiagnosticCategory.Error, key: "'this' cannot be referenced in constructor arguments." }, + this_cannot_be_referenced_in_a_static_property_initializer: { code: 2334, category: ts.DiagnosticCategory.Error, key: "'this' cannot be referenced in a static property initializer." }, + super_can_only_be_referenced_in_a_derived_class: { code: 2335, category: ts.DiagnosticCategory.Error, key: "'super' can only be referenced in a derived class." }, + super_cannot_be_referenced_in_constructor_arguments: { code: 2336, category: ts.DiagnosticCategory.Error, key: "'super' cannot be referenced in constructor arguments." }, + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: { code: 2337, category: ts.DiagnosticCategory.Error, key: "Super calls are not permitted outside constructors or in nested functions inside constructors." }, + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: { code: 2338, category: ts.DiagnosticCategory.Error, key: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class." }, + Property_0_does_not_exist_on_type_1: { code: 2339, category: ts.DiagnosticCategory.Error, key: "Property '{0}' does not exist on type '{1}'." }, + Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: ts.DiagnosticCategory.Error, key: "Only public and protected methods of the base class are accessible via the 'super' keyword." }, + Property_0_is_private_and_only_accessible_within_class_1: { code: 2341, category: ts.DiagnosticCategory.Error, key: "Property '{0}' is private and only accessible within class '{1}'." }, + An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: { code: 2342, category: ts.DiagnosticCategory.Error, key: "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'." }, + Type_0_does_not_satisfy_the_constraint_1: { code: 2344, category: ts.DiagnosticCategory.Error, key: "Type '{0}' does not satisfy the constraint '{1}'." }, + Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: { code: 2345, category: ts.DiagnosticCategory.Error, key: "Argument of type '{0}' is not assignable to parameter of type '{1}'." }, + Supplied_parameters_do_not_match_any_signature_of_call_target: { code: 2346, category: ts.DiagnosticCategory.Error, key: "Supplied parameters do not match any signature of call target." }, + Untyped_function_calls_may_not_accept_type_arguments: { code: 2347, category: ts.DiagnosticCategory.Error, key: "Untyped function calls may not accept type arguments." }, + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: { code: 2348, category: ts.DiagnosticCategory.Error, key: "Value of type '{0}' is not callable. Did you mean to include 'new'?" }, + Cannot_invoke_an_expression_whose_type_lacks_a_call_signature: { code: 2349, category: ts.DiagnosticCategory.Error, key: "Cannot invoke an expression whose type lacks a call signature." }, + Only_a_void_function_can_be_called_with_the_new_keyword: { code: 2350, category: ts.DiagnosticCategory.Error, key: "Only a void function can be called with the 'new' keyword." }, + Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: ts.DiagnosticCategory.Error, key: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, + Neither_type_0_nor_type_1_is_assignable_to_the_other: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Neither type '{0}' nor type '{1}' is assignable to the other." }, + Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, + No_best_common_type_exists_among_return_expressions: { code: 2354, category: ts.DiagnosticCategory.Error, key: "No best common type exists among return expressions." }, + A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement." }, + An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The operand of an increment or decrement operator must be a variable, property or indexer." }, + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: ts.DiagnosticCategory.Error, key: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." }, + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: { code: 2359, category: ts.DiagnosticCategory.Error, key: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type." }, + The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: { code: 2360, category: ts.DiagnosticCategory.Error, key: "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'." }, + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2361, category: ts.DiagnosticCategory.Error, key: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter" }, + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2362, category: ts.DiagnosticCategory.Error, key: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2363, category: ts.DiagnosticCategory.Error, key: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, + Invalid_left_hand_side_of_assignment_expression: { code: 2364, category: ts.DiagnosticCategory.Error, key: "Invalid left-hand side of assignment expression." }, + Operator_0_cannot_be_applied_to_types_1_and_2: { code: 2365, category: ts.DiagnosticCategory.Error, key: "Operator '{0}' cannot be applied to types '{1}' and '{2}'." }, + Type_parameter_name_cannot_be_0: { code: 2368, category: ts.DiagnosticCategory.Error, key: "Type parameter name cannot be '{0}'" }, + A_parameter_property_is_only_allowed_in_a_constructor_implementation: { code: 2369, category: ts.DiagnosticCategory.Error, key: "A parameter property is only allowed in a constructor implementation." }, + A_rest_parameter_must_be_of_an_array_type: { code: 2370, category: ts.DiagnosticCategory.Error, key: "A rest parameter must be of an array type." }, + A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: { code: 2371, category: ts.DiagnosticCategory.Error, key: "A parameter initializer is only allowed in a function or constructor implementation." }, + Parameter_0_cannot_be_referenced_in_its_initializer: { code: 2372, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' cannot be referenced in its initializer." }, + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: { code: 2373, category: ts.DiagnosticCategory.Error, key: "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it." }, + Duplicate_string_index_signature: { code: 2374, category: ts.DiagnosticCategory.Error, key: "Duplicate string index signature." }, + Duplicate_number_index_signature: { code: 2375, category: ts.DiagnosticCategory.Error, key: "Duplicate number index signature." }, + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: { code: 2376, category: ts.DiagnosticCategory.Error, key: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties." }, + Constructors_for_derived_classes_must_contain_a_super_call: { code: 2377, category: ts.DiagnosticCategory.Error, key: "Constructors for derived classes must contain a 'super' call." }, + A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2378, category: ts.DiagnosticCategory.Error, key: "A 'get' accessor must return a value or consist of a single 'throw' statement." }, + Getter_and_setter_accessors_do_not_agree_in_visibility: { code: 2379, category: ts.DiagnosticCategory.Error, key: "Getter and setter accessors do not agree in visibility." }, + get_and_set_accessor_must_have_the_same_type: { code: 2380, category: ts.DiagnosticCategory.Error, key: "'get' and 'set' accessor must have the same type." }, + A_signature_with_an_implementation_cannot_use_a_string_literal_type: { code: 2381, category: ts.DiagnosticCategory.Error, key: "A signature with an implementation cannot use a string literal type." }, + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: { code: 2382, category: ts.DiagnosticCategory.Error, key: "Specialized overload signature is not assignable to any non-specialized signature." }, + Overload_signatures_must_all_be_exported_or_not_exported: { code: 2383, category: ts.DiagnosticCategory.Error, key: "Overload signatures must all be exported or not exported." }, + Overload_signatures_must_all_be_ambient_or_non_ambient: { code: 2384, category: ts.DiagnosticCategory.Error, key: "Overload signatures must all be ambient or non-ambient." }, + Overload_signatures_must_all_be_public_private_or_protected: { code: 2385, category: ts.DiagnosticCategory.Error, key: "Overload signatures must all be public, private or protected." }, + Overload_signatures_must_all_be_optional_or_required: { code: 2386, category: ts.DiagnosticCategory.Error, key: "Overload signatures must all be optional or required." }, + Function_overload_must_be_static: { code: 2387, category: ts.DiagnosticCategory.Error, key: "Function overload must be static." }, + Function_overload_must_not_be_static: { code: 2388, category: ts.DiagnosticCategory.Error, key: "Function overload must not be static." }, + Function_implementation_name_must_be_0: { code: 2389, category: ts.DiagnosticCategory.Error, key: "Function implementation name must be '{0}'." }, + Constructor_implementation_is_missing: { code: 2390, category: ts.DiagnosticCategory.Error, key: "Constructor implementation is missing." }, + Function_implementation_is_missing_or_not_immediately_following_the_declaration: { code: 2391, category: ts.DiagnosticCategory.Error, key: "Function implementation is missing or not immediately following the declaration." }, + Multiple_constructor_implementations_are_not_allowed: { code: 2392, category: ts.DiagnosticCategory.Error, key: "Multiple constructor implementations are not allowed." }, + Duplicate_function_implementation: { code: 2393, category: ts.DiagnosticCategory.Error, key: "Duplicate function implementation." }, + Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: ts.DiagnosticCategory.Error, key: "Overload signature is not compatible with function implementation." }, + Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: ts.DiagnosticCategory.Error, key: "Individual declarations in merged declaration '{0}' must be all exported or all local." }, + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: ts.DiagnosticCategory.Error, key: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." }, + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: ts.DiagnosticCategory.Error, key: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." }, + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: ts.DiagnosticCategory.Error, key: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." }, + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: { code: 2401, category: ts.DiagnosticCategory.Error, key: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference." }, + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: { code: 2402, category: ts.DiagnosticCategory.Error, key: "Expression resolves to '_super' that compiler uses to capture base class reference." }, + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: { code: 2403, category: ts.DiagnosticCategory.Error, key: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'." }, + The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: { code: 2404, category: ts.DiagnosticCategory.Error, key: "The left-hand side of a 'for...in' statement cannot use a type annotation." }, + The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: { code: 2405, category: ts.DiagnosticCategory.Error, key: "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'." }, + Invalid_left_hand_side_in_for_in_statement: { code: 2406, category: ts.DiagnosticCategory.Error, key: "Invalid left-hand side in 'for...in' statement." }, + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, + Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters cannot return a value." }, + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return type of constructor signature must be assignable to the instance type of the class" }, + All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All symbols within a 'with' block will be resolved to 'any'." }, + Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, + Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, + Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, + Class_name_cannot_be_0: { code: 2414, category: ts.DiagnosticCategory.Error, key: "Class name cannot be '{0}'" }, + Class_0_incorrectly_extends_base_class_1: { code: 2415, category: ts.DiagnosticCategory.Error, key: "Class '{0}' incorrectly extends base class '{1}'." }, + Class_static_side_0_incorrectly_extends_base_class_static_side_1: { code: 2417, category: ts.DiagnosticCategory.Error, key: "Class static side '{0}' incorrectly extends base class static side '{1}'." }, + Type_name_0_in_extends_clause_does_not_reference_constructor_function_for_0: { code: 2419, category: ts.DiagnosticCategory.Error, key: "Type name '{0}' in extends clause does not reference constructor function for '{0}'." }, + Class_0_incorrectly_implements_interface_1: { code: 2420, category: ts.DiagnosticCategory.Error, key: "Class '{0}' incorrectly implements interface '{1}'." }, + A_class_may_only_implement_another_class_or_interface: { code: 2422, category: ts.DiagnosticCategory.Error, key: "A class may only implement another class or interface." }, + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: { code: 2423, category: ts.DiagnosticCategory.Error, key: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor." }, + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: { code: 2424, category: ts.DiagnosticCategory.Error, key: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property." }, + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2425, category: ts.DiagnosticCategory.Error, key: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function." }, + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2426, category: ts.DiagnosticCategory.Error, key: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function." }, + Interface_name_cannot_be_0: { code: 2427, category: ts.DiagnosticCategory.Error, key: "Interface name cannot be '{0}'" }, + All_declarations_of_an_interface_must_have_identical_type_parameters: { code: 2428, category: ts.DiagnosticCategory.Error, key: "All declarations of an interface must have identical type parameters." }, + Interface_0_incorrectly_extends_interface_1: { code: 2430, category: ts.DiagnosticCategory.Error, key: "Interface '{0}' incorrectly extends interface '{1}'." }, + Enum_name_cannot_be_0: { code: 2431, category: ts.DiagnosticCategory.Error, key: "Enum name cannot be '{0}'" }, + In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: { code: 2432, category: ts.DiagnosticCategory.Error, key: "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element." }, + A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: { code: 2433, category: ts.DiagnosticCategory.Error, key: "A namespace declaration cannot be in a different file from a class or function with which it is merged" }, + A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: { code: 2434, category: ts.DiagnosticCategory.Error, key: "A namespace declaration cannot be located prior to a class or function with which it is merged" }, + Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: { code: 2435, category: ts.DiagnosticCategory.Error, key: "Ambient modules cannot be nested in other modules or namespaces." }, + Ambient_module_declaration_cannot_specify_relative_module_name: { code: 2436, category: ts.DiagnosticCategory.Error, key: "Ambient module declaration cannot specify relative module name." }, + Module_0_is_hidden_by_a_local_declaration_with_the_same_name: { code: 2437, category: ts.DiagnosticCategory.Error, key: "Module '{0}' is hidden by a local declaration with the same name" }, + Import_name_cannot_be_0: { code: 2438, category: ts.DiagnosticCategory.Error, key: "Import name cannot be '{0}'" }, + Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: { code: 2439, category: ts.DiagnosticCategory.Error, key: "Import or export declaration in an ambient module declaration cannot reference module through relative module name." }, + Import_declaration_conflicts_with_local_declaration_of_0: { code: 2440, category: ts.DiagnosticCategory.Error, key: "Import declaration conflicts with local declaration of '{0}'" }, + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: { code: 2441, category: ts.DiagnosticCategory.Error, key: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module." }, + Types_have_separate_declarations_of_a_private_property_0: { code: 2442, category: ts.DiagnosticCategory.Error, key: "Types have separate declarations of a private property '{0}'." }, + Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: { code: 2443, category: ts.DiagnosticCategory.Error, key: "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'." }, + Property_0_is_protected_in_type_1_but_public_in_type_2: { code: 2444, category: ts.DiagnosticCategory.Error, key: "Property '{0}' is protected in type '{1}' but public in type '{2}'." }, + Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: { code: 2445, category: ts.DiagnosticCategory.Error, key: "Property '{0}' is protected and only accessible within class '{1}' and its subclasses." }, + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: ts.DiagnosticCategory.Error, key: "Property '{0}' is protected and only accessible through an instance of class '{1}'." }, + The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: ts.DiagnosticCategory.Error, key: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." }, + Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: ts.DiagnosticCategory.Error, key: "Block-scoped variable '{0}' used before its declaration." }, + The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant: { code: 2449, category: ts.DiagnosticCategory.Error, key: "The operand of an increment or decrement operator cannot be a constant." }, + Left_hand_side_of_assignment_expression_cannot_be_a_constant: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Left-hand side of assignment expression cannot be a constant." }, + Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: ts.DiagnosticCategory.Error, key: "Cannot redeclare block-scoped variable '{0}'." }, + An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: ts.DiagnosticCategory.Error, key: "An enum member cannot have a numeric name." }, + The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: ts.DiagnosticCategory.Error, key: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, + Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: { code: 2455, category: ts.DiagnosticCategory.Error, key: "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'." }, + Type_alias_0_circularly_references_itself: { code: 2456, category: ts.DiagnosticCategory.Error, key: "Type alias '{0}' circularly references itself." }, + Type_alias_name_cannot_be_0: { code: 2457, category: ts.DiagnosticCategory.Error, key: "Type alias name cannot be '{0}'" }, + An_AMD_module_cannot_have_multiple_name_assignments: { code: 2458, category: ts.DiagnosticCategory.Error, key: "An AMD module cannot have multiple name assignments." }, + Type_0_has_no_property_1_and_no_string_index_signature: { code: 2459, category: ts.DiagnosticCategory.Error, key: "Type '{0}' has no property '{1}' and no string index signature." }, + Type_0_has_no_property_1: { code: 2460, category: ts.DiagnosticCategory.Error, key: "Type '{0}' has no property '{1}'." }, + Type_0_is_not_an_array_type: { code: 2461, category: ts.DiagnosticCategory.Error, key: "Type '{0}' is not an array type." }, + A_rest_element_must_be_last_in_an_array_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A rest element must be last in an array destructuring pattern" }, + A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: { code: 2463, category: ts.DiagnosticCategory.Error, key: "A binding pattern parameter cannot be optional in an implementation signature." }, + A_computed_property_name_must_be_of_type_string_number_symbol_or_any: { code: 2464, category: ts.DiagnosticCategory.Error, key: "A computed property name must be of type 'string', 'number', 'symbol', or 'any'." }, + this_cannot_be_referenced_in_a_computed_property_name: { code: 2465, category: ts.DiagnosticCategory.Error, key: "'this' cannot be referenced in a computed property name." }, + super_cannot_be_referenced_in_a_computed_property_name: { code: 2466, category: ts.DiagnosticCategory.Error, key: "'super' cannot be referenced in a computed property name." }, + A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: { code: 2467, category: ts.DiagnosticCategory.Error, key: "A computed property name cannot reference a type parameter from its containing type." }, + Cannot_find_global_value_0: { code: 2468, category: ts.DiagnosticCategory.Error, key: "Cannot find global value '{0}'." }, + The_0_operator_cannot_be_applied_to_type_symbol: { code: 2469, category: ts.DiagnosticCategory.Error, key: "The '{0}' operator cannot be applied to type 'symbol'." }, + Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: { code: 2470, category: ts.DiagnosticCategory.Error, key: "'Symbol' reference does not refer to the global Symbol constructor object." }, + A_computed_property_name_of_the_form_0_must_be_of_type_symbol: { code: 2471, category: ts.DiagnosticCategory.Error, key: "A computed property name of the form '{0}' must be of type 'symbol'." }, + Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: { code: 2472, category: ts.DiagnosticCategory.Error, key: "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher." }, + Enum_declarations_must_all_be_const_or_non_const: { code: 2473, category: ts.DiagnosticCategory.Error, key: "Enum declarations must all be const or non-const." }, + In_const_enum_declarations_member_initializer_must_be_constant_expression: { code: 2474, category: ts.DiagnosticCategory.Error, key: "In 'const' enum declarations member initializer must be constant expression." }, + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: { code: 2475, category: ts.DiagnosticCategory.Error, key: "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment." }, + A_const_enum_member_can_only_be_accessed_using_a_string_literal: { code: 2476, category: ts.DiagnosticCategory.Error, key: "A const enum member can only be accessed using a string literal." }, + const_enum_member_initializer_was_evaluated_to_a_non_finite_value: { code: 2477, category: ts.DiagnosticCategory.Error, key: "'const' enum member initializer was evaluated to a non-finite value." }, + const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: { code: 2478, category: ts.DiagnosticCategory.Error, key: "'const' enum member initializer was evaluated to disallowed value 'NaN'." }, + Property_0_does_not_exist_on_const_enum_1: { code: 2479, category: ts.DiagnosticCategory.Error, key: "Property '{0}' does not exist on 'const' enum '{1}'." }, + let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: { code: 2480, category: ts.DiagnosticCategory.Error, key: "'let' is not allowed to be used as a name in 'let' or 'const' declarations." }, + Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: { code: 2481, category: ts.DiagnosticCategory.Error, key: "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'." }, + The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: { code: 2483, category: ts.DiagnosticCategory.Error, key: "The left-hand side of a 'for...of' statement cannot use a type annotation." }, + Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: ts.DiagnosticCategory.Error, key: "Export declaration conflicts with exported declaration of '{0}'" }, + The_left_hand_side_of_a_for_of_statement_cannot_be_a_previously_defined_constant: { code: 2485, category: ts.DiagnosticCategory.Error, key: "The left-hand side of a 'for...of' statement cannot be a previously defined constant." }, + The_left_hand_side_of_a_for_in_statement_cannot_be_a_previously_defined_constant: { code: 2486, category: ts.DiagnosticCategory.Error, key: "The left-hand side of a 'for...in' statement cannot be a previously defined constant." }, + Invalid_left_hand_side_in_for_of_statement: { code: 2487, category: ts.DiagnosticCategory.Error, key: "Invalid left-hand side in 'for...of' statement." }, + Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: ts.DiagnosticCategory.Error, key: "Type must have a '[Symbol.iterator]()' method that returns an iterator." }, + An_iterator_must_have_a_next_method: { code: 2489, category: ts.DiagnosticCategory.Error, key: "An iterator must have a 'next()' method." }, + The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: { code: 2490, category: ts.DiagnosticCategory.Error, key: "The type returned by the 'next()' method of an iterator must have a 'value' property." }, + The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: { code: 2491, category: ts.DiagnosticCategory.Error, key: "The left-hand side of a 'for...in' statement cannot be a destructuring pattern." }, + Cannot_redeclare_identifier_0_in_catch_clause: { code: 2492, category: ts.DiagnosticCategory.Error, key: "Cannot redeclare identifier '{0}' in catch clause" }, + Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: { code: 2493, category: ts.DiagnosticCategory.Error, key: "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'." }, + Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: { code: 2494, category: ts.DiagnosticCategory.Error, key: "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher." }, + Type_0_is_not_an_array_type_or_a_string_type: { code: 2495, category: ts.DiagnosticCategory.Error, key: "Type '{0}' is not an array type or a string type." }, + The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: { code: 2496, category: ts.DiagnosticCategory.Error, key: "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression." }, + Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: { code: 2497, category: ts.DiagnosticCategory.Error, key: "Module '{0}' resolves to a non-module entity and cannot be imported using this construct." }, + Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: { code: 2498, category: ts.DiagnosticCategory.Error, key: "Module '{0}' uses 'export =' and cannot be used with 'export *'." }, + An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2499, category: ts.DiagnosticCategory.Error, key: "An interface can only extend an identifier/qualified-name with optional type arguments." }, + A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2500, category: ts.DiagnosticCategory.Error, key: "A class can only implement an identifier/qualified-name with optional type arguments." }, + A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "A rest element cannot contain a binding pattern." }, + _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: ts.DiagnosticCategory.Error, key: "'{0}' is referenced directly or indirectly in its own type annotation." }, + Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot find namespace '{0}'." }, + No_best_common_type_exists_among_yield_expressions: { code: 2504, category: ts.DiagnosticCategory.Error, key: "No best common type exists among yield expressions." }, + A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: ts.DiagnosticCategory.Error, key: "A generator cannot have a 'void' type annotation." }, + _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: { code: 2506, category: ts.DiagnosticCategory.Error, key: "'{0}' is referenced directly or indirectly in its own base expression." }, + Type_0_is_not_a_constructor_function_type: { code: 2507, category: ts.DiagnosticCategory.Error, key: "Type '{0}' is not a constructor function type." }, + No_base_constructor_has_the_specified_number_of_type_arguments: { code: 2508, category: ts.DiagnosticCategory.Error, key: "No base constructor has the specified number of type arguments." }, + Base_constructor_return_type_0_is_not_a_class_or_interface_type: { code: 2509, category: ts.DiagnosticCategory.Error, key: "Base constructor return type '{0}' is not a class or interface type." }, + Base_constructors_must_all_have_the_same_return_type: { code: 2510, category: ts.DiagnosticCategory.Error, key: "Base constructors must all have the same return type." }, + Cannot_create_an_instance_of_the_abstract_class_0: { code: 2511, category: ts.DiagnosticCategory.Error, key: "Cannot create an instance of the abstract class '{0}'." }, + Overload_signatures_must_all_be_abstract_or_not_abstract: { code: 2512, category: ts.DiagnosticCategory.Error, key: "Overload signatures must all be abstract or not abstract." }, + Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: { code: 2513, category: ts.DiagnosticCategory.Error, key: "Abstract method '{0}' in class '{1}' cannot be accessed via super expression." }, + Classes_containing_abstract_methods_must_be_marked_abstract: { code: 2514, category: ts.DiagnosticCategory.Error, key: "Classes containing abstract methods must be marked abstract." }, + Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: ts.DiagnosticCategory.Error, key: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." }, + All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All declarations of an abstract method must be consecutive." }, + Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, + Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, + Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, + The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_function_expression: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression." }, + yield_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2523, category: ts.DiagnosticCategory.Error, key: "'yield' expressions cannot be used in a parameter initializer." }, + await_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2524, category: ts.DiagnosticCategory.Error, key: "'await' expressions cannot be used in a parameter initializer." }, + Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: { code: 2525, category: ts.DiagnosticCategory.Error, key: "Initializer provides no value for this binding element and the binding element has no default value." }, + A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: { code: 2526, category: ts.DiagnosticCategory.Error, key: "A 'this' type is available only in a non-static member of a class or interface." }, + The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: { code: 2527, category: ts.DiagnosticCategory.Error, key: "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary." }, + A_module_cannot_have_multiple_default_exports: { code: 2528, category: ts.DiagnosticCategory.Error, key: "A module cannot have multiple default exports." }, + JSX_element_attributes_type_0_must_be_an_object_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX element attributes type '{0}' must be an object type." }, + The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The return type of a JSX element constructor must return an object type." }, + JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, + Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: ts.DiagnosticCategory.Error, key: "Property '{0}' in type '{1}' is not assignable to type '{2}'" }, + JSX_element_type_0_does_not_have_any_construct_or_call_signatures: { code: 2604, category: ts.DiagnosticCategory.Error, key: "JSX element type '{0}' does not have any construct or call signatures." }, + JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: { code: 2605, category: ts.DiagnosticCategory.Error, key: "JSX element type '{0}' is not a constructor function for JSX elements." }, + Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: { code: 2606, category: ts.DiagnosticCategory.Error, key: "Property '{0}' of JSX spread attribute is not assignable to target property." }, + JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: { code: 2607, category: ts.DiagnosticCategory.Error, key: "JSX element class does not support attributes because it does not have a '{0}' property" }, + The_global_type_JSX_0_may_not_have_more_than_one_property: { code: 2608, category: ts.DiagnosticCategory.Error, key: "The global type 'JSX.{0}' may not have more than one property" }, + Cannot_emit_namespaced_JSX_elements_in_React: { code: 2650, category: ts.DiagnosticCategory.Error, key: "Cannot emit namespaced JSX elements in React" }, + A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: { code: 2651, category: ts.DiagnosticCategory.Error, key: "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums." }, + Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: { code: 2652, category: ts.DiagnosticCategory.Error, key: "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead." }, + Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: { code: 2653, category: ts.DiagnosticCategory.Error, key: "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'." }, + Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: { code: 2654, category: ts.DiagnosticCategory.Error, key: "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition." }, + Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: { code: 2656, category: ts.DiagnosticCategory.Error, key: "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition." }, + Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import declaration '{0}' is using private name '{1}'." }, + Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, + Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, + Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4006, category: ts.DiagnosticCategory.Error, key: "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." }, + Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4008, category: ts.DiagnosticCategory.Error, key: "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'." }, + Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 4010, category: ts.DiagnosticCategory.Error, key: "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'." }, + Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 4012, category: ts.DiagnosticCategory.Error, key: "Type parameter '{0}' of public method from exported class has or is using private name '{1}'." }, + Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 4014, category: ts.DiagnosticCategory.Error, key: "Type parameter '{0}' of method from exported interface has or is using private name '{1}'." }, + Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4016, category: ts.DiagnosticCategory.Error, key: "Type parameter '{0}' of exported function has or is using private name '{1}'." }, + Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4019, category: ts.DiagnosticCategory.Error, key: "Implements clause of exported class '{0}' has or is using private name '{1}'." }, + Extends_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4020, category: ts.DiagnosticCategory.Error, key: "Extends clause of exported class '{0}' has or is using private name '{1}'." }, + Extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: { code: 4022, category: ts.DiagnosticCategory.Error, key: "Extends clause of exported interface '{0}' has or is using private name '{1}'." }, + Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4023, category: ts.DiagnosticCategory.Error, key: "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named." }, + Exported_variable_0_has_or_is_using_name_1_from_private_module_2: { code: 4024, category: ts.DiagnosticCategory.Error, key: "Exported variable '{0}' has or is using name '{1}' from private module '{2}'." }, + Exported_variable_0_has_or_is_using_private_name_1: { code: 4025, category: ts.DiagnosticCategory.Error, key: "Exported variable '{0}' has or is using private name '{1}'." }, + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4026, category: ts.DiagnosticCategory.Error, key: "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." }, + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4027, category: ts.DiagnosticCategory.Error, key: "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'." }, + Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 4028, category: ts.DiagnosticCategory.Error, key: "Public static property '{0}' of exported class has or is using private name '{1}'." }, + Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4029, category: ts.DiagnosticCategory.Error, key: "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." }, + Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4030, category: ts.DiagnosticCategory.Error, key: "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'." }, + Public_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 4031, category: ts.DiagnosticCategory.Error, key: "Public property '{0}' of exported class has or is using private name '{1}'." }, + Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4032, category: ts.DiagnosticCategory.Error, key: "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'." }, + Property_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4033, category: ts.DiagnosticCategory.Error, key: "Property '{0}' of exported interface has or is using private name '{1}'." }, + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4034, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'." }, + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 4035, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'." }, + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4036, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'." }, + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 4037, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'." }, + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4038, category: ts.DiagnosticCategory.Error, key: "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." }, + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4039, category: ts.DiagnosticCategory.Error, key: "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'." }, + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 4040, category: ts.DiagnosticCategory.Error, key: "Return type of public static property getter from exported class has or is using private name '{0}'." }, + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4041, category: ts.DiagnosticCategory.Error, key: "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." }, + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4042, category: ts.DiagnosticCategory.Error, key: "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'." }, + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 4043, category: ts.DiagnosticCategory.Error, key: "Return type of public property getter from exported class has or is using private name '{0}'." }, + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4044, category: ts.DiagnosticCategory.Error, key: "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'." }, + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4045, category: ts.DiagnosticCategory.Error, key: "Return type of constructor signature from exported interface has or is using private name '{0}'." }, + Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4046, category: ts.DiagnosticCategory.Error, key: "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'." }, + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4047, category: ts.DiagnosticCategory.Error, key: "Return type of call signature from exported interface has or is using private name '{0}'." }, + Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4048, category: ts.DiagnosticCategory.Error, key: "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'." }, + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4049, category: ts.DiagnosticCategory.Error, key: "Return type of index signature from exported interface has or is using private name '{0}'." }, + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4050, category: ts.DiagnosticCategory.Error, key: "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named." }, + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4051, category: ts.DiagnosticCategory.Error, key: "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'." }, + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: { code: 4052, category: ts.DiagnosticCategory.Error, key: "Return type of public static method from exported class has or is using private name '{0}'." }, + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4053, category: ts.DiagnosticCategory.Error, key: "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named." }, + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4054, category: ts.DiagnosticCategory.Error, key: "Return type of public method from exported class has or is using name '{0}' from private module '{1}'." }, + Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: { code: 4055, category: ts.DiagnosticCategory.Error, key: "Return type of public method from exported class has or is using private name '{0}'." }, + Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4056, category: ts.DiagnosticCategory.Error, key: "Return type of method from exported interface has or is using name '{0}' from private module '{1}'." }, + Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: { code: 4057, category: ts.DiagnosticCategory.Error, key: "Return type of method from exported interface has or is using private name '{0}'." }, + Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4058, category: ts.DiagnosticCategory.Error, key: "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named." }, + Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: { code: 4059, category: ts.DiagnosticCategory.Error, key: "Return type of exported function has or is using name '{0}' from private module '{1}'." }, + Return_type_of_exported_function_has_or_is_using_private_name_0: { code: 4060, category: ts.DiagnosticCategory.Error, key: "Return type of exported function has or is using private name '{0}'." }, + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4061, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named." }, + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4062, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'." }, + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: { code: 4063, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of constructor from exported class has or is using private name '{1}'." }, + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4064, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'." }, + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4065, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." }, + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4066, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'." }, + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4067, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'." }, + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4068, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named." }, + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4069, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'." }, + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 4070, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of public static method from exported class has or is using private name '{1}'." }, + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4071, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named." }, + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4072, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'." }, + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 4073, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of public method from exported class has or is using private name '{1}'." }, + Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4074, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'." }, + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 4075, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of method from exported interface has or is using private name '{1}'." }, + Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4076, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named." }, + Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: { code: 4077, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'." }, + Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' of exported function has or is using private name '{1}'." }, + Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported type alias '{0}' has or is using private name '{1}'." }, + Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default export of the module has or is using private name '{0}'." }, + Loop_contains_block_scoped_variable_0_referenced_by_a_function_in_the_loop_This_is_only_supported_in_ECMAScript_6_or_higher: { code: 4091, category: ts.DiagnosticCategory.Error, key: "Loop contains block-scoped variable '{0}' referenced by a function in the loop. This is only supported in ECMAScript 6 or higher." }, + The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The current host does not support the '{0}' option." }, + Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot find the common subdirectory path for the input files." }, + Cannot_read_file_0_Colon_1: { code: 5012, category: ts.DiagnosticCategory.Error, key: "Cannot read file '{0}': {1}" }, + Unsupported_file_encoding: { code: 5013, category: ts.DiagnosticCategory.Error, key: "Unsupported file encoding." }, + Failed_to_parse_file_0_Colon_1: { code: 5014, category: ts.DiagnosticCategory.Error, key: "Failed to parse file '{0}': {1}." }, + Unknown_compiler_option_0: { code: 5023, category: ts.DiagnosticCategory.Error, key: "Unknown compiler option '{0}'." }, + Compiler_option_0_requires_a_value_of_type_1: { code: 5024, category: ts.DiagnosticCategory.Error, key: "Compiler option '{0}' requires a value of type {1}." }, + Could_not_write_file_0_Colon_1: { code: 5033, category: ts.DiagnosticCategory.Error, key: "Could not write file '{0}': {1}" }, + Option_project_cannot_be_mixed_with_source_files_on_a_command_line: { code: 5042, category: ts.DiagnosticCategory.Error, key: "Option 'project' cannot be mixed with source files on a command line." }, + Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher: { code: 5047, category: ts.DiagnosticCategory.Error, key: "Option 'isolatedModules' can only be used when either option'--module' is provided or option 'target' is 'ES6' or higher." }, + Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: { code: 5051, category: ts.DiagnosticCategory.Error, key: "Option 'inlineSources' can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided." }, + Option_0_cannot_be_specified_without_specifying_option_1: { code: 5052, category: ts.DiagnosticCategory.Error, key: "Option '{0}' cannot be specified without specifying option '{1}'." }, + Option_0_cannot_be_specified_with_option_1: { code: 5053, category: ts.DiagnosticCategory.Error, key: "Option '{0}' cannot be specified with option '{1}'." }, + A_tsconfig_json_file_is_already_defined_at_Colon_0: { code: 5054, category: ts.DiagnosticCategory.Error, key: "A 'tsconfig.json' file is already defined at: '{0}'." }, + Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate and emit output to single file." }, + Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates corresponding '.d.ts' file." }, + Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specifies the location where debugger should locate map files instead of generated locations." }, + Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: { code: 6004, category: ts.DiagnosticCategory.Message, key: "Specifies the location where debugger should locate TypeScript files instead of source locations." }, + Watch_input_files: { code: 6005, category: ts.DiagnosticCategory.Message, key: "Watch input files." }, + Redirect_output_structure_to_the_directory: { code: 6006, category: ts.DiagnosticCategory.Message, key: "Redirect output structure to the directory." }, + Do_not_erase_const_enum_declarations_in_generated_code: { code: 6007, category: ts.DiagnosticCategory.Message, key: "Do not erase const enum declarations in generated code." }, + Do_not_emit_outputs_if_any_errors_were_reported: { code: 6008, category: ts.DiagnosticCategory.Message, key: "Do not emit outputs if any errors were reported." }, + Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do not emit comments to output." }, + Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do not emit outputs." }, + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES6_experimental: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES6' (experimental)" }, + Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es6: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es6'" }, + Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print this message." }, + Print_the_compiler_s_version: { code: 6019, category: ts.DiagnosticCategory.Message, key: "Print the compiler's version." }, + Compile_the_project_in_the_given_directory: { code: 6020, category: ts.DiagnosticCategory.Message, key: "Compile the project in the given directory." }, + Syntax_Colon_0: { code: 6023, category: ts.DiagnosticCategory.Message, key: "Syntax: {0}" }, + options: { code: 6024, category: ts.DiagnosticCategory.Message, key: "options" }, + file: { code: 6025, category: ts.DiagnosticCategory.Message, key: "file" }, + Examples_Colon_0: { code: 6026, category: ts.DiagnosticCategory.Message, key: "Examples: {0}" }, + Options_Colon: { code: 6027, category: ts.DiagnosticCategory.Message, key: "Options:" }, + Version_0: { code: 6029, category: ts.DiagnosticCategory.Message, key: "Version {0}" }, + Insert_command_line_options_and_files_from_a_file: { code: 6030, category: ts.DiagnosticCategory.Message, key: "Insert command line options and files from a file." }, + File_change_detected_Starting_incremental_compilation: { code: 6032, category: ts.DiagnosticCategory.Message, key: "File change detected. Starting incremental compilation..." }, + KIND: { code: 6034, category: ts.DiagnosticCategory.Message, key: "KIND" }, + FILE: { code: 6035, category: ts.DiagnosticCategory.Message, key: "FILE" }, + VERSION: { code: 6036, category: ts.DiagnosticCategory.Message, key: "VERSION" }, + LOCATION: { code: 6037, category: ts.DiagnosticCategory.Message, key: "LOCATION" }, + DIRECTORY: { code: 6038, category: ts.DiagnosticCategory.Message, key: "DIRECTORY" }, + Compilation_complete_Watching_for_file_changes: { code: 6042, category: ts.DiagnosticCategory.Message, key: "Compilation complete. Watching for file changes." }, + Generates_corresponding_map_file: { code: 6043, category: ts.DiagnosticCategory.Message, key: "Generates corresponding '.map' file." }, + Compiler_option_0_expects_an_argument: { code: 6044, category: ts.DiagnosticCategory.Error, key: "Compiler option '{0}' expects an argument." }, + Unterminated_quoted_string_in_response_file_0: { code: 6045, category: ts.DiagnosticCategory.Error, key: "Unterminated quoted string in response file '{0}'." }, + Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es6: { code: 6046, category: ts.DiagnosticCategory.Error, key: "Argument for '--module' option must be 'commonjs', 'amd', 'system', 'umd', or 'es6'." }, + Argument_for_target_option_must_be_ES3_ES5_or_ES6: { code: 6047, category: ts.DiagnosticCategory.Error, key: "Argument for '--target' option must be 'ES3', 'ES5', or 'ES6'." }, + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: { code: 6048, category: ts.DiagnosticCategory.Error, key: "Locale must be of the form or -. For example '{0}' or '{1}'." }, + Unsupported_locale_0: { code: 6049, category: ts.DiagnosticCategory.Error, key: "Unsupported locale '{0}'." }, + Unable_to_open_file_0: { code: 6050, category: ts.DiagnosticCategory.Error, key: "Unable to open file '{0}'." }, + Corrupted_locale_file_0: { code: 6051, category: ts.DiagnosticCategory.Error, key: "Corrupted locale file {0}." }, + Raise_error_on_expressions_and_declarations_with_an_implied_any_type: { code: 6052, category: ts.DiagnosticCategory.Message, key: "Raise error on expressions and declarations with an implied 'any' type." }, + File_0_not_found: { code: 6053, category: ts.DiagnosticCategory.Error, key: "File '{0}' not found." }, + File_0_has_unsupported_extension_The_only_supported_extensions_are_1: { code: 6054, category: ts.DiagnosticCategory.Error, key: "File '{0}' has unsupported extension. The only supported extensions are {1}." }, + Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: { code: 6055, category: ts.DiagnosticCategory.Message, key: "Suppress noImplicitAny errors for indexing objects lacking index signatures." }, + Do_not_emit_declarations_for_code_that_has_an_internal_annotation: { code: 6056, category: ts.DiagnosticCategory.Message, key: "Do not emit declarations for code that has an '@internal' annotation." }, + Specifies_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: { code: 6058, category: ts.DiagnosticCategory.Message, key: "Specifies the root directory of input files. Use to control the output directory structure with --outDir." }, + File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: { code: 6059, category: ts.DiagnosticCategory.Error, key: "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files." }, + Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: { code: 6060, category: ts.DiagnosticCategory.Message, key: "Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)." }, + NEWLINE: { code: 6061, category: ts.DiagnosticCategory.Message, key: "NEWLINE" }, + Argument_for_newLine_option_must_be_CRLF_or_LF: { code: 6062, category: ts.DiagnosticCategory.Error, key: "Argument for '--newLine' option must be 'CRLF' or 'LF'." }, + Argument_for_moduleResolution_option_must_be_node_or_classic: { code: 6063, category: ts.DiagnosticCategory.Error, key: "Argument for '--moduleResolution' option must be 'node' or 'classic'." }, + Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify JSX code generation: 'preserve' or 'react'" }, + Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument for '--jsx' must be 'preserve' or 'react'." }, + Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "Enables experimental support for ES7 decorators." }, + Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: ts.DiagnosticCategory.Message, key: "Enables experimental support for emitting type metadata for decorators." }, + Enables_experimental_support_for_ES7_async_functions: { code: 6068, category: ts.DiagnosticCategory.Message, key: "Enables experimental support for ES7 async functions." }, + Specifies_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: { code: 6069, category: ts.DiagnosticCategory.Message, key: "Specifies module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)." }, + Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: { code: 6070, category: ts.DiagnosticCategory.Message, key: "Initializes a TypeScript project and creates a tsconfig.json file." }, + Successfully_created_a_tsconfig_json_file: { code: 6071, category: ts.DiagnosticCategory.Message, key: "Successfully created a tsconfig.json file." }, + Suppress_excess_property_checks_for_object_literals: { code: 6072, category: ts.DiagnosticCategory.Message, key: "Suppress excess property checks for object literals." }, + Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable '{0}' implicitly has an '{1}' type." }, + Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' implicitly has an '{1}' type." }, + Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member '{0}' implicitly has an '{1}' type." }, + new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: { code: 7009, category: ts.DiagnosticCategory.Error, key: "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type." }, + _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: { code: 7010, category: ts.DiagnosticCategory.Error, key: "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type." }, + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, + Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Property '{0}' implicitly has type 'any', because its 'set' accessor lacks a type annotation." }, + Index_signature_of_object_type_implicitly_has_an_any_type: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Index signature of object type implicitly has an 'any' type." }, + Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object literal's property '{0}' implicitly has an '{1}' type." }, + Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest parameter '{0}' implicitly has an 'any[]' type." }, + Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: ts.DiagnosticCategory.Error, key: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, + _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: { code: 7022, category: ts.DiagnosticCategory.Error, key: "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer." }, + _0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7023, category: ts.DiagnosticCategory.Error, key: "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." }, + Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7024, category: ts.DiagnosticCategory.Error, key: "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." }, + Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: { code: 7025, category: ts.DiagnosticCategory.Error, key: "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type." }, + JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: { code: 7026, category: ts.DiagnosticCategory.Error, key: "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists" }, + You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You cannot rename this element." }, + You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You cannot rename elements that are defined in the standard TypeScript library." }, + import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "'import ... =' can only be used in a .ts file." }, + export_can_only_be_used_in_a_ts_file: { code: 8003, category: ts.DiagnosticCategory.Error, key: "'export=' can only be used in a .ts file." }, + type_parameter_declarations_can_only_be_used_in_a_ts_file: { code: 8004, category: ts.DiagnosticCategory.Error, key: "'type parameter declarations' can only be used in a .ts file." }, + implements_clauses_can_only_be_used_in_a_ts_file: { code: 8005, category: ts.DiagnosticCategory.Error, key: "'implements clauses' can only be used in a .ts file." }, + interface_declarations_can_only_be_used_in_a_ts_file: { code: 8006, category: ts.DiagnosticCategory.Error, key: "'interface declarations' can only be used in a .ts file." }, + module_declarations_can_only_be_used_in_a_ts_file: { code: 8007, category: ts.DiagnosticCategory.Error, key: "'module declarations' can only be used in a .ts file." }, + type_aliases_can_only_be_used_in_a_ts_file: { code: 8008, category: ts.DiagnosticCategory.Error, key: "'type aliases' can only be used in a .ts file." }, + _0_can_only_be_used_in_a_ts_file: { code: 8009, category: ts.DiagnosticCategory.Error, key: "'{0}' can only be used in a .ts file." }, + types_can_only_be_used_in_a_ts_file: { code: 8010, category: ts.DiagnosticCategory.Error, key: "'types' can only be used in a .ts file." }, + type_arguments_can_only_be_used_in_a_ts_file: { code: 8011, category: ts.DiagnosticCategory.Error, key: "'type arguments' can only be used in a .ts file." }, + parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: ts.DiagnosticCategory.Error, key: "'parameter modifiers' can only be used in a .ts file." }, + property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: ts.DiagnosticCategory.Error, key: "'property declarations' can only be used in a .ts file." }, + enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "'enum declarations' can only be used in a .ts file." }, + type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "'type assertion expressions' can only be used in a .ts file." }, + decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: ts.DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." }, + Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, + class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "'class' expressions are not currently supported." }, + JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: ts.DiagnosticCategory.Error, key: "JSX attributes must only be assigned a non-empty 'expression'." }, + JSX_elements_cannot_have_multiple_attributes_with_the_same_name: { code: 17001, category: ts.DiagnosticCategory.Error, key: "JSX elements cannot have multiple attributes with the same name." }, + Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: ts.DiagnosticCategory.Error, key: "Expected corresponding JSX closing tag for '{0}'." }, + JSX_attribute_expected: { code: 17003, category: ts.DiagnosticCategory.Error, key: "JSX attribute expected." }, + Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: ts.DiagnosticCategory.Error, key: "Cannot use JSX unless the '--jsx' flag is provided." }, + A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: ts.DiagnosticCategory.Error, key: "A constructor cannot contain a 'super' call when its class extends 'null'" }, + An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17006, category: ts.DiagnosticCategory.Error, key: "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." } + }; +})(ts || (ts = {})); +/// +/// +var ts; +(function (ts) { + /* @internal */ + function tokenIsIdentifierOrKeyword(token) { + return token >= 69 /* Identifier */; + } + ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword; + var textToToken = { + "abstract": 115 /* AbstractKeyword */, + "any": 117 /* AnyKeyword */, + "as": 116 /* AsKeyword */, + "boolean": 120 /* BooleanKeyword */, + "break": 70 /* BreakKeyword */, + "case": 71 /* CaseKeyword */, + "catch": 72 /* CatchKeyword */, + "class": 73 /* ClassKeyword */, + "continue": 75 /* ContinueKeyword */, + "const": 74 /* ConstKeyword */, + "constructor": 121 /* ConstructorKeyword */, + "debugger": 76 /* DebuggerKeyword */, + "declare": 122 /* DeclareKeyword */, + "default": 77 /* DefaultKeyword */, + "delete": 78 /* DeleteKeyword */, + "do": 79 /* DoKeyword */, + "else": 80 /* ElseKeyword */, + "enum": 81 /* EnumKeyword */, + "export": 82 /* ExportKeyword */, + "extends": 83 /* ExtendsKeyword */, + "false": 84 /* FalseKeyword */, + "finally": 85 /* FinallyKeyword */, + "for": 86 /* ForKeyword */, + "from": 133 /* FromKeyword */, + "function": 87 /* FunctionKeyword */, + "get": 123 /* GetKeyword */, + "if": 88 /* IfKeyword */, + "implements": 106 /* ImplementsKeyword */, + "import": 89 /* ImportKeyword */, + "in": 90 /* InKeyword */, + "instanceof": 91 /* InstanceOfKeyword */, + "interface": 107 /* InterfaceKeyword */, + "is": 124 /* IsKeyword */, + "let": 108 /* LetKeyword */, + "module": 125 /* ModuleKeyword */, + "namespace": 126 /* NamespaceKeyword */, + "new": 92 /* NewKeyword */, + "null": 93 /* NullKeyword */, + "number": 128 /* NumberKeyword */, + "package": 109 /* PackageKeyword */, + "private": 110 /* PrivateKeyword */, + "protected": 111 /* ProtectedKeyword */, + "public": 112 /* PublicKeyword */, + "require": 127 /* RequireKeyword */, + "return": 94 /* ReturnKeyword */, + "set": 129 /* SetKeyword */, + "static": 113 /* StaticKeyword */, + "string": 130 /* StringKeyword */, + "super": 95 /* SuperKeyword */, + "switch": 96 /* SwitchKeyword */, + "symbol": 131 /* SymbolKeyword */, + "this": 97 /* ThisKeyword */, + "throw": 98 /* ThrowKeyword */, + "true": 99 /* TrueKeyword */, + "try": 100 /* TryKeyword */, + "type": 132 /* TypeKeyword */, + "typeof": 101 /* TypeOfKeyword */, + "var": 102 /* VarKeyword */, + "void": 103 /* VoidKeyword */, + "while": 104 /* WhileKeyword */, + "with": 105 /* WithKeyword */, + "yield": 114 /* YieldKeyword */, + "async": 118 /* AsyncKeyword */, + "await": 119 /* AwaitKeyword */, + "of": 134 /* OfKeyword */, + "{": 15 /* OpenBraceToken */, + "}": 16 /* CloseBraceToken */, + "(": 17 /* OpenParenToken */, + ")": 18 /* CloseParenToken */, + "[": 19 /* OpenBracketToken */, + "]": 20 /* CloseBracketToken */, + ".": 21 /* DotToken */, + "...": 22 /* DotDotDotToken */, + ";": 23 /* SemicolonToken */, + ",": 24 /* CommaToken */, + "<": 25 /* LessThanToken */, + ">": 27 /* GreaterThanToken */, + "<=": 28 /* LessThanEqualsToken */, + ">=": 29 /* GreaterThanEqualsToken */, + "==": 30 /* EqualsEqualsToken */, + "!=": 31 /* ExclamationEqualsToken */, + "===": 32 /* EqualsEqualsEqualsToken */, + "!==": 33 /* ExclamationEqualsEqualsToken */, + "=>": 34 /* EqualsGreaterThanToken */, + "+": 35 /* PlusToken */, + "-": 36 /* MinusToken */, + "**": 38 /* AsteriskAsteriskToken */, + "*": 37 /* AsteriskToken */, + "/": 39 /* SlashToken */, + "%": 40 /* PercentToken */, + "++": 41 /* PlusPlusToken */, + "--": 42 /* MinusMinusToken */, + "<<": 43 /* LessThanLessThanToken */, + ">": 44 /* GreaterThanGreaterThanToken */, + ">>>": 45 /* GreaterThanGreaterThanGreaterThanToken */, + "&": 46 /* AmpersandToken */, + "|": 47 /* BarToken */, + "^": 48 /* CaretToken */, + "!": 49 /* ExclamationToken */, + "~": 50 /* TildeToken */, + "&&": 51 /* AmpersandAmpersandToken */, + "||": 52 /* BarBarToken */, + "?": 53 /* QuestionToken */, + ":": 54 /* ColonToken */, + "=": 56 /* EqualsToken */, + "+=": 57 /* PlusEqualsToken */, + "-=": 58 /* MinusEqualsToken */, + "*=": 59 /* AsteriskEqualsToken */, + "**=": 60 /* AsteriskAsteriskEqualsToken */, + "/=": 61 /* SlashEqualsToken */, + "%=": 62 /* PercentEqualsToken */, + "<<=": 63 /* LessThanLessThanEqualsToken */, + ">>=": 64 /* GreaterThanGreaterThanEqualsToken */, + ">>>=": 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */, + "&=": 66 /* AmpersandEqualsToken */, + "|=": 67 /* BarEqualsToken */, + "^=": 68 /* CaretEqualsToken */, + "@": 55 /* AtToken */ + }; + /* + As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers + IdentifierStart :: + Can contain Unicode 3.0.0 categories: + Uppercase letter (Lu), + Lowercase letter (Ll), + Titlecase letter (Lt), + Modifier letter (Lm), + Other letter (Lo), or + Letter number (Nl). + IdentifierPart :: = + Can contain IdentifierStart + Unicode 3.0.0 categories: + Non-spacing mark (Mn), + Combining spacing mark (Mc), + Decimal number (Nd), or + Connector punctuation (Pc). + + Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at: + http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt + */ + var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + /* + As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers + IdentifierStart :: + Can contain Unicode 6.2 categories: + Uppercase letter (Lu), + Lowercase letter (Ll), + Titlecase letter (Lt), + Modifier letter (Lm), + Other letter (Lo), or + Letter number (Nl). + IdentifierPart :: + Can contain IdentifierStart + Unicode 6.2 categories: + Non-spacing mark (Mn), + Combining spacing mark (Mc), + Decimal number (Nd), + Connector punctuation (Pc), + , or + . + + Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at: + http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt + */ + var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + var unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; + function lookupInUnicodeMap(code, map) { + // Bail out quickly if it couldn't possibly be in the map. + if (code < map[0]) { + return false; + } + // Perform binary search in one of the Unicode range maps + var lo = 0; + var hi = map.length; + var mid; + while (lo + 1 < hi) { + mid = lo + (hi - lo) / 2; + // mid has to be even to catch a range's beginning + mid -= mid % 2; + if (map[mid] <= code && code <= map[mid + 1]) { + return true; + } + if (code < map[mid]) { + hi = mid; + } + else { + lo = mid + 2; + } + } + return false; + } + /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) { + return languageVersion >= 1 /* ES5 */ ? + lookupInUnicodeMap(code, unicodeES5IdentifierStart) : + lookupInUnicodeMap(code, unicodeES3IdentifierStart); + } + ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart; + function isUnicodeIdentifierPart(code, languageVersion) { + return languageVersion >= 1 /* ES5 */ ? + lookupInUnicodeMap(code, unicodeES5IdentifierPart) : + lookupInUnicodeMap(code, unicodeES3IdentifierPart); + } + function makeReverseMap(source) { + var result = []; + for (var name_4 in source) { + if (source.hasOwnProperty(name_4)) { + result[source[name_4]] = name_4; + } + } + return result; + } + var tokenStrings = makeReverseMap(textToToken); + function tokenToString(t) { + return tokenStrings[t]; + } + ts.tokenToString = tokenToString; + /* @internal */ + function stringToToken(s) { + return textToToken[s]; + } + ts.stringToToken = stringToToken; + /* @internal */ + function computeLineStarts(text) { + var result = new Array(); + var pos = 0; + var lineStart = 0; + while (pos < text.length) { + var ch = text.charCodeAt(pos++); + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + case 10 /* lineFeed */: + result.push(lineStart); + lineStart = pos; + break; + default: + if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) { + result.push(lineStart); + lineStart = pos; + } + break; + } + } + result.push(lineStart); + return result; + } + ts.computeLineStarts = computeLineStarts; + function getPositionOfLineAndCharacter(sourceFile, line, character) { + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character); + } + ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; + /* @internal */ + function computePositionOfLineAndCharacter(lineStarts, line, character) { + ts.Debug.assert(line >= 0 && line < lineStarts.length); + return lineStarts[line] + character; + } + ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter; + /* @internal */ + function getLineStarts(sourceFile) { + return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text)); + } + ts.getLineStarts = getLineStarts; + /* @internal */ + /** + * We assume the first line starts at position 0 and 'position' is non-negative. + */ + function computeLineAndCharacterOfPosition(lineStarts, position) { + var lineNumber = ts.binarySearch(lineStarts, position); + if (lineNumber < 0) { + // If the actual position was not found, + // the binary search returns the 2's-complement of the next line start + // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20 + // then the search will return -2. + // + // We want the index of the previous line start, so we subtract 1. + // Review 2's-complement if this is confusing. + lineNumber = ~lineNumber - 1; + ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file"); + } + return { + line: lineNumber, + character: position - lineStarts[lineNumber] + }; + } + ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition; + function getLineAndCharacterOfPosition(sourceFile, position) { + return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position); + } + ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition; + var hasOwnProperty = Object.prototype.hasOwnProperty; + function isWhiteSpace(ch) { + // Note: nextLine is in the Zs space, and should be considered to be a whitespace. + // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript. + return ch === 32 /* space */ || + ch === 9 /* tab */ || + ch === 11 /* verticalTab */ || + ch === 12 /* formFeed */ || + ch === 160 /* nonBreakingSpace */ || + ch === 133 /* nextLine */ || + ch === 5760 /* ogham */ || + ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ || + ch === 8239 /* narrowNoBreakSpace */ || + ch === 8287 /* mathematicalSpace */ || + ch === 12288 /* ideographicSpace */ || + ch === 65279 /* byteOrderMark */; + } + ts.isWhiteSpace = isWhiteSpace; + function isLineBreak(ch) { + // ES5 7.3: + // The ECMAScript line terminator characters are listed in Table 3. + // Table 3: Line Terminator Characters + // Code Unit Value Name Formal Name + // \u000A Line Feed + // \u000D Carriage Return + // \u2028 Line separator + // \u2029 Paragraph separator + // Only the characters in Table 3 are treated as line terminators. Other new line or line + // breaking characters are treated as white space but not as line terminators. + return ch === 10 /* lineFeed */ || + ch === 13 /* carriageReturn */ || + ch === 8232 /* lineSeparator */ || + ch === 8233 /* paragraphSeparator */; + } + ts.isLineBreak = isLineBreak; + function isDigit(ch) { + return ch >= 48 /* _0 */ && ch <= 57 /* _9 */; + } + /* @internal */ + function isOctalDigit(ch) { + return ch >= 48 /* _0 */ && ch <= 55 /* _7 */; + } + ts.isOctalDigit = isOctalDigit; + function couldStartTrivia(text, pos) { + // Keep in sync with skipTrivia + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + case 10 /* lineFeed */: + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + case 47 /* slash */: + // starts of normal trivia + case 60 /* lessThan */: + case 61 /* equals */: + case 62 /* greaterThan */: + // Starts of conflict marker trivia + return true; + case 35 /* hash */: + // Only if its the beginning can we have #! trivia + return pos === 0; + default: + return ch > 127 /* maxAsciiCharacter */; + } + } + ts.couldStartTrivia = couldStartTrivia; + /* @internal */ + function skipTrivia(text, pos, stopAfterLineBreak) { + // Keep in sync with couldStartTrivia + while (true) { + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + pos++; + } + case 10 /* lineFeed */: + pos++; + if (stopAfterLineBreak) { + return pos; + } + continue; + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + pos++; + continue; + case 47 /* slash */: + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + continue; + } + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + pos += 2; + while (pos < text.length) { + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + break; + } + pos++; + } + continue; + } + break; + case 60 /* lessThan */: + case 61 /* equals */: + case 62 /* greaterThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos); + continue; + } + break; + case 35 /* hash */: + if (pos === 0 && isShebangTrivia(text, pos)) { + pos = scanShebangTrivia(text, pos); + continue; + } + break; + default: + if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpace(ch) || isLineBreak(ch))) { + pos++; + continue; + } + break; + } + return pos; + } + } + ts.skipTrivia = skipTrivia; + // All conflict markers consist of the same character repeated seven times. If it is + // a <<<<<<< or >>>>>>> marker then it is also followd by a space. + var mergeConflictMarkerLength = "<<<<<<<".length; + function isConflictMarkerTrivia(text, pos) { + ts.Debug.assert(pos >= 0); + // Conflict markers must be at the start of a line. + if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) { + var ch = text.charCodeAt(pos); + if ((pos + mergeConflictMarkerLength) < text.length) { + for (var i = 0, n = mergeConflictMarkerLength; i < n; i++) { + if (text.charCodeAt(pos + i) !== ch) { + return false; + } + } + return ch === 61 /* equals */ || + text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */; + } + } + return false; + } + function scanConflictMarkerTrivia(text, pos, error) { + if (error) { + error(ts.Diagnostics.Merge_conflict_marker_encountered, mergeConflictMarkerLength); + } + var ch = text.charCodeAt(pos); + var len = text.length; + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + while (pos < len && !isLineBreak(text.charCodeAt(pos))) { + pos++; + } + } + else { + ts.Debug.assert(ch === 61 /* equals */); + // Consume everything from the start of the mid-conlict marker to the start of the next + // end-conflict marker. + while (pos < len) { + var ch_1 = text.charCodeAt(pos); + if (ch_1 === 62 /* greaterThan */ && isConflictMarkerTrivia(text, pos)) { + break; + } + pos++; + } + } + return pos; + } + var shebangTriviaRegex = /^#!.*/; + function isShebangTrivia(text, pos) { + // Shebangs check must only be done at the start of the file + ts.Debug.assert(pos === 0); + return shebangTriviaRegex.test(text); + } + function scanShebangTrivia(text, pos) { + var shebang = shebangTriviaRegex.exec(text)[0]; + pos = pos + shebang.length; + return pos; + } + /** + * Extract comments from text prefixing the token closest following `pos`. + * The return value is an array containing a TextRange for each comment. + * Single-line comment ranges include the beginning '//' characters but not the ending line break. + * Multi - line comment ranges include the beginning '/* and ending '/' characters. + * The return value is undefined if no comments were found. + * @param trailing + * If false, whitespace is skipped until the first line break and comments between that location + * and the next token are returned. + * If true, comments occurring between the given position and the next line break are returned. + */ + function getCommentRanges(text, pos, trailing) { + var result; + var collecting = trailing || pos === 0; + while (true) { + var ch = text.charCodeAt(pos); + switch (ch) { + case 13 /* carriageReturn */: + if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + pos++; + } + case 10 /* lineFeed */: + pos++; + if (trailing) { + return result; + } + collecting = true; + if (result && result.length) { + ts.lastOrUndefined(result).hasTrailingNewLine = true; + } + continue; + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + pos++; + continue; + case 47 /* slash */: + var nextChar = text.charCodeAt(pos + 1); + var hasTrailingNewLine = false; + if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) { + var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */; + var startPos = pos; + pos += 2; + if (nextChar === 47 /* slash */) { + while (pos < text.length) { + if (isLineBreak(text.charCodeAt(pos))) { + hasTrailingNewLine = true; + break; + } + pos++; + } + } + else { + while (pos < text.length) { + if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + break; + } + pos++; + } + } + if (collecting) { + if (!result) { + result = []; + } + result.push({ pos: startPos, end: pos, hasTrailingNewLine: hasTrailingNewLine, kind: kind }); + } + continue; + } + break; + default: + if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpace(ch) || isLineBreak(ch))) { + if (result && result.length && isLineBreak(ch)) { + ts.lastOrUndefined(result).hasTrailingNewLine = true; + } + pos++; + continue; + } + break; + } + return result; + } + } + function getLeadingCommentRanges(text, pos) { + return getCommentRanges(text, pos, /*trailing*/ false); + } + ts.getLeadingCommentRanges = getLeadingCommentRanges; + function getTrailingCommentRanges(text, pos) { + return getCommentRanges(text, pos, /*trailing*/ true); + } + ts.getTrailingCommentRanges = getTrailingCommentRanges; + /** Optionally, get the shebang */ + function getShebang(text) { + return shebangTriviaRegex.test(text) + ? shebangTriviaRegex.exec(text)[0] + : undefined; + } + ts.getShebang = getShebang; + function isIdentifierStart(ch, languageVersion) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || + ch === 36 /* $ */ || ch === 95 /* _ */ || + ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion); + } + ts.isIdentifierStart = isIdentifierStart; + function isIdentifierPart(ch, languageVersion) { + return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || + ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ || + ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); + } + ts.isIdentifierPart = isIdentifierPart; + // Creates a scanner over a (possibly unspecified) range of a piece of text. + function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { + if (languageVariant === void 0) { languageVariant = 0 /* Standard */; } + // Current position (end position of text of current token) + var pos; + // end of text + var end; + // Start position of whitespace before current token + var startPos; + // Start position of text of current token + var tokenPos; + var token; + var tokenValue; + var precedingLineBreak; + var hasExtendedUnicodeEscape; + var tokenIsUnterminated; + setText(text, start, length); + return { + getStartPos: function () { return startPos; }, + getTextPos: function () { return pos; }, + getToken: function () { return token; }, + getTokenPos: function () { return tokenPos; }, + getTokenText: function () { return text.substring(tokenPos, pos); }, + getTokenValue: function () { return tokenValue; }, + hasExtendedUnicodeEscape: function () { return hasExtendedUnicodeEscape; }, + hasPrecedingLineBreak: function () { return precedingLineBreak; }, + isIdentifier: function () { return token === 69 /* Identifier */ || token > 105 /* LastReservedWord */; }, + isReservedWord: function () { return token >= 70 /* FirstReservedWord */ && token <= 105 /* LastReservedWord */; }, + isUnterminated: function () { return tokenIsUnterminated; }, + reScanGreaterToken: reScanGreaterToken, + reScanSlashToken: reScanSlashToken, + reScanTemplateToken: reScanTemplateToken, + scanJsxIdentifier: scanJsxIdentifier, + reScanJsxToken: reScanJsxToken, + scanJsxToken: scanJsxToken, + scan: scan, + setText: setText, + setScriptTarget: setScriptTarget, + setLanguageVariant: setLanguageVariant, + setOnError: setOnError, + setTextPos: setTextPos, + tryScan: tryScan, + lookAhead: lookAhead + }; + function error(message, length) { + if (onError) { + onError(message, length || 0); + } + } + function scanNumber() { + var start = pos; + while (isDigit(text.charCodeAt(pos))) + pos++; + if (text.charCodeAt(pos) === 46 /* dot */) { + pos++; + while (isDigit(text.charCodeAt(pos))) + pos++; + } + var end = pos; + if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) { + pos++; + if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) + pos++; + if (isDigit(text.charCodeAt(pos))) { + pos++; + while (isDigit(text.charCodeAt(pos))) + pos++; + end = pos; + } + else { + error(ts.Diagnostics.Digit_expected); + } + } + return +(text.substring(start, end)); + } + function scanOctalDigits() { + var start = pos; + while (isOctalDigit(text.charCodeAt(pos))) { + pos++; + } + return +(text.substring(start, pos)); + } + /** + * Scans the given number of hexadecimal digits in the text, + * returning -1 if the given number is unavailable. + */ + function scanExactNumberOfHexDigits(count) { + return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false); + } + /** + * Scans as many hexadecimal digits as are available in the text, + * returning -1 if the given number of digits was unavailable. + */ + function scanMinimumNumberOfHexDigits(count) { + return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true); + } + function scanHexDigits(minCount, scanAsManyAsPossible) { + var digits = 0; + var value = 0; + while (digits < minCount || scanAsManyAsPossible) { + var ch = text.charCodeAt(pos); + if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) { + value = value * 16 + ch - 48 /* _0 */; + } + else if (ch >= 65 /* A */ && ch <= 70 /* F */) { + value = value * 16 + ch - 65 /* A */ + 10; + } + else if (ch >= 97 /* a */ && ch <= 102 /* f */) { + value = value * 16 + ch - 97 /* a */ + 10; + } + else { + break; + } + pos++; + digits++; + } + if (digits < minCount) { + value = -1; + } + return value; + } + function scanString() { + var quote = text.charCodeAt(pos++); + var result = ""; + var start = pos; + while (true) { + if (pos >= end) { + result += text.substring(start, pos); + tokenIsUnterminated = true; + error(ts.Diagnostics.Unterminated_string_literal); + break; + } + var ch = text.charCodeAt(pos); + if (ch === quote) { + result += text.substring(start, pos); + pos++; + break; + } + if (ch === 92 /* backslash */) { + result += text.substring(start, pos); + result += scanEscapeSequence(); + start = pos; + continue; + } + if (isLineBreak(ch)) { + result += text.substring(start, pos); + tokenIsUnterminated = true; + error(ts.Diagnostics.Unterminated_string_literal); + break; + } + pos++; + } + return result; + } + /** + * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or + * a literal component of a TemplateExpression. + */ + function scanTemplateAndSetTokenValue() { + var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */; + pos++; + var start = pos; + var contents = ""; + var resultingToken; + while (true) { + if (pos >= end) { + contents += text.substring(start, pos); + tokenIsUnterminated = true; + error(ts.Diagnostics.Unterminated_template_literal); + resultingToken = startedWithBacktick ? 11 /* NoSubstitutionTemplateLiteral */ : 14 /* TemplateTail */; + break; + } + var currChar = text.charCodeAt(pos); + // '`' + if (currChar === 96 /* backtick */) { + contents += text.substring(start, pos); + pos++; + resultingToken = startedWithBacktick ? 11 /* NoSubstitutionTemplateLiteral */ : 14 /* TemplateTail */; + break; + } + // '${' + if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) { + contents += text.substring(start, pos); + pos += 2; + resultingToken = startedWithBacktick ? 12 /* TemplateHead */ : 13 /* TemplateMiddle */; + break; + } + // Escape character + if (currChar === 92 /* backslash */) { + contents += text.substring(start, pos); + contents += scanEscapeSequence(); + start = pos; + continue; + } + // Speculated ECMAScript 6 Spec 11.8.6.1: + // and LineTerminatorSequences are normalized to for Template Values + if (currChar === 13 /* carriageReturn */) { + contents += text.substring(start, pos); + pos++; + if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + contents += "\n"; + start = pos; + continue; + } + pos++; + } + ts.Debug.assert(resultingToken !== undefined); + tokenValue = contents; + return resultingToken; + } + function scanEscapeSequence() { + pos++; + if (pos >= end) { + error(ts.Diagnostics.Unexpected_end_of_text); + return ""; + } + var ch = text.charCodeAt(pos++); + switch (ch) { + case 48 /* _0 */: + return "\0"; + case 98 /* b */: + return "\b"; + case 116 /* t */: + return "\t"; + case 110 /* n */: + return "\n"; + case 118 /* v */: + return "\v"; + case 102 /* f */: + return "\f"; + case 114 /* r */: + return "\r"; + case 39 /* singleQuote */: + return "\'"; + case 34 /* doubleQuote */: + return "\""; + case 117 /* u */: + // '\u{DDDDDDDD}' + if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) { + hasExtendedUnicodeEscape = true; + pos++; + return scanExtendedUnicodeEscape(); + } + // '\uDDDD' + return scanHexadecimalEscape(/*numDigits*/ 4); + case 120 /* x */: + // '\xDD' + return scanHexadecimalEscape(/*numDigits*/ 2); + // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence), + // the line terminator is interpreted to be "the empty code unit sequence". + case 13 /* carriageReturn */: + if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) { + pos++; + } + // fall through + case 10 /* lineFeed */: + case 8232 /* lineSeparator */: + case 8233 /* paragraphSeparator */: + return ""; + default: + return String.fromCharCode(ch); + } + } + function scanHexadecimalEscape(numDigits) { + var escapedValue = scanExactNumberOfHexDigits(numDigits); + if (escapedValue >= 0) { + return String.fromCharCode(escapedValue); + } + else { + error(ts.Diagnostics.Hexadecimal_digit_expected); + return ""; + } + } + function scanExtendedUnicodeEscape() { + var escapedValue = scanMinimumNumberOfHexDigits(1); + var isInvalidExtendedEscape = false; + // Validate the value of the digit + if (escapedValue < 0) { + error(ts.Diagnostics.Hexadecimal_digit_expected); + isInvalidExtendedEscape = true; + } + else if (escapedValue > 0x10FFFF) { + error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive); + isInvalidExtendedEscape = true; + } + if (pos >= end) { + error(ts.Diagnostics.Unexpected_end_of_text); + isInvalidExtendedEscape = true; + } + else if (text.charCodeAt(pos) === 125 /* closeBrace */) { + // Only swallow the following character up if it's a '}'. + pos++; + } + else { + error(ts.Diagnostics.Unterminated_Unicode_escape_sequence); + isInvalidExtendedEscape = true; + } + if (isInvalidExtendedEscape) { + return ""; + } + return utf16EncodeAsString(escapedValue); + } + // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec. + function utf16EncodeAsString(codePoint) { + ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF); + if (codePoint <= 65535) { + return String.fromCharCode(codePoint); + } + var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800; + var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00; + return String.fromCharCode(codeUnit1, codeUnit2); + } + // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX' + // and return code point value if valid Unicode escape is found. Otherwise return -1. + function peekUnicodeEscape() { + if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) { + var start_1 = pos; + pos += 2; + var value = scanExactNumberOfHexDigits(4); + pos = start_1; + return value; + } + return -1; + } + function scanIdentifierParts() { + var result = ""; + var start = pos; + while (pos < end) { + var ch = text.charCodeAt(pos); + if (isIdentifierPart(ch, languageVersion)) { + pos++; + } + else if (ch === 92 /* backslash */) { + ch = peekUnicodeEscape(); + if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) { + break; + } + result += text.substring(start, pos); + result += String.fromCharCode(ch); + // Valid Unicode escape is always six characters + pos += 6; + start = pos; + } + else { + break; + } + } + result += text.substring(start, pos); + return result; + } + function getIdentifierToken() { + // Reserved words are between 2 and 11 characters long and start with a lowercase letter + var len = tokenValue.length; + if (len >= 2 && len <= 11) { + var ch = tokenValue.charCodeAt(0); + if (ch >= 97 /* a */ && ch <= 122 /* z */ && hasOwnProperty.call(textToToken, tokenValue)) { + return token = textToToken[tokenValue]; + } + } + return token = 69 /* Identifier */; + } + function scanBinaryOrOctalDigits(base) { + ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + var value = 0; + // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. + // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. + var numberOfDigits = 0; + while (true) { + var ch = text.charCodeAt(pos); + var valueOfCh = ch - 48 /* _0 */; + if (!isDigit(ch) || valueOfCh >= base) { + break; + } + value = value * base + valueOfCh; + pos++; + numberOfDigits++; + } + // Invalid binaryIntegerLiteral or octalIntegerLiteral + if (numberOfDigits === 0) { + return -1; + } + return value; + } + function scan() { + startPos = pos; + hasExtendedUnicodeEscape = false; + precedingLineBreak = false; + tokenIsUnterminated = false; + while (true) { + tokenPos = pos; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + var ch = text.charCodeAt(pos); + // Special handling for shebang + if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) { + pos = scanShebangTrivia(text, pos); + if (skipTrivia) { + continue; + } + else { + return token = 6 /* ShebangTrivia */; + } + } + switch (ch) { + case 10 /* lineFeed */: + case 13 /* carriageReturn */: + precedingLineBreak = true; + if (skipTrivia) { + pos++; + continue; + } + else { + if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + // consume both CR and LF + pos += 2; + } + else { + pos++; + } + return token = 4 /* NewLineTrivia */; + } + case 9 /* tab */: + case 11 /* verticalTab */: + case 12 /* formFeed */: + case 32 /* space */: + if (skipTrivia) { + pos++; + continue; + } + else { + while (pos < end && isWhiteSpace(text.charCodeAt(pos))) { + pos++; + } + return token = 5 /* WhitespaceTrivia */; + } + case 33 /* exclamation */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 33 /* ExclamationEqualsEqualsToken */; + } + return pos += 2, token = 31 /* ExclamationEqualsToken */; + } + return pos++, token = 49 /* ExclamationToken */; + case 34 /* doubleQuote */: + case 39 /* singleQuote */: + tokenValue = scanString(); + return token = 9 /* StringLiteral */; + case 96 /* backtick */: + return token = scanTemplateAndSetTokenValue(); + case 37 /* percent */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 62 /* PercentEqualsToken */; + } + return pos++, token = 40 /* PercentToken */; + case 38 /* ampersand */: + if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { + return pos += 2, token = 51 /* AmpersandAmpersandToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 66 /* AmpersandEqualsToken */; + } + return pos++, token = 46 /* AmpersandToken */; + case 40 /* openParen */: + return pos++, token = 17 /* OpenParenToken */; + case 41 /* closeParen */: + return pos++, token = 18 /* CloseParenToken */; + case 42 /* asterisk */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 59 /* AsteriskEqualsToken */; + } + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 60 /* AsteriskAsteriskEqualsToken */; + } + return pos += 2, token = 38 /* AsteriskAsteriskToken */; + } + return pos++, token = 37 /* AsteriskToken */; + case 43 /* plus */: + if (text.charCodeAt(pos + 1) === 43 /* plus */) { + return pos += 2, token = 41 /* PlusPlusToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 57 /* PlusEqualsToken */; + } + return pos++, token = 35 /* PlusToken */; + case 44 /* comma */: + return pos++, token = 24 /* CommaToken */; + case 45 /* minus */: + if (text.charCodeAt(pos + 1) === 45 /* minus */) { + return pos += 2, token = 42 /* MinusMinusToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 58 /* MinusEqualsToken */; + } + return pos++, token = 36 /* MinusToken */; + case 46 /* dot */: + if (isDigit(text.charCodeAt(pos + 1))) { + tokenValue = "" + scanNumber(); + return token = 8 /* NumericLiteral */; + } + if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { + return pos += 3, token = 22 /* DotDotDotToken */; + } + return pos++, token = 21 /* DotToken */; + case 47 /* slash */: + // Single-line comment + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + while (pos < end) { + if (isLineBreak(text.charCodeAt(pos))) { + break; + } + pos++; + } + if (skipTrivia) { + continue; + } + else { + return token = 2 /* SingleLineCommentTrivia */; + } + } + // Multi-line comment + if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + pos += 2; + var commentClosed = false; + while (pos < end) { + var ch_2 = text.charCodeAt(pos); + if (ch_2 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + commentClosed = true; + break; + } + if (isLineBreak(ch_2)) { + precedingLineBreak = true; + } + pos++; + } + if (!commentClosed) { + error(ts.Diagnostics.Asterisk_Slash_expected); + } + if (skipTrivia) { + continue; + } + else { + tokenIsUnterminated = !commentClosed; + return token = 3 /* MultiLineCommentTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 61 /* SlashEqualsToken */; + } + return pos++, token = 39 /* SlashToken */; + case 48 /* _0 */: + if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { + pos += 2; + var value = scanMinimumNumberOfHexDigits(1); + if (value < 0) { + error(ts.Diagnostics.Hexadecimal_digit_expected); + value = 0; + } + tokenValue = "" + value; + return token = 8 /* NumericLiteral */; + } + else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) { + pos += 2; + var value = scanBinaryOrOctalDigits(/* base */ 2); + if (value < 0) { + error(ts.Diagnostics.Binary_digit_expected); + value = 0; + } + tokenValue = "" + value; + return token = 8 /* NumericLiteral */; + } + else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) { + pos += 2; + var value = scanBinaryOrOctalDigits(/* base */ 8); + if (value < 0) { + error(ts.Diagnostics.Octal_digit_expected); + value = 0; + } + tokenValue = "" + value; + return token = 8 /* NumericLiteral */; + } + // Try to parse as an octal + if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { + tokenValue = "" + scanOctalDigits(); + return token = 8 /* NumericLiteral */; + } + // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero + // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being + // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do). + case 49 /* _1 */: + case 50 /* _2 */: + case 51 /* _3 */: + case 52 /* _4 */: + case 53 /* _5 */: + case 54 /* _6 */: + case 55 /* _7 */: + case 56 /* _8 */: + case 57 /* _9 */: + tokenValue = "" + scanNumber(); + return token = 8 /* NumericLiteral */; + case 58 /* colon */: + return pos++, token = 54 /* ColonToken */; + case 59 /* semicolon */: + return pos++, token = 23 /* SemicolonToken */; + case 60 /* lessThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 60 /* lessThan */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 63 /* LessThanLessThanEqualsToken */; + } + return pos += 2, token = 43 /* LessThanLessThanToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 28 /* LessThanEqualsToken */; + } + if (languageVariant === 1 /* JSX */ && + text.charCodeAt(pos + 1) === 47 /* slash */ && + text.charCodeAt(pos + 2) !== 42 /* asterisk */) { + return pos += 2, token = 26 /* LessThanSlashToken */; + } + return pos++, token = 25 /* LessThanToken */; + case 61 /* equals */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 32 /* EqualsEqualsEqualsToken */; + } + return pos += 2, token = 30 /* EqualsEqualsToken */; + } + if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { + return pos += 2, token = 34 /* EqualsGreaterThanToken */; + } + return pos++, token = 56 /* EqualsToken */; + case 62 /* greaterThan */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } + return pos++, token = 27 /* GreaterThanToken */; + case 63 /* question */: + return pos++, token = 53 /* QuestionToken */; + case 91 /* openBracket */: + return pos++, token = 19 /* OpenBracketToken */; + case 93 /* closeBracket */: + return pos++, token = 20 /* CloseBracketToken */; + case 94 /* caret */: + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 68 /* CaretEqualsToken */; + } + return pos++, token = 48 /* CaretToken */; + case 123 /* openBrace */: + return pos++, token = 15 /* OpenBraceToken */; + case 124 /* bar */: + if (text.charCodeAt(pos + 1) === 124 /* bar */) { + return pos += 2, token = 52 /* BarBarToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 67 /* BarEqualsToken */; + } + return pos++, token = 47 /* BarToken */; + case 125 /* closeBrace */: + return pos++, token = 16 /* CloseBraceToken */; + case 126 /* tilde */: + return pos++, token = 50 /* TildeToken */; + case 64 /* at */: + return pos++, token = 55 /* AtToken */; + case 92 /* backslash */: + var cookedChar = peekUnicodeEscape(); + if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { + pos += 6; + tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts(); + return token = getIdentifierToken(); + } + error(ts.Diagnostics.Invalid_character); + return pos++, token = 0 /* Unknown */; + default: + if (isIdentifierStart(ch, languageVersion)) { + pos++; + while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion)) + pos++; + tokenValue = text.substring(tokenPos, pos); + if (ch === 92 /* backslash */) { + tokenValue += scanIdentifierParts(); + } + return token = getIdentifierToken(); + } + else if (isWhiteSpace(ch)) { + pos++; + continue; + } + else if (isLineBreak(ch)) { + precedingLineBreak = true; + pos++; + continue; + } + error(ts.Diagnostics.Invalid_character); + return pos++, token = 0 /* Unknown */; + } + } + } + function reScanGreaterToken() { + if (token === 27 /* GreaterThanToken */) { + if (text.charCodeAt(pos) === 62 /* greaterThan */) { + if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { + if (text.charCodeAt(pos + 2) === 61 /* equals */) { + return pos += 3, token = 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */; + } + return pos += 2, token = 45 /* GreaterThanGreaterThanGreaterThanToken */; + } + if (text.charCodeAt(pos + 1) === 61 /* equals */) { + return pos += 2, token = 64 /* GreaterThanGreaterThanEqualsToken */; + } + return pos++, token = 44 /* GreaterThanGreaterThanToken */; + } + if (text.charCodeAt(pos) === 61 /* equals */) { + return pos++, token = 29 /* GreaterThanEqualsToken */; + } + } + return token; + } + function reScanSlashToken() { + if (token === 39 /* SlashToken */ || token === 61 /* SlashEqualsToken */) { + var p = tokenPos + 1; + var inEscape = false; + var inCharacterClass = false; + while (true) { + // If we reach the end of a file, or hit a newline, then this is an unterminated + // regex. Report error and return what we have so far. + if (p >= end) { + tokenIsUnterminated = true; + error(ts.Diagnostics.Unterminated_regular_expression_literal); + break; + } + var ch = text.charCodeAt(p); + if (isLineBreak(ch)) { + tokenIsUnterminated = true; + error(ts.Diagnostics.Unterminated_regular_expression_literal); + break; + } + if (inEscape) { + // Parsing an escape character; + // reset the flag and just advance to the next char. + inEscape = false; + } + else if (ch === 47 /* slash */ && !inCharacterClass) { + // A slash within a character class is permissible, + // but in general it signals the end of the regexp literal. + p++; + break; + } + else if (ch === 91 /* openBracket */) { + inCharacterClass = true; + } + else if (ch === 92 /* backslash */) { + inEscape = true; + } + else if (ch === 93 /* closeBracket */) { + inCharacterClass = false; + } + p++; + } + while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) { + p++; + } + pos = p; + tokenValue = text.substring(tokenPos, pos); + token = 10 /* RegularExpressionLiteral */; + } + return token; + } + /** + * Unconditionally back up and scan a template expression portion. + */ + function reScanTemplateToken() { + ts.Debug.assert(token === 16 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); + pos = tokenPos; + return token = scanTemplateAndSetTokenValue(); + } + function reScanJsxToken() { + pos = tokenPos = startPos; + return token = scanJsxToken(); + } + function scanJsxToken() { + startPos = tokenPos = pos; + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + var char = text.charCodeAt(pos); + if (char === 60 /* lessThan */) { + if (text.charCodeAt(pos + 1) === 47 /* slash */) { + pos += 2; + return token = 26 /* LessThanSlashToken */; + } + pos++; + return token = 25 /* LessThanToken */; + } + if (char === 123 /* openBrace */) { + pos++; + return token = 15 /* OpenBraceToken */; + } + while (pos < end) { + pos++; + char = text.charCodeAt(pos); + if ((char === 123 /* openBrace */) || (char === 60 /* lessThan */)) { + break; + } + } + return token = 236 /* JsxText */; + } + // Scans a JSX identifier; these differ from normal identifiers in that + // they allow dashes + function scanJsxIdentifier() { + if (tokenIsIdentifierOrKeyword(token)) { + var firstCharPosition = pos; + while (pos < end) { + var ch = text.charCodeAt(pos); + if (ch === 45 /* minus */ || ((firstCharPosition === pos) ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) { + pos++; + } + else { + break; + } + } + tokenValue += text.substr(firstCharPosition, pos - firstCharPosition); + } + return token; + } + function speculationHelper(callback, isLookahead) { + var savePos = pos; + var saveStartPos = startPos; + var saveTokenPos = tokenPos; + var saveToken = token; + var saveTokenValue = tokenValue; + var savePrecedingLineBreak = precedingLineBreak; + var result = callback(); + // If our callback returned something 'falsy' or we're just looking ahead, + // then unconditionally restore us to where we were. + if (!result || isLookahead) { + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + tokenValue = saveTokenValue; + precedingLineBreak = savePrecedingLineBreak; + } + return result; + } + function lookAhead(callback) { + return speculationHelper(callback, /*isLookahead:*/ true); + } + function tryScan(callback) { + return speculationHelper(callback, /*isLookahead:*/ false); + } + function setText(newText, start, length) { + text = newText || ""; + end = length === undefined ? text.length : start + length; + setTextPos(start || 0); + } + function setOnError(errorCallback) { + onError = errorCallback; + } + function setScriptTarget(scriptTarget) { + languageVersion = scriptTarget; + } + function setLanguageVariant(variant) { + languageVariant = variant; + } + function setTextPos(textPos) { + ts.Debug.assert(textPos >= 0); + pos = textPos; + startPos = textPos; + tokenPos = textPos; + token = 0 /* Unknown */; + precedingLineBreak = false; + tokenValue = undefined; + hasExtendedUnicodeEscape = false; + tokenIsUnterminated = false; + } + } + ts.createScanner = createScanner; +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + ts.bindTime = 0; + (function (ModuleInstanceState) { + ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; + ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; + ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; + })(ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); + var ModuleInstanceState = ts.ModuleInstanceState; + function getModuleInstanceState(node) { + // A module is uninstantiated if it contains only + // 1. interface declarations, type alias declarations + if (node.kind === 215 /* InterfaceDeclaration */ || node.kind === 216 /* TypeAliasDeclaration */) { + return 0 /* NonInstantiated */; + } + else if (ts.isConstEnumDeclaration(node)) { + return 2 /* ConstEnumOnly */; + } + else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && !(node.flags & 1 /* Export */)) { + return 0 /* NonInstantiated */; + } + else if (node.kind === 219 /* ModuleBlock */) { + var state = 0 /* NonInstantiated */; + ts.forEachChild(node, function (n) { + switch (getModuleInstanceState(n)) { + case 0 /* NonInstantiated */: + // child is non-instantiated - continue searching + return false; + case 2 /* ConstEnumOnly */: + // child is const enum only - record state and continue searching + state = 2 /* ConstEnumOnly */; + return false; + case 1 /* Instantiated */: + // child is instantiated - record state and stop + state = 1 /* Instantiated */; + return true; + } + }); + return state; + } + else if (node.kind === 218 /* ModuleDeclaration */) { + return getModuleInstanceState(node.body); + } + else { + return 1 /* Instantiated */; + } + } + ts.getModuleInstanceState = getModuleInstanceState; + var ContainerFlags; + (function (ContainerFlags) { + // The current node is not a container, and no container manipulation should happen before + // recursing into it. + ContainerFlags[ContainerFlags["None"] = 0] = "None"; + // The current node is a container. It should be set as the current container (and block- + // container) before recursing into it. The current node does not have locals. Examples: + // + // Classes, ObjectLiterals, TypeLiterals, Interfaces... + ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; + // The current node is a block-scoped-container. It should be set as the current block- + // container before recursing into it. Examples: + // + // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... + ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; + ContainerFlags[ContainerFlags["HasLocals"] = 4] = "HasLocals"; + // If the current node is a container that also container that also contains locals. Examples: + // + // Functions, Methods, Modules, Source-files. + ContainerFlags[ContainerFlags["IsContainerWithLocals"] = 5] = "IsContainerWithLocals"; + })(ContainerFlags || (ContainerFlags = {})); + function bindSourceFile(file) { + var start = new Date().getTime(); + bindSourceFileWorker(file); + ts.bindTime += new Date().getTime() - start; + } + ts.bindSourceFile = bindSourceFile; + function bindSourceFileWorker(file) { + var parent; + var container; + var blockScopeContainer; + var lastContainer; + var seenThisKeyword; + // If this file is an external module, then it is automatically in strict-mode according to + // ES6. If it is not an external module, then we'll determine if it is in strict mode or + // not depending on if we see "use strict" in certain places (or if we hit a class/namespace). + var inStrictMode = !!file.externalModuleIndicator; + var symbolCount = 0; + var Symbol = ts.objectAllocator.getSymbolConstructor(); + var classifiableNames = {}; + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + } + return; + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); + } + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; + node.symbol = symbol; + if (!symbol.declarations) { + symbol.declarations = []; + } + symbol.declarations.push(node); + if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { + symbol.exports = {}; + } + if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { + symbol.members = {}; + } + if (symbolFlags & 107455 /* Value */ && !symbol.valueDeclaration) { + symbol.valueDeclaration = node; + } + } + // Should not be called on a declaration with a computed property name, + // unless it is a well known Symbol. + function getDeclarationName(node) { + if (node.name) { + if (node.kind === 218 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) { + return "\"" + node.name.text + "\""; + } + if (node.name.kind === 136 /* ComputedPropertyName */) { + var nameExpression = node.name.expression; + ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); + return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); + } + return node.name.text; + } + switch (node.kind) { + case 144 /* Constructor */: + return "__constructor"; + case 152 /* FunctionType */: + case 147 /* CallSignature */: + return "__call"; + case 153 /* ConstructorType */: + case 148 /* ConstructSignature */: + return "__new"; + case 149 /* IndexSignature */: + return "__index"; + case 228 /* ExportDeclaration */: + return "__export"; + case 227 /* ExportAssignment */: + return node.isExportEquals ? "export=" : "default"; + case 213 /* FunctionDeclaration */: + case 214 /* ClassDeclaration */: + return node.flags & 1024 /* Default */ ? "default" : undefined; + } + } + function getDisplayName(node) { + return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node); + } + /** + * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. + * @param symbolTable - The symbol table which node will be added to. + * @param parent - node's parent declaration. + * @param node - The declaration to be added to the symbol table + * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) + * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. + */ + function declareSymbol(symbolTable, parent, node, includes, excludes) { + ts.Debug.assert(!ts.hasDynamicName(node)); + var isDefaultExport = node.flags & 1024 /* Default */; + // The exported symbol for an export default function/class node is always named "default" + var name = isDefaultExport && parent ? "default" : getDeclarationName(node); + var symbol; + if (name !== undefined) { + // Check and see if the symbol table already has a symbol with this name. If not, + // create a new symbol with this name and add it to the table. Note that we don't + // give the new symbol any flags *yet*. This ensures that it will not conflict + // with the 'excludes' flags we pass in. + // + // If we do get an existing symbol, see if it conflicts with the new symbol we're + // creating. For example, a 'var' symbol and a 'class' symbol will conflict within + // the same symbol table. If we have a conflict, report the issue on each + // declaration we have for this symbol, and then create a new symbol for this + // declaration. + // + // If we created a new symbol, either because we didn't have a symbol with this name + // in the symbol table, or we conflicted with an existing symbol, then just add this + // node as the sole declaration of the new symbol. + // + // Otherwise, we'll be merging into a compatible existing symbol (for example when + // you have multiple 'vars' with the same name in the same container). In this case + // just add this node into the declarations list of the symbol. + symbol = ts.hasProperty(symbolTable, name) + ? symbolTable[name] + : (symbolTable[name] = createSymbol(0 /* None */, name)); + if (name && (includes & 788448 /* Classifiable */)) { + classifiableNames[name] = name; + } + if (symbol.flags & excludes) { + if (node.name) { + node.name.parent = node; + } + // Report errors every position with duplicate declaration + // Report errors on previous encountered declarations + var message = symbol.flags & 2 /* BlockScopedVariable */ + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + ts.forEach(symbol.declarations, function (declaration) { + if (declaration.flags & 1024 /* Default */) { + message = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + }); + ts.forEach(symbol.declarations, function (declaration) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration))); + }); + file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message, getDisplayName(node))); + symbol = createSymbol(0 /* None */, name); + } + } + else { + symbol = createSymbol(0 /* None */, "__missing"); + } + addDeclarationToSymbol(symbol, node, includes); + symbol.parent = parent; + return symbol; + } + function declareModuleMember(node, symbolFlags, symbolExcludes) { + var hasExportModifier = ts.getCombinedNodeFlags(node) & 1 /* Export */; + if (symbolFlags & 8388608 /* Alias */) { + if (node.kind === 230 /* ExportSpecifier */ || (node.kind === 221 /* ImportEqualsDeclaration */ && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } + else { + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + else { + // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue, + // ExportType, or ExportContainer flag, and an associated export symbol with all the correct flags set + // on it. There are 2 main reasons: + // + // 1. We treat locals and exports of the same name as mutually exclusive within a container. + // That means the binder will issue a Duplicate Identifier error if you mix locals and exports + // with the same name in the same container. + // TODO: Make this a more specific error and decouple it from the exclusion logic. + // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, + // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way + // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. + if (hasExportModifier || container.flags & 262144 /* ExportContext */) { + var exportKind = (symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) | + (symbolFlags & 793056 /* Type */ ? 2097152 /* ExportType */ : 0) | + (symbolFlags & 1536 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0); + var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + node.localSymbol = local; + return local; + } + else { + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + } + // All container nodes are kept on a linked list in declaration order. This list is used by + // the getLocalNameOfContainer function in the type checker to validate that the local name + // used for a container is unique. + function bindChildren(node) { + // Before we recurse into a node's chilren, we first save the existing parent, container + // and block-container. Then after we pop out of processing the children, we restore + // these saved values. + var saveParent = parent; + var saveContainer = container; + var savedBlockScopeContainer = blockScopeContainer; + // This node will now be set as the parent of all of its children as we recurse into them. + parent = node; + // Depending on what kind of node this is, we may have to adjust the current container + // and block-container. If the current node is a container, then it is automatically + // considered the current block-container as well. Also, for containers that we know + // may contain locals, we proactively initialize the .locals field. We do this because + // it's highly likely that the .locals will be needed to place some child in (for example, + // a parameter, or variable declaration). + // + // However, we do not proactively create the .locals for block-containers because it's + // totally normal and common for block-containers to never actually have a block-scoped + // variable in them. We don't want to end up allocating an object for every 'block' we + // run into when most of them won't be necessary. + // + // Finally, if this is a block-container, then we clear out any existing .locals object + // it may contain within it. This happens in incremental scenarios. Because we can be + // reusing a node from a previous compilation, that node may have had 'locals' created + // for it. We must clear this so we don't accidently move any stale data forward from + // a previous compilation. + var containerFlags = getContainerFlags(node); + if (containerFlags & 1 /* IsContainer */) { + container = blockScopeContainer = node; + if (containerFlags & 4 /* HasLocals */) { + container.locals = {}; + } + addToContainerChain(container); + } + else if (containerFlags & 2 /* IsBlockScopedContainer */) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; + } + if (node.kind === 215 /* InterfaceDeclaration */) { + seenThisKeyword = false; + ts.forEachChild(node, bind); + node.flags = seenThisKeyword ? node.flags | 524288 /* ContainsThis */ : node.flags & ~524288 /* ContainsThis */; + } + else { + ts.forEachChild(node, bind); + } + container = saveContainer; + parent = saveParent; + blockScopeContainer = savedBlockScopeContainer; + } + function getContainerFlags(node) { + switch (node.kind) { + case 186 /* ClassExpression */: + case 214 /* ClassDeclaration */: + case 215 /* InterfaceDeclaration */: + case 217 /* EnumDeclaration */: + case 155 /* TypeLiteral */: + case 165 /* ObjectLiteralExpression */: + return 1 /* IsContainer */; + case 147 /* CallSignature */: + case 148 /* ConstructSignature */: + case 149 /* IndexSignature */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 213 /* FunctionDeclaration */: + case 144 /* Constructor */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 152 /* FunctionType */: + case 153 /* ConstructorType */: + case 173 /* FunctionExpression */: + case 174 /* ArrowFunction */: + case 218 /* ModuleDeclaration */: + case 248 /* SourceFile */: + case 216 /* TypeAliasDeclaration */: + return 5 /* IsContainerWithLocals */; + case 244 /* CatchClause */: + case 199 /* ForStatement */: + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + case 220 /* CaseBlock */: + return 2 /* IsBlockScopedContainer */; + case 192 /* Block */: + // do not treat blocks directly inside a function as a block-scoped-container. + // Locals that reside in this block should go to the function locals. Othewise 'x' + // would not appear to be a redeclaration of a block scoped local in the following + // example: + // + // function foo() { + // var x; + // let x; + // } + // + // If we placed 'var x' into the function locals and 'let x' into the locals of + // the block, then there would be no collision. + // + // By not creating a new block-scoped-container here, we ensure that both 'var x' + // and 'let x' go into the Function-container's locals, and we do get a collision + // conflict. + return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */; + } + return 0 /* None */; + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + // Just call this directly so that the return type of this function stays "void". + declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); + } + function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { + switch (container.kind) { + // Modules, source files, and classes need specialized handling for how their + // members are declared (for example, a member of a class will go into a specific + // symbol table depending on if it is static or not). We defer to specialized + // handlers to take care of declaring these child members. + case 218 /* ModuleDeclaration */: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 248 /* SourceFile */: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 186 /* ClassExpression */: + case 214 /* ClassDeclaration */: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 217 /* EnumDeclaration */: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 155 /* TypeLiteral */: + case 165 /* ObjectLiteralExpression */: + case 215 /* InterfaceDeclaration */: + // Interface/Object-types always have their children added to the 'members' of + // their container. They are only accessible through an instance of their + // container, and are never in scope otherwise (even inside the body of the + // object / type / interface declaring them). An exception is type parameters, + // which are in scope without qualification (similar to 'locals'). + return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + case 152 /* FunctionType */: + case 153 /* ConstructorType */: + case 147 /* CallSignature */: + case 148 /* ConstructSignature */: + case 149 /* IndexSignature */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 144 /* Constructor */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 213 /* FunctionDeclaration */: + case 173 /* FunctionExpression */: + case 174 /* ArrowFunction */: + case 216 /* TypeAliasDeclaration */: + // All the children of these container types are never visible through another + // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, + // they're only accessed 'lexically' (i.e. from code that exists underneath + // their container in the tree. To accomplish this, we simply add their declared + // symbol to the 'locals' of the container. These symbols can then be found as + // the type checker walks up the containers, checking them for matching names. + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return node.flags & 128 /* Static */ + ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) + : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + } + function declareSourceFileMember(node, symbolFlags, symbolExcludes) { + return ts.isExternalModule(file) + ? declareModuleMember(node, symbolFlags, symbolExcludes) + : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); + } + function isAmbientContext(node) { + while (node) { + if (node.flags & 2 /* Ambient */) { + return true; + } + node = node.parent; + } + return false; + } + function hasExportDeclarations(node) { + var body = node.kind === 248 /* SourceFile */ ? node : node.body; + if (body.kind === 248 /* SourceFile */ || body.kind === 219 /* ModuleBlock */) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var stat = _a[_i]; + if (stat.kind === 228 /* ExportDeclaration */ || stat.kind === 227 /* ExportAssignment */) { + return true; + } + } + } + return false; + } + function setExportContextFlag(node) { + // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular + // declarations with export modifiers) is an export context in which declarations are implicitly exported. + if (isAmbientContext(node) && !hasExportDeclarations(node)) { + node.flags |= 262144 /* ExportContext */; + } + else { + node.flags &= ~262144 /* ExportContext */; + } + } + function bindModuleDeclaration(node) { + setExportContextFlag(node); + if (node.name.kind === 9 /* StringLiteral */) { + declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); + } + else { + var state = getModuleInstanceState(node); + if (state === 0 /* NonInstantiated */) { + declareSymbolAndAddToSymbolTable(node, 1024 /* NamespaceModule */, 0 /* NamespaceModuleExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); + if (node.symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) { + // if module was already merged with some function, class or non-const enum + // treat is a non-const-enum-only + node.symbol.constEnumOnlyModule = false; + } + else { + var currentModuleIsConstEnumOnly = state === 2 /* ConstEnumOnly */; + if (node.symbol.constEnumOnlyModule === undefined) { + // non-merged case - use the current state + node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; + } + else { + // merged case: module is const enum only if all its pieces are non-instantiated or const enum + node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; + } + } + } + } + } + function bindFunctionOrConstructorType(node) { + // For a given function symbol "<...>(...) => T" we want to generate a symbol identical + // to the one we would get for: { <...>(...): T } + // + // We do that by making an anonymous type literal symbol, and then setting the function + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // from an actual type literal symbol you would have gotten had you used the long form. + var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); + addDeclarationToSymbol(symbol, node, 131072 /* Signature */); + var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type"); + addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); + typeLiteralSymbol.members = (_a = {}, _a[symbol.name] = symbol, _a); + var _a; + } + function bindObjectLiteralExpression(node) { + var ElementKind; + (function (ElementKind) { + ElementKind[ElementKind["Property"] = 1] = "Property"; + ElementKind[ElementKind["Accessor"] = 2] = "Accessor"; + })(ElementKind || (ElementKind = {})); + if (inStrictMode) { + var seen = {}; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.name.kind !== 69 /* Identifier */) { + continue; + } + var identifier = prop.name; + // ECMA-262 11.1.5 Object Initialiser + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = prop.kind === 245 /* PropertyAssignment */ || prop.kind === 246 /* ShorthandPropertyAssignment */ || prop.kind === 143 /* MethodDeclaration */ + ? 1 /* Property */ + : 2 /* Accessor */; + var existingKind = seen[identifier.text]; + if (!existingKind) { + seen[identifier.text] = currentKind; + continue; + } + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { + var span = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + } + } + } + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object"); + } + function bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + addDeclarationToSymbol(symbol, node, symbolFlags); + } + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { + switch (blockScopeContainer.kind) { + case 218 /* ModuleDeclaration */: + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + case 248 /* SourceFile */: + if (ts.isExternalModule(container)) { + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + } + // fall through. + default: + if (!blockScopeContainer.locals) { + blockScopeContainer.locals = {}; + addToContainerChain(blockScopeContainer); + } + declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + function bindBlockScopedVariableDeclaration(node) { + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 107455 /* BlockScopedVariableExcludes */); + } + // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized + // check for reserved words used as identifiers in strict mode code. + function checkStrictModeIdentifier(node) { + if (inStrictMode && + node.originalKeywordKind >= 106 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 114 /* LastFutureReservedWord */ && + !ts.isIdentifierName(node)) { + // Report error only if there are no parse errors in file + if (!file.parseDiagnostics.length) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + } + } + } + function getStrictModeIdentifierMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; + } + function checkStrictModeBinaryExpression(node) { + if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) + checkStrictModeEvalOrArguments(node, node.left); + } + } + function checkStrictModeCatchClause(node) { + // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the + // Catch production is eval or arguments + if (inStrictMode && node.variableDeclaration) { + checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); + } + } + function checkStrictModeDeleteExpression(node) { + // Grammar checking + if (inStrictMode && node.expression.kind === 69 /* Identifier */) { + // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its + // UnaryExpression is a direct reference to a variable, function argument, or function name + var span = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + function isEvalOrArgumentsIdentifier(node) { + return node.kind === 69 /* Identifier */ && + (node.text === "eval" || node.text === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 69 /* Identifier */) { + var identifier = name; + if (isEvalOrArgumentsIdentifier(identifier)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. + var span = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); + } + } + } + function getStrictModeEvalOrArgumentsMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; + } + function checkStrictModeFunctionName(node) { + if (inStrictMode) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) + checkStrictModeEvalOrArguments(node, node.name); + } + } + function checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.flags & 65536 /* OctalLiteral */) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + } + } + function checkStrictModePostfixUnaryExpression(node) { + // Grammar checking + // The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression + // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator. + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + function checkStrictModePrefixUnaryExpression(node) { + // Grammar checking + if (inStrictMode) { + if (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + // Grammar checking for withStatement + if (inStrictMode) { + grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); + } + function getDestructuringParameterName(node) { + return "__" + ts.indexOf(node.parent.parameters, node); + } + function bind(node) { + node.parent = parent; + var savedInStrictMode = inStrictMode; + if (!savedInStrictMode) { + updateStrictMode(node); + } + // First we bind declaration nodes to a symbol if possible. We'll both create a symbol + // and then potentially add the symbol to an appropriate symbol table. Possible + // destination symbol tables are: + // + // 1) The 'exports' table of the current container's symbol. + // 2) The 'members' table of the current container's symbol. + // 3) The 'locals' table of the current container. + // + // However, not all symbols will end up in any of these tables. 'Anonymous' symbols + // (like TypeLiterals for example) will not be put in any table. + bindWorker(node); + // Then we recurse into the children of the node to bind them as well. For certain + // symbols we do specialized work when we recurse. For example, we'll keep track of + // the current 'container' node when it changes. This helps us know which symbol table + // a local should go into for example. + bindChildren(node); + inStrictMode = savedInStrictMode; + } + function updateStrictMode(node) { + switch (node.kind) { + case 248 /* SourceFile */: + case 219 /* ModuleBlock */: + updateStrictModeStatementList(node.statements); + return; + case 192 /* Block */: + if (ts.isFunctionLike(node.parent)) { + updateStrictModeStatementList(node.statements); + } + return; + case 214 /* ClassDeclaration */: + case 186 /* ClassExpression */: + // All classes are automatically in strict mode in ES6. + inStrictMode = true; + return; + } + } + function updateStrictModeStatementList(statements) { + for (var _i = 0; _i < statements.length; _i++) { + var statement = statements[_i]; + if (!ts.isPrologueDirective(statement)) { + return; + } + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; + } + } + } + /// Should be called only on prologue directives (isPrologueDirective(node) should be true) + function isUseStrictPrologueDirective(node) { + var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); + // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the + // string to contain unicode escapes (as per ES5). + return nodeText === "\"use strict\"" || nodeText === "'use strict'"; + } + function bindWorker(node) { + switch (node.kind) { + case 69 /* Identifier */: + return checkStrictModeIdentifier(node); + case 181 /* BinaryExpression */: + return checkStrictModeBinaryExpression(node); + case 244 /* CatchClause */: + return checkStrictModeCatchClause(node); + case 175 /* DeleteExpression */: + return checkStrictModeDeleteExpression(node); + case 8 /* NumericLiteral */: + return checkStrictModeNumericLiteral(node); + case 180 /* PostfixUnaryExpression */: + return checkStrictModePostfixUnaryExpression(node); + case 179 /* PrefixUnaryExpression */: + return checkStrictModePrefixUnaryExpression(node); + case 205 /* WithStatement */: + return checkStrictModeWithStatement(node); + case 97 /* ThisKeyword */: + seenThisKeyword = true; + return; + case 137 /* TypeParameter */: + return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */); + case 138 /* Parameter */: + return bindParameter(node); + case 211 /* VariableDeclaration */: + case 163 /* BindingElement */: + return bindVariableDeclarationOrBindingElement(node); + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 107455 /* PropertyExcludes */); + case 245 /* PropertyAssignment */: + case 246 /* ShorthandPropertyAssignment */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */); + case 247 /* EnumMember */: + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */); + case 147 /* CallSignature */: + case 148 /* ConstructSignature */: + case 149 /* IndexSignature */: + return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + // If this is an ObjectLiteralExpression method, then it sits in the same space + // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes + // so that it will conflict with any other object literal members with the same + // name. + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */); + case 213 /* FunctionDeclaration */: + checkStrictModeFunctionName(node); + return declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */); + case 144 /* Constructor */: + return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); + case 145 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); + case 146 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); + case 152 /* FunctionType */: + case 153 /* ConstructorType */: + return bindFunctionOrConstructorType(node); + case 155 /* TypeLiteral */: + return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type"); + case 165 /* ObjectLiteralExpression */: + return bindObjectLiteralExpression(node); + case 173 /* FunctionExpression */: + case 174 /* ArrowFunction */: + checkStrictModeFunctionName(node); + var bindingName = node.name ? node.name.text : "__function"; + return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); + case 186 /* ClassExpression */: + case 214 /* ClassDeclaration */: + return bindClassLikeDeclaration(node); + case 215 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 792960 /* InterfaceExcludes */); + case 216 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */); + case 217 /* EnumDeclaration */: + return bindEnumDeclaration(node); + case 218 /* ModuleDeclaration */: + return bindModuleDeclaration(node); + case 221 /* ImportEqualsDeclaration */: + case 224 /* NamespaceImport */: + case 226 /* ImportSpecifier */: + case 230 /* ExportSpecifier */: + return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); + case 223 /* ImportClause */: + return bindImportClause(node); + case 228 /* ExportDeclaration */: + return bindExportDeclaration(node); + case 227 /* ExportAssignment */: + return bindExportAssignment(node); + case 248 /* SourceFile */: + return bindSourceFileIfExternalModule(); + } + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); + } + } + function bindExportAssignment(node) { + if (!container.symbol || !container.symbol.exports) { + // Export assignment in some sort of block construct + bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node)); + } + else if (node.expression.kind === 69 /* Identifier */) { + // An export default clause with an identifier exports all meanings of that identifier + declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* Alias */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + } + else { + // An export default clause with an expression exports a value + declareSymbol(container.symbol.exports, container.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + } + } + function bindExportDeclaration(node) { + if (!container.symbol || !container.symbol.exports) { + // Export * in some sort of block construct + bindAnonymousDeclaration(node, 1073741824 /* ExportStar */, getDeclarationName(node)); + } + else if (!node.exportClause) { + // All export * declarations are collected in an __export symbol + declareSymbol(container.symbol.exports, container.symbol, node, 1073741824 /* ExportStar */, 0 /* None */); + } + } + function bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); + } + } + function bindClassLikeDeclaration(node) { + if (node.kind === 214 /* ClassDeclaration */) { + bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */); + } + else { + var bindingName = node.name ? node.name.text : "__class"; + bindAnonymousDeclaration(node, 32 /* Class */, bindingName); + // Add name of class expression into the map for semantic classifier + if (node.name) { + classifiableNames[node.name.text] = node.name.text; + } + } + var symbol = node.symbol; + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', the + // type of which is an instantiation of the class type with type Any supplied as a type + // argument for each type parameter. It is an error to explicitly declare a static + // property member with the name 'prototype'. + // + // Note: we check for this here because this class may be merging into a module. The + // module might have an exported variable called 'prototype'. We can't allow that as + // that would clash with the built-in 'prototype' for the class. + var prototypeSymbol = createSymbol(4 /* Property */ | 134217728 /* Prototype */, "prototype"); + if (ts.hasProperty(symbol.exports, prototypeSymbol.name)) { + if (node.name) { + node.name.parent = node; + } + file.bindDiagnostics.push(ts.createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name)); + } + symbol.exports[prototypeSymbol.name] = prototypeSymbol; + prototypeSymbol.parent = symbol; + } + function bindEnumDeclaration(node) { + return ts.isConst(node) + ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */) + : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */); + } + function bindVariableDeclarationOrBindingElement(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (!ts.isBindingPattern(node.name)) { + if (ts.isBlockOrCatchScoped(node)) { + bindBlockScopedVariableDeclaration(node); + } + else if (ts.isParameterDeclaration(node)) { + // It is safe to walk up parent chain to find whether the node is a destructing parameter declaration + // because its parent chain has already been set up, since parents are set before descending into children. + // + // If node is a binding element in parameter declaration, we need to use ParameterExcludes. + // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration + // For example: + // function foo([a,a]) {} // Duplicate Identifier error + // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter + // // which correctly set excluded symbols + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107454 /* FunctionScopedVariableExcludes */); + } + } + } + function bindParameter(node) { + if (inStrictMode) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a + // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) + checkStrictModeEvalOrArguments(node, node.name); + } + if (ts.isBindingPattern(node.name)) { + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, getDestructuringParameterName(node)); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); + } + // If this is a property-parameter, then also declare the property symbol into the + // containing class. + if (node.flags & 112 /* AccessibilityModifier */ && + node.parent.kind === 144 /* Constructor */ && + ts.isClassLike(node.parent.parent)) { + var classDeclaration = node.parent.parent; + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */); + } + } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed") + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + } +})(ts || (ts = {})); +/// +/// +/* @internal */ +var ts; +(function (ts) { + function getDeclarationOfKind(symbol, kind) { + var declarations = symbol.declarations; + if (declarations) { + for (var _i = 0; _i < declarations.length; _i++) { + var declaration = declarations[_i]; + if (declaration.kind === kind) { + return declaration; + } + } + } + return undefined; + } + ts.getDeclarationOfKind = getDeclarationOfKind; + // Pool writers to avoid needing to allocate them for every symbol we write. + var stringWriters = []; + function getSingleLineStringWriter() { + if (stringWriters.length === 0) { + var str = ""; + var writeText = function (text) { return str += text; }; + return { + string: function () { return str; }, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeSymbol: writeText, + // Completely ignore indentation for string writers. And map newlines to + // a single space. + writeLine: function () { return str += " "; }, + increaseIndent: function () { }, + decreaseIndent: function () { }, + clear: function () { return str = ""; }, + trackSymbol: function () { }, + reportInaccessibleThisError: function () { } + }; + } + return stringWriters.pop(); + } + ts.getSingleLineStringWriter = getSingleLineStringWriter; + function releaseStringWriter(writer) { + writer.clear(); + stringWriters.push(writer); + } + ts.releaseStringWriter = releaseStringWriter; + function getFullWidth(node) { + return node.end - node.pos; + } + ts.getFullWidth = getFullWidth; + function arrayIsEqualTo(arr1, arr2, comparer) { + if (!arr1 || !arr2) { + return arr1 === arr2; + } + if (arr1.length !== arr2.length) { + return false; + } + for (var i = 0; i < arr1.length; ++i) { + var equals = comparer ? comparer(arr1[i], arr2[i]) : arr1[i] === arr2[i]; + if (!equals) { + return false; + } + } + return true; + } + ts.arrayIsEqualTo = arrayIsEqualTo; + function hasResolvedModule(sourceFile, moduleNameText) { + return sourceFile.resolvedModules && ts.hasProperty(sourceFile.resolvedModules, moduleNameText); + } + ts.hasResolvedModule = hasResolvedModule; + function getResolvedModule(sourceFile, moduleNameText) { + return hasResolvedModule(sourceFile, moduleNameText) ? sourceFile.resolvedModules[moduleNameText] : undefined; + } + ts.getResolvedModule = getResolvedModule; + function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { + if (!sourceFile.resolvedModules) { + sourceFile.resolvedModules = {}; + } + sourceFile.resolvedModules[moduleNameText] = resolvedModule; + } + ts.setResolvedModule = setResolvedModule; + // Returns true if this node contains a parse error anywhere underneath it. + function containsParseError(node) { + aggregateChildData(node); + return (node.parserContextFlags & 64 /* ThisNodeOrAnySubNodesHasError */) !== 0; + } + ts.containsParseError = containsParseError; + function aggregateChildData(node) { + if (!(node.parserContextFlags & 128 /* HasAggregatedChildData */)) { + // A node is considered to contain a parse error if: + // a) the parser explicitly marked that it had an error + // b) any of it's children reported that it had an error. + var thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & 16 /* ThisNodeHasError */) !== 0) || + ts.forEachChild(node, containsParseError); + // If so, mark ourselves accordingly. + if (thisNodeOrAnySubNodesHasError) { + node.parserContextFlags |= 64 /* ThisNodeOrAnySubNodesHasError */; + } + // Also mark that we've propogated the child information to this node. This way we can + // always consult the bit directly on this node without needing to check its children + // again. + node.parserContextFlags |= 128 /* HasAggregatedChildData */; + } + } + function getSourceFileOfNode(node) { + while (node && node.kind !== 248 /* SourceFile */) { + node = node.parent; + } + return node; + } + ts.getSourceFileOfNode = getSourceFileOfNode; + function getStartPositionOfLine(line, sourceFile) { + ts.Debug.assert(line >= 0); + return ts.getLineStarts(sourceFile)[line]; + } + ts.getStartPositionOfLine = getStartPositionOfLine; + // This is a useful function for debugging purposes. + function nodePosToString(node) { + var file = getSourceFileOfNode(node); + var loc = ts.getLineAndCharacterOfPosition(file, node.pos); + return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")"; + } + ts.nodePosToString = nodePosToString; + function getStartPosOfNode(node) { + return node.pos; + } + ts.getStartPosOfNode = getStartPosOfNode; + // Returns true if this node is missing from the actual source code. A 'missing' node is different + // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes + // in the tree), it is definitely missing. However, a node may be defined, but still be + // missing. This happens whenever the parser knows it needs to parse something, but can't + // get anything in the source code that it expects at that location. For example: + // + // let a: ; + // + // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source + // code). So the parser will attempt to parse out a type, and will create an actual node. + // However, this node will be 'missing' in the sense that no actual source-code/tokens are + // contained within it. + function nodeIsMissing(node) { + if (!node) { + return true; + } + return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */; + } + ts.nodeIsMissing = nodeIsMissing; + function nodeIsPresent(node) { + return !nodeIsMissing(node); + } + ts.nodeIsPresent = nodeIsPresent; + function getTokenPosOfNode(node, sourceFile) { + // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't* + // want to skip trivia because this will launch us forward to the next token. + if (nodeIsMissing(node)) { + return node.pos; + } + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + } + ts.getTokenPosOfNode = getTokenPosOfNode; + function getNonDecoratorTokenPosOfNode(node, sourceFile) { + if (nodeIsMissing(node) || !node.decorators) { + return getTokenPosOfNode(node, sourceFile); + } + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end); + } + ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; + function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + if (nodeIsMissing(node)) { + return ""; + } + var text = sourceFile.text; + return text.substring(includeTrivia ? node.pos : ts.skipTrivia(text, node.pos), node.end); + } + ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function getTextOfNodeFromSourceText(sourceText, node) { + if (nodeIsMissing(node)) { + return ""; + } + return sourceText.substring(ts.skipTrivia(sourceText, node.pos), node.end); + } + ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; + function getTextOfNode(node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); + } + ts.getTextOfNode = getTextOfNode; + // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' + function escapeIdentifier(identifier) { + return identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier; + } + ts.escapeIdentifier = escapeIdentifier; + // Remove extra underscore from escaped identifier + function unescapeIdentifier(identifier) { + return identifier.length >= 3 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ && identifier.charCodeAt(2) === 95 /* _ */ ? identifier.substr(1) : identifier; + } + ts.unescapeIdentifier = unescapeIdentifier; + // Make an identifier from an external module name by extracting the string after the last "/" and replacing + // all non-alphanumeric characters with underscores + function makeIdentifierFromModuleName(moduleName) { + return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_"); + } + ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; + function isBlockOrCatchScoped(declaration) { + return (getCombinedNodeFlags(declaration) & 49152 /* BlockScoped */) !== 0 || + isCatchClauseVariableDeclaration(declaration); + } + ts.isBlockOrCatchScoped = isBlockOrCatchScoped; + // Gets the nearest enclosing block scope container that has the provided node + // as a descendant, that is not the provided node. + function getEnclosingBlockScopeContainer(node) { + var current = node.parent; + while (current) { + if (isFunctionLike(current)) { + return current; + } + switch (current.kind) { + case 248 /* SourceFile */: + case 220 /* CaseBlock */: + case 244 /* CatchClause */: + case 218 /* ModuleDeclaration */: + case 199 /* ForStatement */: + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + return current; + case 192 /* Block */: + // function block is not considered block-scope container + // see comment in binder.ts: bind(...), case for SyntaxKind.Block + if (!isFunctionLike(current.parent)) { + return current; + } + } + current = current.parent; + } + } + ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; + function isCatchClauseVariableDeclaration(declaration) { + return declaration && + declaration.kind === 211 /* VariableDeclaration */ && + declaration.parent && + declaration.parent.kind === 244 /* CatchClause */; + } + ts.isCatchClauseVariableDeclaration = isCatchClauseVariableDeclaration; + // Return display name of an identifier + // Computed property names will just be emitted as "[]", where is the source + // text of the expression in the computed property. + function declarationNameToString(name) { + return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); + } + ts.declarationNameToString = declarationNameToString; + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + var sourceFile = getSourceFileOfNode(node); + var span = getErrorSpanForNode(sourceFile, node); + return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2); + } + ts.createDiagnosticForNode = createDiagnosticForNode; + function createDiagnosticForNodeFromMessageChain(node, messageChain) { + var sourceFile = getSourceFileOfNode(node); + var span = getErrorSpanForNode(sourceFile, node); + return { + file: sourceFile, + start: span.start, + length: span.length, + code: messageChain.code, + category: messageChain.category, + messageText: messageChain.next ? messageChain : messageChain.messageText + }; + } + ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain; + function getSpanOfTokenAtPosition(sourceFile, pos) { + var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos); + scanner.scan(); + var start = scanner.getTokenPos(); + return ts.createTextSpanFromBounds(start, scanner.getTextPos()); + } + ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; + function getErrorSpanForNode(sourceFile, node) { + var errorNode = node; + switch (node.kind) { + case 248 /* SourceFile */: + var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); + if (pos_1 === sourceFile.text.length) { + // file is empty - return span for the beginning of the file + return ts.createTextSpan(0, 0); + } + return getSpanOfTokenAtPosition(sourceFile, pos_1); + // This list is a work in progress. Add missing node kinds to improve their error + // spans. + case 211 /* VariableDeclaration */: + case 163 /* BindingElement */: + case 214 /* ClassDeclaration */: + case 186 /* ClassExpression */: + case 215 /* InterfaceDeclaration */: + case 218 /* ModuleDeclaration */: + case 217 /* EnumDeclaration */: + case 247 /* EnumMember */: + case 213 /* FunctionDeclaration */: + case 173 /* FunctionExpression */: + errorNode = node.name; + break; + } + if (errorNode === undefined) { + // If we don't have a better node, then just set the error on the first token of + // construct. + return getSpanOfTokenAtPosition(sourceFile, node.pos); + } + var pos = nodeIsMissing(errorNode) + ? errorNode.pos + : ts.skipTrivia(sourceFile.text, errorNode.pos); + return ts.createTextSpanFromBounds(pos, errorNode.end); + } + ts.getErrorSpanForNode = getErrorSpanForNode; + function isExternalModule(file) { + return file.externalModuleIndicator !== undefined; + } + ts.isExternalModule = isExternalModule; + function isDeclarationFile(file) { + return (file.flags & 8192 /* DeclarationFile */) !== 0; + } + ts.isDeclarationFile = isDeclarationFile; + function isConstEnumDeclaration(node) { + return node.kind === 217 /* EnumDeclaration */ && isConst(node); + } + ts.isConstEnumDeclaration = isConstEnumDeclaration; + function walkUpBindingElementsAndPatterns(node) { + while (node && (node.kind === 163 /* BindingElement */ || isBindingPattern(node))) { + node = node.parent; + } + return node; + } + // Returns the node flags for this node and all relevant parent nodes. This is done so that + // nodes like variable declarations and binding elements can returned a view of their flags + // that includes the modifiers from their container. i.e. flags like export/declare aren't + // stored on the variable declaration directly, but on the containing variable statement + // (if it has one). Similarly, flags for let/const are store on the variable declaration + // list. By calling this function, all those flags are combined so that the client can treat + // the node as if it actually had those flags. + function getCombinedNodeFlags(node) { + node = walkUpBindingElementsAndPatterns(node); + var flags = node.flags; + if (node.kind === 211 /* VariableDeclaration */) { + node = node.parent; + } + if (node && node.kind === 212 /* VariableDeclarationList */) { + flags |= node.flags; + node = node.parent; + } + if (node && node.kind === 193 /* VariableStatement */) { + flags |= node.flags; + } + return flags; + } + ts.getCombinedNodeFlags = getCombinedNodeFlags; + function isConst(node) { + return !!(getCombinedNodeFlags(node) & 32768 /* Const */); + } + ts.isConst = isConst; + function isLet(node) { + return !!(getCombinedNodeFlags(node) & 16384 /* Let */); + } + ts.isLet = isLet; + function isPrologueDirective(node) { + return node.kind === 195 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; + } + ts.isPrologueDirective = isPrologueDirective; + function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { + return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos); + } + ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; + function getJsDocComments(node, sourceFileOfNode) { + var commentRanges = (node.kind === 138 /* Parameter */ || node.kind === 137 /* TypeParameter */) ? + ts.concatenate(ts.getTrailingCommentRanges(sourceFileOfNode.text, node.pos), ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos)) : + getLeadingCommentRangesOfNode(node, sourceFileOfNode); + return ts.filter(commentRanges, isJsDocComment); + function isJsDocComment(comment) { + // True if the comment starts with '/**' but not if it is '/**/' + return sourceFileOfNode.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && + sourceFileOfNode.text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && + sourceFileOfNode.text.charCodeAt(comment.pos + 3) !== 47 /* slash */; + } + } + ts.getJsDocComments = getJsDocComments; + ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; + ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; + function isTypeNode(node) { + if (151 /* FirstTypeNode */ <= node.kind && node.kind <= 160 /* LastTypeNode */) { + return true; + } + switch (node.kind) { + case 117 /* AnyKeyword */: + case 128 /* NumberKeyword */: + case 130 /* StringKeyword */: + case 120 /* BooleanKeyword */: + case 131 /* SymbolKeyword */: + return true; + case 103 /* VoidKeyword */: + return node.parent.kind !== 177 /* VoidExpression */; + case 9 /* StringLiteral */: + // Specialized signatures can have string literals as their parameters' type names + return node.parent.kind === 138 /* Parameter */; + case 188 /* ExpressionWithTypeArguments */: + return !isExpressionWithTypeArgumentsInClassExtendsClause(node); + // Identifiers and qualified names may be type nodes, depending on their context. Climb + // above them to find the lowest container + case 69 /* Identifier */: + // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. + if (node.parent.kind === 135 /* QualifiedName */ && node.parent.right === node) { + node = node.parent; + } + else if (node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.name === node) { + node = node.parent; + } + // At this point, node is either a qualified name or an identifier + ts.Debug.assert(node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */ || node.kind === 166 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + case 135 /* QualifiedName */: + case 166 /* PropertyAccessExpression */: + case 97 /* ThisKeyword */: + var parent_1 = node.parent; + if (parent_1.kind === 154 /* TypeQuery */) { + return false; + } + // Do not recursively call isTypeNode on the parent. In the example: + // + // let a: A.B.C; + // + // Calling isTypeNode would consider the qualified name A.B a type node. Only C or + // A.B.C is a type node. + if (151 /* FirstTypeNode */ <= parent_1.kind && parent_1.kind <= 160 /* LastTypeNode */) { + return true; + } + switch (parent_1.kind) { + case 188 /* ExpressionWithTypeArguments */: + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); + case 137 /* TypeParameter */: + return node === parent_1.constraint; + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 138 /* Parameter */: + case 211 /* VariableDeclaration */: + return node === parent_1.type; + case 213 /* FunctionDeclaration */: + case 173 /* FunctionExpression */: + case 174 /* ArrowFunction */: + case 144 /* Constructor */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + return node === parent_1.type; + case 147 /* CallSignature */: + case 148 /* ConstructSignature */: + case 149 /* IndexSignature */: + return node === parent_1.type; + case 171 /* TypeAssertionExpression */: + return node === parent_1.type; + case 168 /* CallExpression */: + case 169 /* NewExpression */: + return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; + case 170 /* TaggedTemplateExpression */: + // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. + return false; + } + } + return false; + } + ts.isTypeNode = isTypeNode; + // Warning: This has the same semantics as the forEach family of functions, + // in that traversal terminates in the event that 'visitor' supplies a truthy value. + function forEachReturnStatement(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 204 /* ReturnStatement */: + return visitor(node); + case 220 /* CaseBlock */: + case 192 /* Block */: + case 196 /* IfStatement */: + case 197 /* DoStatement */: + case 198 /* WhileStatement */: + case 199 /* ForStatement */: + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + case 205 /* WithStatement */: + case 206 /* SwitchStatement */: + case 241 /* CaseClause */: + case 242 /* DefaultClause */: + case 207 /* LabeledStatement */: + case 209 /* TryStatement */: + case 244 /* CatchClause */: + return ts.forEachChild(node, traverse); + } + } + } + ts.forEachReturnStatement = forEachReturnStatement; + function forEachYieldExpression(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 184 /* YieldExpression */: + visitor(node); + var operand = node.expression; + if (operand) { + traverse(operand); + } + case 217 /* EnumDeclaration */: + case 215 /* InterfaceDeclaration */: + case 218 /* ModuleDeclaration */: + case 216 /* TypeAliasDeclaration */: + case 214 /* ClassDeclaration */: + case 186 /* ClassExpression */: + // These are not allowed inside a generator now, but eventually they may be allowed + // as local types. Regardless, any yield statements contained within them should be + // skipped in this traversal. + return; + default: + if (isFunctionLike(node)) { + var name_5 = node.name; + if (name_5 && name_5.kind === 136 /* ComputedPropertyName */) { + // Note that we will not include methods/accessors of a class because they would require + // first descending into the class. This is by design. + traverse(name_5.expression); + return; + } + } + else if (!isTypeNode(node)) { + // This is the general case, which should include mostly expressions and statements. + // Also includes NodeArrays. + ts.forEachChild(node, traverse); + } + } + } + } + ts.forEachYieldExpression = forEachYieldExpression; + function isVariableLike(node) { + if (node) { + switch (node.kind) { + case 163 /* BindingElement */: + case 247 /* EnumMember */: + case 138 /* Parameter */: + case 245 /* PropertyAssignment */: + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 246 /* ShorthandPropertyAssignment */: + case 211 /* VariableDeclaration */: + return true; + } + } + return false; + } + ts.isVariableLike = isVariableLike; + function isAccessor(node) { + return node && (node.kind === 145 /* GetAccessor */ || node.kind === 146 /* SetAccessor */); + } + ts.isAccessor = isAccessor; + function isClassLike(node) { + return node && (node.kind === 214 /* ClassDeclaration */ || node.kind === 186 /* ClassExpression */); + } + ts.isClassLike = isClassLike; + function isFunctionLike(node) { + if (node) { + switch (node.kind) { + case 144 /* Constructor */: + case 173 /* FunctionExpression */: + case 213 /* FunctionDeclaration */: + case 174 /* ArrowFunction */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 147 /* CallSignature */: + case 148 /* ConstructSignature */: + case 149 /* IndexSignature */: + case 152 /* FunctionType */: + case 153 /* ConstructorType */: + return true; + } + } + return false; + } + ts.isFunctionLike = isFunctionLike; + function introducesArgumentsExoticObject(node) { + switch (node.kind) { + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 144 /* Constructor */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 213 /* FunctionDeclaration */: + case 173 /* FunctionExpression */: + return true; + } + return false; + } + ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; + function isFunctionBlock(node) { + return node && node.kind === 192 /* Block */ && isFunctionLike(node.parent); + } + ts.isFunctionBlock = isFunctionBlock; + function isObjectLiteralMethod(node) { + return node && node.kind === 143 /* MethodDeclaration */ && node.parent.kind === 165 /* ObjectLiteralExpression */; + } + ts.isObjectLiteralMethod = isObjectLiteralMethod; + function getContainingFunction(node) { + while (true) { + node = node.parent; + if (!node || isFunctionLike(node)) { + return node; + } + } + } + ts.getContainingFunction = getContainingFunction; + function getContainingClass(node) { + while (true) { + node = node.parent; + if (!node || isClassLike(node)) { + return node; + } + } + } + ts.getContainingClass = getContainingClass; + function getThisContainer(node, includeArrowFunctions) { + while (true) { + node = node.parent; + if (!node) { + return undefined; + } + switch (node.kind) { + case 136 /* ComputedPropertyName */: + // If the grandparent node is an object literal (as opposed to a class), + // then the computed property is not a 'this' container. + // A computed property name in a class needs to be a this container + // so that we can error on it. + if (isClassLike(node.parent.parent)) { + return node; + } + // If this is a computed property, then the parent should not + // make it a this container. The parent might be a property + // in an object literal, like a method or accessor. But in order for + // such a parent to be a this container, the reference must be in + // the *body* of the container. + node = node.parent; + break; + case 139 /* Decorator */: + // Decorators are always applied outside of the body of a class or method. + if (node.parent.kind === 138 /* Parameter */ && isClassElement(node.parent.parent)) { + // If the decorator's parent is a Parameter, we resolve the this container from + // the grandparent class declaration. + node = node.parent.parent; + } + else if (isClassElement(node.parent)) { + // If the decorator's parent is a class element, we resolve the 'this' container + // from the parent class declaration. + node = node.parent; + } + break; + case 174 /* ArrowFunction */: + if (!includeArrowFunctions) { + continue; + } + // Fall through + case 213 /* FunctionDeclaration */: + case 173 /* FunctionExpression */: + case 218 /* ModuleDeclaration */: + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 144 /* Constructor */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 147 /* CallSignature */: + case 148 /* ConstructSignature */: + case 149 /* IndexSignature */: + case 217 /* EnumDeclaration */: + case 248 /* SourceFile */: + return node; + } + } + } + ts.getThisContainer = getThisContainer; + function getSuperContainer(node, includeFunctions) { + while (true) { + node = node.parent; + if (!node) + return node; + switch (node.kind) { + case 136 /* ComputedPropertyName */: + // If the grandparent node is an object literal (as opposed to a class), + // then the computed property is not a 'super' container. + // A computed property name in a class needs to be a super container + // so that we can error on it. + if (isClassLike(node.parent.parent)) { + return node; + } + // If this is a computed property, then the parent should not + // make it a super container. The parent might be a property + // in an object literal, like a method or accessor. But in order for + // such a parent to be a super container, the reference must be in + // the *body* of the container. + node = node.parent; + break; + case 139 /* Decorator */: + // Decorators are always applied outside of the body of a class or method. + if (node.parent.kind === 138 /* Parameter */ && isClassElement(node.parent.parent)) { + // If the decorator's parent is a Parameter, we resolve the this container from + // the grandparent class declaration. + node = node.parent.parent; + } + else if (isClassElement(node.parent)) { + // If the decorator's parent is a class element, we resolve the 'this' container + // from the parent class declaration. + node = node.parent; + } + break; + case 213 /* FunctionDeclaration */: + case 173 /* FunctionExpression */: + case 174 /* ArrowFunction */: + if (!includeFunctions) { + continue; + } + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 144 /* Constructor */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + return node; + } + } + } + ts.getSuperContainer = getSuperContainer; + function getEntityNameFromTypeNode(node) { + if (node) { + switch (node.kind) { + case 151 /* TypeReference */: + return node.typeName; + case 188 /* ExpressionWithTypeArguments */: + return node.expression; + case 69 /* Identifier */: + case 135 /* QualifiedName */: + return node; + } + } + return undefined; + } + ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; + function getInvokedExpression(node) { + if (node.kind === 170 /* TaggedTemplateExpression */) { + return node.tag; + } + // Will either be a CallExpression, NewExpression, or Decorator. + return node.expression; + } + ts.getInvokedExpression = getInvokedExpression; + function nodeCanBeDecorated(node) { + switch (node.kind) { + case 214 /* ClassDeclaration */: + // classes are valid targets + return true; + case 141 /* PropertyDeclaration */: + // property declarations are valid if their parent is a class declaration. + return node.parent.kind === 214 /* ClassDeclaration */; + case 138 /* Parameter */: + // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; + return node.parent.body && node.parent.parent.kind === 214 /* ClassDeclaration */; + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 143 /* MethodDeclaration */: + // if this method has a body and its parent is a class declaration, this is a valid target. + return node.body && node.parent.kind === 214 /* ClassDeclaration */; + } + return false; + } + ts.nodeCanBeDecorated = nodeCanBeDecorated; + function nodeIsDecorated(node) { + switch (node.kind) { + case 214 /* ClassDeclaration */: + if (node.decorators) { + return true; + } + return false; + case 141 /* PropertyDeclaration */: + case 138 /* Parameter */: + if (node.decorators) { + return true; + } + return false; + case 145 /* GetAccessor */: + if (node.body && node.decorators) { + return true; + } + return false; + case 143 /* MethodDeclaration */: + case 146 /* SetAccessor */: + if (node.body && node.decorators) { + return true; + } + return false; + } + return false; + } + ts.nodeIsDecorated = nodeIsDecorated; + function childIsDecorated(node) { + switch (node.kind) { + case 214 /* ClassDeclaration */: + return ts.forEach(node.members, nodeOrChildIsDecorated); + case 143 /* MethodDeclaration */: + case 146 /* SetAccessor */: + return ts.forEach(node.parameters, nodeIsDecorated); + } + return false; + } + ts.childIsDecorated = childIsDecorated; + function nodeOrChildIsDecorated(node) { + return nodeIsDecorated(node) || childIsDecorated(node); + } + ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; + function isPropertyAccessExpression(node) { + return node.kind === 166 /* PropertyAccessExpression */; + } + ts.isPropertyAccessExpression = isPropertyAccessExpression; + function isElementAccessExpression(node) { + return node.kind === 167 /* ElementAccessExpression */; + } + ts.isElementAccessExpression = isElementAccessExpression; + function isExpression(node) { + switch (node.kind) { + case 95 /* SuperKeyword */: + case 93 /* NullKeyword */: + case 99 /* TrueKeyword */: + case 84 /* FalseKeyword */: + case 10 /* RegularExpressionLiteral */: + case 164 /* ArrayLiteralExpression */: + case 165 /* ObjectLiteralExpression */: + case 166 /* PropertyAccessExpression */: + case 167 /* ElementAccessExpression */: + case 168 /* CallExpression */: + case 169 /* NewExpression */: + case 170 /* TaggedTemplateExpression */: + case 189 /* AsExpression */: + case 171 /* TypeAssertionExpression */: + case 172 /* ParenthesizedExpression */: + case 173 /* FunctionExpression */: + case 186 /* ClassExpression */: + case 174 /* ArrowFunction */: + case 177 /* VoidExpression */: + case 175 /* DeleteExpression */: + case 176 /* TypeOfExpression */: + case 179 /* PrefixUnaryExpression */: + case 180 /* PostfixUnaryExpression */: + case 181 /* BinaryExpression */: + case 182 /* ConditionalExpression */: + case 185 /* SpreadElementExpression */: + case 183 /* TemplateExpression */: + case 11 /* NoSubstitutionTemplateLiteral */: + case 187 /* OmittedExpression */: + case 233 /* JsxElement */: + case 234 /* JsxSelfClosingElement */: + case 184 /* YieldExpression */: + case 178 /* AwaitExpression */: + return true; + case 135 /* QualifiedName */: + while (node.parent.kind === 135 /* QualifiedName */) { + node = node.parent; + } + return node.parent.kind === 154 /* TypeQuery */; + case 69 /* Identifier */: + if (node.parent.kind === 154 /* TypeQuery */) { + return true; + } + // fall through + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 97 /* ThisKeyword */: + var parent_2 = node.parent; + switch (parent_2.kind) { + case 211 /* VariableDeclaration */: + case 138 /* Parameter */: + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 247 /* EnumMember */: + case 245 /* PropertyAssignment */: + case 163 /* BindingElement */: + return parent_2.initializer === node; + case 195 /* ExpressionStatement */: + case 196 /* IfStatement */: + case 197 /* DoStatement */: + case 198 /* WhileStatement */: + case 204 /* ReturnStatement */: + case 205 /* WithStatement */: + case 206 /* SwitchStatement */: + case 241 /* CaseClause */: + case 208 /* ThrowStatement */: + case 206 /* SwitchStatement */: + return parent_2.expression === node; + case 199 /* ForStatement */: + var forStatement = parent_2; + return (forStatement.initializer === node && forStatement.initializer.kind !== 212 /* VariableDeclarationList */) || + forStatement.condition === node || + forStatement.incrementor === node; + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + var forInStatement = parent_2; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 212 /* VariableDeclarationList */) || + forInStatement.expression === node; + case 171 /* TypeAssertionExpression */: + case 189 /* AsExpression */: + return node === parent_2.expression; + case 190 /* TemplateSpan */: + return node === parent_2.expression; + case 136 /* ComputedPropertyName */: + return node === parent_2.expression; + case 139 /* Decorator */: + case 240 /* JsxExpression */: + case 239 /* JsxSpreadAttribute */: + return true; + case 188 /* ExpressionWithTypeArguments */: + return parent_2.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_2); + default: + if (isExpression(parent_2)) { + return true; + } + } + } + return false; + } + ts.isExpression = isExpression; + function isExternalModuleNameRelative(moduleName) { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + return moduleName.substr(0, 2) === "./" || moduleName.substr(0, 3) === "../" || moduleName.substr(0, 2) === ".\\" || moduleName.substr(0, 3) === "..\\"; + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function isInstantiatedModule(node, preserveConstEnums) { + var moduleState = ts.getModuleInstanceState(node); + return moduleState === 1 /* Instantiated */ || + (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */); + } + ts.isInstantiatedModule = isInstantiatedModule; + function isExternalModuleImportEqualsDeclaration(node) { + return node.kind === 221 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 232 /* ExternalModuleReference */; + } + ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; + function getExternalModuleImportEqualsDeclarationExpression(node) { + ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node)); + return node.moduleReference.expression; + } + ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; + function isInternalModuleImportEqualsDeclaration(node) { + return node.kind === 221 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 232 /* ExternalModuleReference */; + } + ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; + function getExternalModuleName(node) { + if (node.kind === 222 /* ImportDeclaration */) { + return node.moduleSpecifier; + } + if (node.kind === 221 /* ImportEqualsDeclaration */) { + var reference = node.moduleReference; + if (reference.kind === 232 /* ExternalModuleReference */) { + return reference.expression; + } + } + if (node.kind === 228 /* ExportDeclaration */) { + return node.moduleSpecifier; + } + } + ts.getExternalModuleName = getExternalModuleName; + function hasQuestionToken(node) { + if (node) { + switch (node.kind) { + case 138 /* Parameter */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 246 /* ShorthandPropertyAssignment */: + case 245 /* PropertyAssignment */: + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + return node.questionToken !== undefined; + } + } + return false; + } + ts.hasQuestionToken = hasQuestionToken; + function isJSDocConstructSignature(node) { + return node.kind === 261 /* JSDocFunctionType */ && + node.parameters.length > 0 && + node.parameters[0].type.kind === 263 /* JSDocConstructorType */; + } + ts.isJSDocConstructSignature = isJSDocConstructSignature; + function getJSDocTag(node, kind) { + if (node && node.jsDocComment) { + for (var _i = 0, _a = node.jsDocComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.kind === kind) { + return tag; + } + } + } + } + function getJSDocTypeTag(node) { + return getJSDocTag(node, 269 /* JSDocTypeTag */); + } + ts.getJSDocTypeTag = getJSDocTypeTag; + function getJSDocReturnTag(node) { + return getJSDocTag(node, 268 /* JSDocReturnTag */); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + function getJSDocTemplateTag(node) { + return getJSDocTag(node, 270 /* JSDocTemplateTag */); + } + ts.getJSDocTemplateTag = getJSDocTemplateTag; + function getCorrespondingJSDocParameterTag(parameter) { + if (parameter.name && parameter.name.kind === 69 /* Identifier */) { + // If it's a parameter, see if the parent has a jsdoc comment with an @param + // annotation. + var parameterName = parameter.name.text; + var docComment = parameter.parent.jsDocComment; + if (docComment) { + return ts.forEach(docComment.tags, function (t) { + if (t.kind === 267 /* JSDocParameterTag */) { + var parameterTag = t; + var name_6 = parameterTag.preParameterName || parameterTag.postParameterName; + if (name_6.text === parameterName) { + return t; + } + } + }); + } + } + } + ts.getCorrespondingJSDocParameterTag = getCorrespondingJSDocParameterTag; + function hasRestParameter(s) { + return isRestParameter(ts.lastOrUndefined(s.parameters)); + } + ts.hasRestParameter = hasRestParameter; + function isRestParameter(node) { + if (node) { + if (node.parserContextFlags & 32 /* JavaScriptFile */) { + if (node.type && node.type.kind === 262 /* JSDocVariadicType */) { + return true; + } + var paramTag = getCorrespondingJSDocParameterTag(node); + if (paramTag && paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 262 /* JSDocVariadicType */; + } + } + return node.dotDotDotToken !== undefined; + } + return false; + } + ts.isRestParameter = isRestParameter; + function isLiteralKind(kind) { + return 8 /* FirstLiteralToken */ <= kind && kind <= 11 /* LastLiteralToken */; + } + ts.isLiteralKind = isLiteralKind; + function isTextualLiteralKind(kind) { + return kind === 9 /* StringLiteral */ || kind === 11 /* NoSubstitutionTemplateLiteral */; + } + ts.isTextualLiteralKind = isTextualLiteralKind; + function isTemplateLiteralKind(kind) { + return 11 /* FirstTemplateToken */ <= kind && kind <= 14 /* LastTemplateToken */; + } + ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isBindingPattern(node) { + return !!node && (node.kind === 162 /* ArrayBindingPattern */ || node.kind === 161 /* ObjectBindingPattern */); + } + ts.isBindingPattern = isBindingPattern; + function isNodeDescendentOf(node, ancestor) { + while (node) { + if (node === ancestor) + return true; + node = node.parent; + } + return false; + } + ts.isNodeDescendentOf = isNodeDescendentOf; + function isInAmbientContext(node) { + while (node) { + if (node.flags & (2 /* Ambient */ | 8192 /* DeclarationFile */)) { + return true; + } + node = node.parent; + } + return false; + } + ts.isInAmbientContext = isInAmbientContext; + function isDeclaration(node) { + switch (node.kind) { + case 174 /* ArrowFunction */: + case 163 /* BindingElement */: + case 214 /* ClassDeclaration */: + case 186 /* ClassExpression */: + case 144 /* Constructor */: + case 217 /* EnumDeclaration */: + case 247 /* EnumMember */: + case 230 /* ExportSpecifier */: + case 213 /* FunctionDeclaration */: + case 173 /* FunctionExpression */: + case 145 /* GetAccessor */: + case 223 /* ImportClause */: + case 221 /* ImportEqualsDeclaration */: + case 226 /* ImportSpecifier */: + case 215 /* InterfaceDeclaration */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 218 /* ModuleDeclaration */: + case 224 /* NamespaceImport */: + case 138 /* Parameter */: + case 245 /* PropertyAssignment */: + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 146 /* SetAccessor */: + case 246 /* ShorthandPropertyAssignment */: + case 216 /* TypeAliasDeclaration */: + case 137 /* TypeParameter */: + case 211 /* VariableDeclaration */: + return true; + } + return false; + } + ts.isDeclaration = isDeclaration; + function isStatement(n) { + switch (n.kind) { + case 203 /* BreakStatement */: + case 202 /* ContinueStatement */: + case 210 /* DebuggerStatement */: + case 197 /* DoStatement */: + case 195 /* ExpressionStatement */: + case 194 /* EmptyStatement */: + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + case 199 /* ForStatement */: + case 196 /* IfStatement */: + case 207 /* LabeledStatement */: + case 204 /* ReturnStatement */: + case 206 /* SwitchStatement */: + case 98 /* ThrowKeyword */: + case 209 /* TryStatement */: + case 193 /* VariableStatement */: + case 198 /* WhileStatement */: + case 205 /* WithStatement */: + case 227 /* ExportAssignment */: + return true; + default: + return false; + } + } + ts.isStatement = isStatement; + function isClassElement(n) { + switch (n.kind) { + case 144 /* Constructor */: + case 141 /* PropertyDeclaration */: + case 143 /* MethodDeclaration */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 142 /* MethodSignature */: + case 149 /* IndexSignature */: + return true; + default: + return false; + } + } + ts.isClassElement = isClassElement; + // True if the given identifier, string literal, or number literal is the name of a declaration node + function isDeclarationName(name) { + if (name.kind !== 69 /* Identifier */ && name.kind !== 9 /* StringLiteral */ && name.kind !== 8 /* NumericLiteral */) { + return false; + } + var parent = name.parent; + if (parent.kind === 226 /* ImportSpecifier */ || parent.kind === 230 /* ExportSpecifier */) { + if (parent.propertyName) { + return true; + } + } + if (isDeclaration(parent)) { + return parent.name === name; + } + return false; + } + ts.isDeclarationName = isDeclarationName; + // Return true if the given identifier is classified as an IdentifierName + function isIdentifierName(node) { + var parent = node.parent; + switch (parent.kind) { + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 247 /* EnumMember */: + case 245 /* PropertyAssignment */: + case 166 /* PropertyAccessExpression */: + // Name in member declaration or property name in property access + return parent.name === node; + case 135 /* QualifiedName */: + // Name on right hand side of dot in a type query + if (parent.right === node) { + while (parent.kind === 135 /* QualifiedName */) { + parent = parent.parent; + } + return parent.kind === 154 /* TypeQuery */; + } + return false; + case 163 /* BindingElement */: + case 226 /* ImportSpecifier */: + // Property name in binding element or import specifier + return parent.propertyName === node; + case 230 /* ExportSpecifier */: + // Any name in an export specifier + return true; + } + return false; + } + ts.isIdentifierName = isIdentifierName; + // An alias symbol is created by one of the following declarations: + // import = ... + // import from ... + // import * as from ... + // import { x as } from ... + // export { x as } from ... + // export = ... + // export default ... + function isAliasSymbolDeclaration(node) { + return node.kind === 221 /* ImportEqualsDeclaration */ || + node.kind === 223 /* ImportClause */ && !!node.name || + node.kind === 224 /* NamespaceImport */ || + node.kind === 226 /* ImportSpecifier */ || + node.kind === 230 /* ExportSpecifier */ || + node.kind === 227 /* ExportAssignment */ && node.expression.kind === 69 /* Identifier */; + } + ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; + function getClassExtendsHeritageClauseElement(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 83 /* ExtendsKeyword */); + return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; + } + ts.getClassExtendsHeritageClauseElement = getClassExtendsHeritageClauseElement; + function getClassImplementsHeritageClauseElements(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 106 /* ImplementsKeyword */); + return heritageClause ? heritageClause.types : undefined; + } + ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; + function getInterfaceBaseTypeNodes(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 83 /* ExtendsKeyword */); + return heritageClause ? heritageClause.types : undefined; + } + ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; + function getHeritageClause(clauses, kind) { + if (clauses) { + for (var _i = 0; _i < clauses.length; _i++) { + var clause = clauses[_i]; + if (clause.token === kind) { + return clause; + } + } + } + return undefined; + } + ts.getHeritageClause = getHeritageClause; + function tryResolveScriptReference(host, sourceFile, reference) { + if (!host.getCompilerOptions().noResolve) { + var referenceFileName = ts.isRootedDiskPath(reference.fileName) ? reference.fileName : ts.combinePaths(ts.getDirectoryPath(sourceFile.fileName), reference.fileName); + referenceFileName = ts.getNormalizedAbsolutePath(referenceFileName, host.getCurrentDirectory()); + return host.getSourceFile(referenceFileName); + } + } + ts.tryResolveScriptReference = tryResolveScriptReference; + function getAncestor(node, kind) { + while (node) { + if (node.kind === kind) { + return node; + } + node = node.parent; + } + return undefined; + } + ts.getAncestor = getAncestor; + function getFileReferenceFromReferencePath(comment, commentRange) { + var simpleReferenceRegEx = /^\/\/\/\s*/gim; + if (simpleReferenceRegEx.exec(comment)) { + if (isNoDefaultLibRegEx.exec(comment)) { + return { + isNoDefaultLib: true + }; + } + else { + var matchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); + if (matchResult) { + var start = commentRange.pos; + var end = commentRange.end; + return { + fileReference: { + pos: start, + end: end, + fileName: matchResult[3] + }, + isNoDefaultLib: false + }; + } + else { + return { + diagnosticMessage: ts.Diagnostics.Invalid_reference_directive_syntax, + isNoDefaultLib: false + }; + } + } + } + return undefined; + } + ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; + function isKeyword(token) { + return 70 /* FirstKeyword */ <= token && token <= 134 /* LastKeyword */; + } + ts.isKeyword = isKeyword; + function isTrivia(token) { + return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */; + } + ts.isTrivia = isTrivia; + function isAsyncFunctionLike(node) { + return isFunctionLike(node) && (node.flags & 512 /* Async */) !== 0 && !isAccessor(node); + } + ts.isAsyncFunctionLike = isAsyncFunctionLike; + /** + * A declaration has a dynamic name if both of the following are true: + * 1. The declaration has a computed property name + * 2. The computed name is *not* expressed as Symbol., where name + * is a property of the Symbol constructor that denotes a built in + * Symbol. + */ + function hasDynamicName(declaration) { + return declaration.name && + declaration.name.kind === 136 /* ComputedPropertyName */ && + !isWellKnownSymbolSyntactically(declaration.name.expression); + } + ts.hasDynamicName = hasDynamicName; + /** + * Checks if the expression is of the form: + * Symbol.name + * where Symbol is literally the word "Symbol", and name is any identifierName + */ + function isWellKnownSymbolSyntactically(node) { + return isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); + } + ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; + function getPropertyNameForPropertyNameNode(name) { + if (name.kind === 69 /* Identifier */ || name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */) { + return name.text; + } + if (name.kind === 136 /* ComputedPropertyName */) { + var nameExpression = name.expression; + if (isWellKnownSymbolSyntactically(nameExpression)) { + var rightHandSideName = nameExpression.name.text; + return getPropertyNameForKnownSymbolName(rightHandSideName); + } + } + return undefined; + } + ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; + function getPropertyNameForKnownSymbolName(symbolName) { + return "__@" + symbolName; + } + ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + /** + * Includes the word "Symbol" with unicode escapes + */ + function isESSymbolIdentifier(node) { + return node.kind === 69 /* Identifier */ && node.text === "Symbol"; + } + ts.isESSymbolIdentifier = isESSymbolIdentifier; + function isModifier(token) { + switch (token) { + case 115 /* AbstractKeyword */: + case 118 /* AsyncKeyword */: + case 74 /* ConstKeyword */: + case 122 /* DeclareKeyword */: + case 77 /* DefaultKeyword */: + case 82 /* ExportKeyword */: + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + case 113 /* StaticKeyword */: + return true; + } + return false; + } + ts.isModifier = isModifier; + function isParameterDeclaration(node) { + var root = getRootDeclaration(node); + return root.kind === 138 /* Parameter */; + } + ts.isParameterDeclaration = isParameterDeclaration; + function getRootDeclaration(node) { + while (node.kind === 163 /* BindingElement */) { + node = node.parent.parent; + } + return node; + } + ts.getRootDeclaration = getRootDeclaration; + function nodeStartsNewLexicalEnvironment(n) { + return isFunctionLike(n) || n.kind === 218 /* ModuleDeclaration */ || n.kind === 248 /* SourceFile */; + } + ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; + function cloneEntityName(node) { + if (node.kind === 69 /* Identifier */) { + var clone_1 = createSynthesizedNode(69 /* Identifier */); + clone_1.text = node.text; + return clone_1; + } + else { + var clone_2 = createSynthesizedNode(135 /* QualifiedName */); + clone_2.left = cloneEntityName(node.left); + clone_2.left.parent = clone_2; + clone_2.right = cloneEntityName(node.right); + clone_2.right.parent = clone_2; + return clone_2; + } + } + ts.cloneEntityName = cloneEntityName; + function nodeIsSynthesized(node) { + return node.pos === -1; + } + ts.nodeIsSynthesized = nodeIsSynthesized; + function createSynthesizedNode(kind, startsOnNewLine) { + var node = ts.createNode(kind); + node.startsOnNewLine = startsOnNewLine; + return node; + } + ts.createSynthesizedNode = createSynthesizedNode; + function createSynthesizedNodeArray() { + var array = []; + array.pos = -1; + array.end = -1; + return array; + } + ts.createSynthesizedNodeArray = createSynthesizedNodeArray; + function createDiagnosticCollection() { + var nonFileDiagnostics = []; + var fileDiagnostics = {}; + var diagnosticsModified = false; + var modificationCount = 0; + return { + add: add, + getGlobalDiagnostics: getGlobalDiagnostics, + getDiagnostics: getDiagnostics, + getModificationCount: getModificationCount, + reattachFileDiagnostics: reattachFileDiagnostics + }; + function getModificationCount() { + return modificationCount; + } + function reattachFileDiagnostics(newFile) { + if (!ts.hasProperty(fileDiagnostics, newFile.fileName)) { + return; + } + for (var _i = 0, _a = fileDiagnostics[newFile.fileName]; _i < _a.length; _i++) { + var diagnostic = _a[_i]; + diagnostic.file = newFile; + } + } + function add(diagnostic) { + var diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics[diagnostic.file.fileName]; + if (!diagnostics) { + diagnostics = []; + fileDiagnostics[diagnostic.file.fileName] = diagnostics; + } + } + else { + diagnostics = nonFileDiagnostics; + } + diagnostics.push(diagnostic); + diagnosticsModified = true; + modificationCount++; + } + function getGlobalDiagnostics() { + sortAndDeduplicate(); + return nonFileDiagnostics; + } + function getDiagnostics(fileName) { + sortAndDeduplicate(); + if (fileName) { + return fileDiagnostics[fileName] || []; + } + var allDiagnostics = []; + function pushDiagnostic(d) { + allDiagnostics.push(d); + } + ts.forEach(nonFileDiagnostics, pushDiagnostic); + for (var key in fileDiagnostics) { + if (ts.hasProperty(fileDiagnostics, key)) { + ts.forEach(fileDiagnostics[key], pushDiagnostic); + } + } + return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + } + function sortAndDeduplicate() { + if (!diagnosticsModified) { + return; + } + diagnosticsModified = false; + nonFileDiagnostics = ts.sortAndDeduplicateDiagnostics(nonFileDiagnostics); + for (var key in fileDiagnostics) { + if (ts.hasProperty(fileDiagnostics, key)) { + fileDiagnostics[key] = ts.sortAndDeduplicateDiagnostics(fileDiagnostics[key]); + } + } + } + } + ts.createDiagnosticCollection = createDiagnosticCollection; + // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator, + // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in + // the language service. These characters should be escaped when printing, and if any characters are added, + // the map below must be updated. Note that this regexp *does not* include the 'delete' character. + // There is no reason for this other than that JSON.stringify does not handle it either. + var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var escapedCharsMap = { + "\0": "\\0", + "\t": "\\t", + "\v": "\\v", + "\f": "\\f", + "\b": "\\b", + "\r": "\\r", + "\n": "\\n", + "\\": "\\\\", + "\"": "\\\"", + "\u2028": "\\u2028", + "\u2029": "\\u2029", + "\u0085": "\\u0085" // nextLine + }; + /** + * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2), + * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine) + * Note that this doesn't actually wrap the input in double quotes. + */ + function escapeString(s) { + s = escapedCharsRegExp.test(s) ? s.replace(escapedCharsRegExp, getReplacement) : s; + return s; + function getReplacement(c) { + return escapedCharsMap[c] || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); + } + } + ts.escapeString = escapeString; + function isIntrinsicJsxName(name) { + var ch = name.substr(0, 1); + return ch.toLowerCase() === ch; + } + ts.isIntrinsicJsxName = isIntrinsicJsxName; + function get16BitUnicodeEscapeSequence(charCode) { + var hexCharCode = charCode.toString(16).toUpperCase(); + var paddedHexCode = ("0000" + hexCharCode).slice(-4); + return "\\u" + paddedHexCode; + } + var nonAsciiCharacters = /[^\u0000-\u007F]/g; + function escapeNonAsciiCharacters(s) { + // Replace non-ASCII characters with '\uNNNN' escapes if any exist. + // Otherwise just return the original string. + return nonAsciiCharacters.test(s) ? + s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : + s; + } + ts.escapeNonAsciiCharacters = escapeNonAsciiCharacters; + var indentStrings = ["", " "]; + function getIndentString(level) { + if (indentStrings[level] === undefined) { + indentStrings[level] = getIndentString(level - 1) + indentStrings[1]; + } + return indentStrings[level]; + } + ts.getIndentString = getIndentString; + function getIndentSize() { + return indentStrings[1].length; + } + ts.getIndentSize = getIndentSize; + function createTextWriter(newLine) { + var output = ""; + var indent = 0; + var lineStart = true; + var lineCount = 0; + var linePos = 0; + function write(s) { + if (s && s.length) { + if (lineStart) { + output += getIndentString(indent); + lineStart = false; + } + output += s; + } + } + function rawWrite(s) { + if (s !== undefined) { + if (lineStart) { + lineStart = false; + } + output += s; + } + } + function writeLiteral(s) { + if (s && s.length) { + write(s); + var lineStartsOfS = ts.computeLineStarts(s); + if (lineStartsOfS.length > 1) { + lineCount = lineCount + lineStartsOfS.length - 1; + linePos = output.length - s.length + ts.lastOrUndefined(lineStartsOfS); + } + } + } + function writeLine() { + if (!lineStart) { + output += newLine; + lineCount++; + linePos = output.length; + lineStart = true; + } + } + function writeTextOfNode(sourceFile, node) { + write(getSourceTextOfNodeFromSourceFile(sourceFile, node)); + } + return { + write: write, + rawWrite: rawWrite, + writeTextOfNode: writeTextOfNode, + writeLiteral: writeLiteral, + writeLine: writeLine, + increaseIndent: function () { return indent++; }, + decreaseIndent: function () { return indent--; }, + getIndent: function () { return indent; }, + getTextPos: function () { return output.length; }, + getLine: function () { return lineCount + 1; }, + getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, + getText: function () { return output; } + }; + } + ts.createTextWriter = createTextWriter; + function getOwnEmitOutputFilePath(sourceFile, host, extension) { + var compilerOptions = host.getCompilerOptions(); + var emitOutputFilePathWithoutExtension; + if (compilerOptions.outDir) { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); + } + else { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.fileName); + } + return emitOutputFilePathWithoutExtension + extension; + } + ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; + function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { + var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); + sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); + return ts.combinePaths(newDirPath, sourceFilePath); + } + ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + function writeFile(host, diagnostics, fileName, data, writeByteOrderMark) { + host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { + diagnostics.push(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + }); + } + ts.writeFile = writeFile; + function getLineOfLocalPosition(currentSourceFile, pos) { + return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; + } + ts.getLineOfLocalPosition = getLineOfLocalPosition; + function getFirstConstructorWithBody(node) { + return ts.forEach(node.members, function (member) { + if (member.kind === 144 /* Constructor */ && nodeIsPresent(member.body)) { + return member; + } + }); + } + ts.getFirstConstructorWithBody = getFirstConstructorWithBody; + function getSetAccessorTypeAnnotationNode(accessor) { + return accessor && accessor.parameters.length > 0 && accessor.parameters[0].type; + } + ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function shouldEmitToOwnFile(sourceFile, compilerOptions) { + if (!isDeclarationFile(sourceFile)) { + if ((isExternalModule(sourceFile) || !(compilerOptions.outFile || compilerOptions.out))) { + // 1. in-browser single file compilation scenario + // 2. non .js file + return compilerOptions.isolatedModules || !ts.fileExtensionIs(sourceFile.fileName, ".js"); + } + return false; + } + return false; + } + ts.shouldEmitToOwnFile = shouldEmitToOwnFile; + function getAllAccessorDeclarations(declarations, accessor) { + var firstAccessor; + var secondAccessor; + var getAccessor; + var setAccessor; + if (hasDynamicName(accessor)) { + firstAccessor = accessor; + if (accessor.kind === 145 /* GetAccessor */) { + getAccessor = accessor; + } + else if (accessor.kind === 146 /* SetAccessor */) { + setAccessor = accessor; + } + else { + ts.Debug.fail("Accessor has wrong kind"); + } + } + else { + ts.forEach(declarations, function (member) { + if ((member.kind === 145 /* GetAccessor */ || member.kind === 146 /* SetAccessor */) + && (member.flags & 128 /* Static */) === (accessor.flags & 128 /* Static */)) { + var memberName = getPropertyNameForPropertyNameNode(member.name); + var accessorName = getPropertyNameForPropertyNameNode(accessor.name); + if (memberName === accessorName) { + if (!firstAccessor) { + firstAccessor = member; + } + else if (!secondAccessor) { + secondAccessor = member; + } + if (member.kind === 145 /* GetAccessor */ && !getAccessor) { + getAccessor = member; + } + if (member.kind === 146 /* SetAccessor */ && !setAccessor) { + setAccessor = member; + } + } + } + }); + } + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + getAccessor: getAccessor, + setAccessor: setAccessor + }; + } + ts.getAllAccessorDeclarations = getAllAccessorDeclarations; + function emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments) { + // If the leading comments start on different line than the start of node, write new line + if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos && + getLineOfLocalPosition(currentSourceFile, node.pos) !== getLineOfLocalPosition(currentSourceFile, leadingComments[0].pos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; + function emitComments(currentSourceFile, writer, comments, trailingSeparator, newLine, writeComment) { + var emitLeadingSpace = !trailingSeparator; + ts.forEach(comments, function (comment) { + if (emitLeadingSpace) { + writer.write(" "); + emitLeadingSpace = false; + } + writeComment(currentSourceFile, writer, comment, newLine); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + else if (trailingSeparator) { + writer.write(" "); + } + else { + // Emit leading space to separate comment during next comment emit + emitLeadingSpace = true; + } + }); + } + ts.emitComments = emitComments; + function writeCommentRange(currentSourceFile, writer, comment, newLine) { + if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { + var firstCommentLineAndCharacter = ts.getLineAndCharacterOfPosition(currentSourceFile, comment.pos); + var lineCount = ts.getLineStarts(currentSourceFile).length; + var firstCommentLineIndent; + for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { + var nextLineStart = (currentLine + 1) === lineCount + ? currentSourceFile.text.length + 1 + : getStartPositionOfLine(currentLine + 1, currentSourceFile); + if (pos !== comment.pos) { + // If we are not emitting first line, we need to write the spaces to adjust the alignment + if (firstCommentLineIndent === undefined) { + firstCommentLineIndent = calculateIndent(getStartPositionOfLine(firstCommentLineAndCharacter.line, currentSourceFile), comment.pos); + } + // These are number of spaces writer is going to write at current indent + var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); + // Number of spaces we want to be writing + // eg: Assume writer indent + // module m { + // /* starts at character 9 this is line 1 + // * starts at character pos 4 line --1 = 8 - 8 + 3 + // More left indented comment */ --2 = 8 - 8 + 2 + // class c { } + // } + // module m { + // /* this is line 1 -- Assume current writer indent 8 + // * line --3 = 8 - 4 + 5 + // More right indented comment */ --4 = 8 - 4 + 11 + // class c { } + // } + var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart); + if (spacesToEmit > 0) { + var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); + var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); + // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces + writer.rawWrite(indentSizeSpaceString); + // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces) + while (numberOfSingleSpacesToEmit) { + writer.rawWrite(" "); + numberOfSingleSpacesToEmit--; + } + } + else { + // No spaces to emit write empty string + writer.rawWrite(""); + } + } + // Write the comment line text + writeTrimmedCurrentLine(pos, nextLineStart); + pos = nextLineStart; + } + } + else { + // Single line comment of style //.... + writer.write(currentSourceFile.text.substring(comment.pos, comment.end)); + } + function writeTrimmedCurrentLine(pos, nextLineStart) { + var end = Math.min(comment.end, nextLineStart - 1); + var currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, ""); + if (currentLineText) { + // trimmed forward and ending spaces text + writer.write(currentLineText); + if (end !== comment.end) { + writer.writeLine(); + } + } + else { + // Empty string - make sure we write empty line + writer.writeLiteral(newLine); + } + } + function calculateIndent(pos, end) { + var currentLineIndent = 0; + for (; pos < end && ts.isWhiteSpace(currentSourceFile.text.charCodeAt(pos)); pos++) { + if (currentSourceFile.text.charCodeAt(pos) === 9 /* tab */) { + // Tabs = TabSize = indent size and go to next tabStop + currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); + } + else { + // Single space + currentLineIndent++; + } + } + return currentLineIndent; + } + } + ts.writeCommentRange = writeCommentRange; + function modifierToFlag(token) { + switch (token) { + case 113 /* StaticKeyword */: return 128 /* Static */; + case 112 /* PublicKeyword */: return 16 /* Public */; + case 111 /* ProtectedKeyword */: return 64 /* Protected */; + case 110 /* PrivateKeyword */: return 32 /* Private */; + case 115 /* AbstractKeyword */: return 256 /* Abstract */; + case 82 /* ExportKeyword */: return 1 /* Export */; + case 122 /* DeclareKeyword */: return 2 /* Ambient */; + case 74 /* ConstKeyword */: return 32768 /* Const */; + case 77 /* DefaultKeyword */: return 1024 /* Default */; + case 118 /* AsyncKeyword */: return 512 /* Async */; + } + return 0; + } + ts.modifierToFlag = modifierToFlag; + function isLeftHandSideExpression(expr) { + if (expr) { + switch (expr.kind) { + case 166 /* PropertyAccessExpression */: + case 167 /* ElementAccessExpression */: + case 169 /* NewExpression */: + case 168 /* CallExpression */: + case 233 /* JsxElement */: + case 234 /* JsxSelfClosingElement */: + case 170 /* TaggedTemplateExpression */: + case 164 /* ArrayLiteralExpression */: + case 172 /* ParenthesizedExpression */: + case 165 /* ObjectLiteralExpression */: + case 186 /* ClassExpression */: + case 173 /* FunctionExpression */: + case 69 /* Identifier */: + case 10 /* RegularExpressionLiteral */: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 11 /* NoSubstitutionTemplateLiteral */: + case 183 /* TemplateExpression */: + case 84 /* FalseKeyword */: + case 93 /* NullKeyword */: + case 97 /* ThisKeyword */: + case 99 /* TrueKeyword */: + case 95 /* SuperKeyword */: + return true; + } + } + return false; + } + ts.isLeftHandSideExpression = isLeftHandSideExpression; + function isAssignmentOperator(token) { + return token >= 56 /* FirstAssignment */ && token <= 68 /* LastAssignment */; + } + ts.isAssignmentOperator = isAssignmentOperator; + function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return node.kind === 188 /* ExpressionWithTypeArguments */ && + node.parent.token === 83 /* ExtendsKeyword */ && + isClassLike(node.parent.parent); + } + ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; + // Returns false if this heritage clause element's expression contains something unsupported + // (i.e. not a name or dotted name). + function isSupportedExpressionWithTypeArguments(node) { + return isSupportedExpressionWithTypeArgumentsRest(node.expression); + } + ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; + function isSupportedExpressionWithTypeArgumentsRest(node) { + if (node.kind === 69 /* Identifier */) { + return true; + } + else if (isPropertyAccessExpression(node)) { + return isSupportedExpressionWithTypeArgumentsRest(node.expression); + } + else { + return false; + } + } + function isRightSideOfQualifiedNameOrPropertyAccess(node) { + return (node.parent.kind === 135 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.name === node); + } + ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; + function isEmptyObjectLiteralOrArrayLiteral(expression) { + var kind = expression.kind; + if (kind === 165 /* ObjectLiteralExpression */) { + return expression.properties.length === 0; + } + if (kind === 164 /* ArrayLiteralExpression */) { + return expression.elements.length === 0; + } + return false; + } + ts.isEmptyObjectLiteralOrArrayLiteral = isEmptyObjectLiteralOrArrayLiteral; + function getLocalSymbolForExportDefault(symbol) { + return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 1024 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; + } + ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; + function isJavaScript(fileName) { + return ts.fileExtensionIs(fileName, ".js"); + } + ts.isJavaScript = isJavaScript; + function isTsx(fileName) { + return ts.fileExtensionIs(fileName, ".tsx"); + } + ts.isTsx = isTsx; + /** + * Replace each instance of non-ascii characters by one, two, three, or four escape sequences + * representing the UTF-8 encoding of the character, and return the expanded char code list. + */ + function getExpandedCharCodes(input) { + var output = []; + var length = input.length; + for (var i = 0; i < length; i++) { + var charCode = input.charCodeAt(i); + // handel utf8 + if (charCode < 0x80) { + output.push(charCode); + } + else if (charCode < 0x800) { + output.push((charCode >> 6) | 192); + output.push((charCode & 63) | 128); + } + else if (charCode < 0x10000) { + output.push((charCode >> 12) | 224); + output.push(((charCode >> 6) & 63) | 128); + output.push((charCode & 63) | 128); + } + else if (charCode < 0x20000) { + output.push((charCode >> 18) | 240); + output.push(((charCode >> 12) & 63) | 128); + output.push(((charCode >> 6) & 63) | 128); + output.push((charCode & 63) | 128); + } + else { + ts.Debug.assert(false, "Unexpected code point"); + } + } + return output; + } + var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + /** + * Converts a string to a base-64 encoded ASCII string. + */ + function convertToBase64(input) { + var result = ""; + var charCodes = getExpandedCharCodes(input); + var i = 0; + var length = charCodes.length; + var byte1, byte2, byte3, byte4; + while (i < length) { + // Convert every 6-bits in the input 3 character points + // into a base64 digit + byte1 = charCodes[i] >> 2; + byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4; + byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6; + byte4 = charCodes[i + 2] & 63; + // We are out of characters in the input, set the extra + // digits to 64 (padding character). + if (i + 1 >= length) { + byte3 = byte4 = 64; + } + else if (i + 2 >= length) { + byte4 = 64; + } + // Write to the ouput + result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4); + i += 3; + } + return result; + } + ts.convertToBase64 = convertToBase64; + var carriageReturnLineFeed = "\r\n"; + var lineFeed = "\n"; + function getNewLineCharacter(options) { + if (options.newLine === 0 /* CarriageReturnLineFeed */) { + return carriageReturnLineFeed; + } + else if (options.newLine === 1 /* LineFeed */) { + return lineFeed; + } + else if (ts.sys) { + return ts.sys.newLine; + } + return carriageReturnLineFeed; + } + ts.getNewLineCharacter = getNewLineCharacter; +})(ts || (ts = {})); +var ts; +(function (ts) { + function getDefaultLibFileName(options) { + return options.target === 2 /* ES6 */ ? "lib.es6.d.ts" : "lib.d.ts"; + } + ts.getDefaultLibFileName = getDefaultLibFileName; + function textSpanEnd(span) { + return span.start + span.length; + } + ts.textSpanEnd = textSpanEnd; + function textSpanIsEmpty(span) { + return span.length === 0; + } + ts.textSpanIsEmpty = textSpanIsEmpty; + function textSpanContainsPosition(span, position) { + return position >= span.start && position < textSpanEnd(span); + } + ts.textSpanContainsPosition = textSpanContainsPosition; + // Returns true if 'span' contains 'other'. + function textSpanContainsTextSpan(span, other) { + return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); + } + ts.textSpanContainsTextSpan = textSpanContainsTextSpan; + function textSpanOverlapsWith(span, other) { + var overlapStart = Math.max(span.start, other.start); + var overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other)); + return overlapStart < overlapEnd; + } + ts.textSpanOverlapsWith = textSpanOverlapsWith; + function textSpanOverlap(span1, span2) { + var overlapStart = Math.max(span1.start, span2.start); + var overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + if (overlapStart < overlapEnd) { + return createTextSpanFromBounds(overlapStart, overlapEnd); + } + return undefined; + } + ts.textSpanOverlap = textSpanOverlap; + function textSpanIntersectsWithTextSpan(span, other) { + return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start; + } + ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan; + function textSpanIntersectsWith(span, start, length) { + var end = start + length; + return start <= textSpanEnd(span) && end >= span.start; + } + ts.textSpanIntersectsWith = textSpanIntersectsWith; + function decodedTextSpanIntersectsWith(start1, length1, start2, length2) { + var end1 = start1 + length1; + var end2 = start2 + length2; + return start2 <= end1 && end2 >= start1; + } + ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith; + function textSpanIntersectsWithPosition(span, position) { + return position <= textSpanEnd(span) && position >= span.start; + } + ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition; + function textSpanIntersection(span1, span2) { + var intersectStart = Math.max(span1.start, span2.start); + var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + if (intersectStart <= intersectEnd) { + return createTextSpanFromBounds(intersectStart, intersectEnd); + } + return undefined; + } + ts.textSpanIntersection = textSpanIntersection; + function createTextSpan(start, length) { + if (start < 0) { + throw new Error("start < 0"); + } + if (length < 0) { + throw new Error("length < 0"); + } + return { start: start, length: length }; + } + ts.createTextSpan = createTextSpan; + function createTextSpanFromBounds(start, end) { + return createTextSpan(start, end - start); + } + ts.createTextSpanFromBounds = createTextSpanFromBounds; + function textChangeRangeNewSpan(range) { + return createTextSpan(range.span.start, range.newLength); + } + ts.textChangeRangeNewSpan = textChangeRangeNewSpan; + function textChangeRangeIsUnchanged(range) { + return textSpanIsEmpty(range.span) && range.newLength === 0; + } + ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged; + function createTextChangeRange(span, newLength) { + if (newLength < 0) { + throw new Error("newLength < 0"); + } + return { span: span, newLength: newLength }; + } + ts.createTextChangeRange = createTextChangeRange; + ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); + /** + * Called to merge all the changes that occurred across several versions of a script snapshot + * into a single change. i.e. if a user keeps making successive edits to a script we will + * have a text change from V1 to V2, V2 to V3, ..., Vn. + * + * This function will then merge those changes into a single change range valid between V1 and + * Vn. + */ + function collapseTextChangeRangesAcrossMultipleVersions(changes) { + if (changes.length === 0) { + return ts.unchangedTextChangeRange; + } + if (changes.length === 1) { + return changes[0]; + } + // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd } + // as it makes things much easier to reason about. + var change0 = changes[0]; + var oldStartN = change0.span.start; + var oldEndN = textSpanEnd(change0.span); + var newEndN = oldStartN + change0.newLength; + for (var i = 1; i < changes.length; i++) { + var nextChange = changes[i]; + // Consider the following case: + // i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting + // at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }. + // i.e. the span starting at 30 with length 30 is increased to length 40. + // + // 0 10 20 30 40 50 60 70 80 90 100 + // ------------------------------------------------------------------------------------------------------- + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ------------------------------------------------------------------------------------------------------- + // | \ + // | \ + // T2 | \ + // | \ + // | \ + // ------------------------------------------------------------------------------------------------------- + // + // Merging these turns out to not be too difficult. First, determining the new start of the change is trivial + // it's just the min of the old and new starts. i.e.: + // + // 0 10 20 30 40 50 60 70 80 90 100 + // ------------------------------------------------------------*------------------------------------------ + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ----------------------------------------$-------------------$------------------------------------------ + // . | \ + // . | \ + // T2 . | \ + // . | \ + // . | \ + // ----------------------------------------------------------------------*-------------------------------- + // + // (Note the dots represent the newly inferrred start. + // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the + // absolute positions at the asterixes, and the relative change between the dollar signs. Basically, we see + // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that + // means: + // + // 0 10 20 30 40 50 60 70 80 90 100 + // --------------------------------------------------------------------------------*---------------------- + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ------------------------------------------------------------$------------------------------------------ + // . | \ + // . | \ + // T2 . | \ + // . | \ + // . | \ + // ----------------------------------------------------------------------*-------------------------------- + // + // In other words (in this case), we're recognizing that the second edit happened after where the first edit + // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started + // that's the same as if we started at char 80 instead of 60. + // + // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rahter + // than pusing the first edit forward to match the second, we'll push the second edit forward to match the + // first. + // + // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange + // semantics: { { start: 10, length: 70 }, newLength: 60 } + // + // The math then works out as follows. + // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the + // final result like so: + // + // { + // oldStart3: Min(oldStart1, oldStart2), + // oldEnd3 : Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), + // newEnd3 : Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) + // } + var oldStart1 = oldStartN; + var oldEnd1 = oldEndN; + var newEnd1 = newEndN; + var oldStart2 = nextChange.span.start; + var oldEnd2 = textSpanEnd(nextChange.span); + var newEnd2 = oldStart2 + nextChange.newLength; + oldStartN = Math.min(oldStart1, oldStart2); + oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); + newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + } + return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength:*/ newEndN - oldStartN); + } + ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; + function getTypeParameterOwner(d) { + if (d && d.kind === 137 /* TypeParameter */) { + for (var current = d; current; current = current.parent) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 215 /* InterfaceDeclaration */) { + return current; + } + } + } + } + ts.getTypeParameterOwner = getTypeParameterOwner; + function arrayStructurallyIsEqualTo(array1, array2) { + if (!array1 || !array2) { + return false; + } + if (array1.length !== array2.length) { + return false; + } + return ts.arrayIsEqualTo(array1.sort(), array2.sort()); + } + ts.arrayStructurallyIsEqualTo = arrayStructurallyIsEqualTo; +})(ts || (ts = {})); +/// +/// +var ts; +(function (ts) { + var nodeConstructors = new Array(272 /* Count */); + /* @internal */ ts.parseTime = 0; + function getNodeConstructor(kind) { + return nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)); + } + ts.getNodeConstructor = getNodeConstructor; + function createNode(kind) { + return new (getNodeConstructor(kind))(); + } + ts.createNode = createNode; + function visitNode(cbNode, node) { + if (node) { + return cbNode(node); + } + } + function visitNodeArray(cbNodes, nodes) { + if (nodes) { + return cbNodes(nodes); + } + } + function visitEachNode(cbNode, nodes) { + if (nodes) { + for (var _i = 0; _i < nodes.length; _i++) { + var node = nodes[_i]; + var result = cbNode(node); + if (result) { + return result; + } + } + } + } + // Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes + // stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, + // embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns + // a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. + function forEachChild(node, cbNode, cbNodeArray) { + if (!node) { + return; + } + // The visitXXX functions could be written as local functions that close over the cbNode and cbNodeArray + // callback parameters, but that causes a closure allocation for each invocation with noticeable effects + // on performance. + var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; + var cbNodes = cbNodeArray || cbNode; + switch (node.kind) { + case 135 /* QualifiedName */: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.right); + case 137 /* TypeParameter */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.constraint) || + visitNode(cbNode, node.expression); + case 246 /* ShorthandPropertyAssignment */: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.equalsToken) || + visitNode(cbNode, node.objectAssignmentInitializer); + case 138 /* Parameter */: + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 245 /* PropertyAssignment */: + case 211 /* VariableDeclaration */: + case 163 /* BindingElement */: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 152 /* FunctionType */: + case 153 /* ConstructorType */: + case 147 /* CallSignature */: + case 148 /* ConstructSignature */: + case 149 /* IndexSignature */: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNodes(cbNodes, node.typeParameters) || + visitNodes(cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 144 /* Constructor */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 173 /* FunctionExpression */: + case 213 /* FunctionDeclaration */: + case 174 /* ArrowFunction */: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNodes(cbNodes, node.typeParameters) || + visitNodes(cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.equalsGreaterThanToken) || + visitNode(cbNode, node.body); + case 151 /* TypeReference */: + return visitNode(cbNode, node.typeName) || + visitNodes(cbNodes, node.typeArguments); + case 150 /* TypePredicate */: + return visitNode(cbNode, node.parameterName) || + visitNode(cbNode, node.type); + case 154 /* TypeQuery */: + return visitNode(cbNode, node.exprName); + case 155 /* TypeLiteral */: + return visitNodes(cbNodes, node.members); + case 156 /* ArrayType */: + return visitNode(cbNode, node.elementType); + case 157 /* TupleType */: + return visitNodes(cbNodes, node.elementTypes); + case 158 /* UnionType */: + case 159 /* IntersectionType */: + return visitNodes(cbNodes, node.types); + case 160 /* ParenthesizedType */: + return visitNode(cbNode, node.type); + case 161 /* ObjectBindingPattern */: + case 162 /* ArrayBindingPattern */: + return visitNodes(cbNodes, node.elements); + case 164 /* ArrayLiteralExpression */: + return visitNodes(cbNodes, node.elements); + case 165 /* ObjectLiteralExpression */: + return visitNodes(cbNodes, node.properties); + case 166 /* PropertyAccessExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.dotToken) || + visitNode(cbNode, node.name); + case 167 /* ElementAccessExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.argumentExpression); + case 168 /* CallExpression */: + case 169 /* NewExpression */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNodes, node.typeArguments) || + visitNodes(cbNodes, node.arguments); + case 170 /* TaggedTemplateExpression */: + return visitNode(cbNode, node.tag) || + visitNode(cbNode, node.template); + case 171 /* TypeAssertionExpression */: + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.expression); + case 172 /* ParenthesizedExpression */: + return visitNode(cbNode, node.expression); + case 175 /* DeleteExpression */: + return visitNode(cbNode, node.expression); + case 176 /* TypeOfExpression */: + return visitNode(cbNode, node.expression); + case 177 /* VoidExpression */: + return visitNode(cbNode, node.expression); + case 179 /* PrefixUnaryExpression */: + return visitNode(cbNode, node.operand); + case 184 /* YieldExpression */: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 178 /* AwaitExpression */: + return visitNode(cbNode, node.expression); + case 180 /* PostfixUnaryExpression */: + return visitNode(cbNode, node.operand); + case 181 /* BinaryExpression */: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.operatorToken) || + visitNode(cbNode, node.right); + case 189 /* AsExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.type); + case 182 /* ConditionalExpression */: + return visitNode(cbNode, node.condition) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.whenTrue) || + visitNode(cbNode, node.colonToken) || + visitNode(cbNode, node.whenFalse); + case 185 /* SpreadElementExpression */: + return visitNode(cbNode, node.expression); + case 192 /* Block */: + case 219 /* ModuleBlock */: + return visitNodes(cbNodes, node.statements); + case 248 /* SourceFile */: + return visitNodes(cbNodes, node.statements) || + visitNode(cbNode, node.endOfFileToken); + case 193 /* VariableStatement */: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.declarationList); + case 212 /* VariableDeclarationList */: + return visitNodes(cbNodes, node.declarations); + case 195 /* ExpressionStatement */: + return visitNode(cbNode, node.expression); + case 196 /* IfStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.thenStatement) || + visitNode(cbNode, node.elseStatement); + case 197 /* DoStatement */: + return visitNode(cbNode, node.statement) || + visitNode(cbNode, node.expression); + case 198 /* WhileStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 199 /* ForStatement */: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.condition) || + visitNode(cbNode, node.incrementor) || + visitNode(cbNode, node.statement); + case 200 /* ForInStatement */: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 201 /* ForOfStatement */: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 202 /* ContinueStatement */: + case 203 /* BreakStatement */: + return visitNode(cbNode, node.label); + case 204 /* ReturnStatement */: + return visitNode(cbNode, node.expression); + case 205 /* WithStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 206 /* SwitchStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 220 /* CaseBlock */: + return visitNodes(cbNodes, node.clauses); + case 241 /* CaseClause */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNodes, node.statements); + case 242 /* DefaultClause */: + return visitNodes(cbNodes, node.statements); + case 207 /* LabeledStatement */: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 208 /* ThrowStatement */: + return visitNode(cbNode, node.expression); + case 209 /* TryStatement */: + return visitNode(cbNode, node.tryBlock) || + visitNode(cbNode, node.catchClause) || + visitNode(cbNode, node.finallyBlock); + case 244 /* CatchClause */: + return visitNode(cbNode, node.variableDeclaration) || + visitNode(cbNode, node.block); + case 139 /* Decorator */: + return visitNode(cbNode, node.expression); + case 214 /* ClassDeclaration */: + case 186 /* ClassExpression */: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeParameters) || + visitNodes(cbNodes, node.heritageClauses) || + visitNodes(cbNodes, node.members); + case 215 /* InterfaceDeclaration */: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeParameters) || + visitNodes(cbNodes, node.heritageClauses) || + visitNodes(cbNodes, node.members); + case 216 /* TypeAliasDeclaration */: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeParameters) || + visitNode(cbNode, node.type); + case 217 /* EnumDeclaration */: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.members); + case 247 /* EnumMember */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 218 /* ModuleDeclaration */: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.body); + case 221 /* ImportEqualsDeclaration */: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.moduleReference); + case 222 /* ImportDeclaration */: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.importClause) || + visitNode(cbNode, node.moduleSpecifier); + case 223 /* ImportClause */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.namedBindings); + case 224 /* NamespaceImport */: + return visitNode(cbNode, node.name); + case 225 /* NamedImports */: + case 229 /* NamedExports */: + return visitNodes(cbNodes, node.elements); + case 228 /* ExportDeclaration */: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.exportClause) || + visitNode(cbNode, node.moduleSpecifier); + case 226 /* ImportSpecifier */: + case 230 /* ExportSpecifier */: + return visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name); + case 227 /* ExportAssignment */: + return visitNodes(cbNodes, node.decorators) || + visitNodes(cbNodes, node.modifiers) || + visitNode(cbNode, node.expression); + case 183 /* TemplateExpression */: + return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); + case 190 /* TemplateSpan */: + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + case 136 /* ComputedPropertyName */: + return visitNode(cbNode, node.expression); + case 243 /* HeritageClause */: + return visitNodes(cbNodes, node.types); + case 188 /* ExpressionWithTypeArguments */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNodes, node.typeArguments); + case 232 /* ExternalModuleReference */: + return visitNode(cbNode, node.expression); + case 231 /* MissingDeclaration */: + return visitNodes(cbNodes, node.decorators); + case 233 /* JsxElement */: + return visitNode(cbNode, node.openingElement) || + visitNodes(cbNodes, node.children) || + visitNode(cbNode, node.closingElement); + case 234 /* JsxSelfClosingElement */: + case 235 /* JsxOpeningElement */: + return visitNode(cbNode, node.tagName) || + visitNodes(cbNodes, node.attributes); + case 238 /* JsxAttribute */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 239 /* JsxSpreadAttribute */: + return visitNode(cbNode, node.expression); + case 240 /* JsxExpression */: + return visitNode(cbNode, node.expression); + case 237 /* JsxClosingElement */: + return visitNode(cbNode, node.tagName); + case 249 /* JSDocTypeExpression */: + return visitNode(cbNode, node.type); + case 253 /* JSDocUnionType */: + return visitNodes(cbNodes, node.types); + case 254 /* JSDocTupleType */: + return visitNodes(cbNodes, node.types); + case 252 /* JSDocArrayType */: + return visitNode(cbNode, node.elementType); + case 256 /* JSDocNonNullableType */: + return visitNode(cbNode, node.type); + case 255 /* JSDocNullableType */: + return visitNode(cbNode, node.type); + case 257 /* JSDocRecordType */: + return visitNodes(cbNodes, node.members); + case 259 /* JSDocTypeReference */: + return visitNode(cbNode, node.name) || + visitNodes(cbNodes, node.typeArguments); + case 260 /* JSDocOptionalType */: + return visitNode(cbNode, node.type); + case 261 /* JSDocFunctionType */: + return visitNodes(cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 262 /* JSDocVariadicType */: + return visitNode(cbNode, node.type); + case 263 /* JSDocConstructorType */: + return visitNode(cbNode, node.type); + case 264 /* JSDocThisType */: + return visitNode(cbNode, node.type); + case 258 /* JSDocRecordMember */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.type); + case 265 /* JSDocComment */: + return visitNodes(cbNodes, node.tags); + case 267 /* JSDocParameterTag */: + return visitNode(cbNode, node.preParameterName) || + visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.postParameterName); + case 268 /* JSDocReturnTag */: + return visitNode(cbNode, node.typeExpression); + case 269 /* JSDocTypeTag */: + return visitNode(cbNode, node.typeExpression); + case 270 /* JSDocTemplateTag */: + return visitNodes(cbNodes, node.typeParameters); + } + } + ts.forEachChild = forEachChild; + function createSourceFile(fileName, sourceText, languageVersion, setParentNodes) { + if (setParentNodes === void 0) { setParentNodes = false; } + var start = new Date().getTime(); + var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + ts.parseTime += new Date().getTime() - start; + return result; + } + ts.createSourceFile = createSourceFile; + // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter + // indicates what changed between the 'text' that this SourceFile has and the 'newText'. + // The SourceFile will be created with the compiler attempting to reuse as many nodes from + // this file as possible. + // + // Note: this function mutates nodes from this SourceFile. That means any existing nodes + // from this SourceFile that are being held onto may change as a result (including + // becoming detached from any SourceFile). It is recommended that this SourceFile not + // be used once 'update' is called on it. + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + return IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); + } + ts.updateSourceFile = updateSourceFile; + /* @internal */ + function parseIsolatedJSDocComment(content, start, length) { + return Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); + } + ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + /* @internal */ + // Exposed only for testing. + function parseJSDocTypeExpressionForTests(content, start, length) { + return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); + } + ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + // Implement the parser as a singleton module. We do this for perf reasons because creating + // parser instances can actually be expensive enough to impact us on projects with many source + // files. + var Parser; + (function (Parser) { + // Share a single scanner across all calls to parse a source file. This helps speed things + // up by avoiding the cost of creating/compiling scanners over and over again. + var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ true); + var disallowInAndDecoratorContext = 1 /* DisallowIn */ | 4 /* Decorator */; + var sourceFile; + var parseDiagnostics; + var syntaxCursor; + var token; + var sourceText; + var nodeCount; + var identifiers; + var identifierCount; + var parsingContext; + // Flags that dictate what parsing context we're in. For example: + // Whether or not we are in strict parsing mode. All that changes in strict parsing mode is + // that some tokens that would be considered identifiers may be considered keywords. + // + // When adding more parser context flags, consider which is the more common case that the + // flag will be in. This should be the 'false' state for that flag. The reason for this is + // that we don't store data in our nodes unless the value is in the *non-default* state. So, + // for example, more often than code 'allows-in' (or doesn't 'disallow-in'). We opt for + // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost + // all nodes would need extra state on them to store this info. + // + // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 + // grammar specification. + // + // An important thing about these context concepts. By default they are effectively inherited + // while parsing through every grammar production. i.e. if you don't change them, then when + // you parse a sub-production, it will have the same context values as the parent production. + // This is great most of the time. After all, consider all the 'expression' grammar productions + // and how nearly all of them pass along the 'in' and 'yield' context values: + // + // EqualityExpression[In, Yield] : + // RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield] + // + // Where you have to be careful is then understanding what the points are in the grammar + // where the values are *not* passed along. For example: + // + // SingleNameBinding[Yield,GeneratorParameter] + // [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt + // [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt + // + // Here this is saying that if the GeneratorParameter context flag is set, that we should + // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier + // and we should explicitly unset the 'yield' context flag before calling into the Initializer. + // production. Conversely, if the GeneratorParameter context flag is not set, then we + // should leave the 'yield' context flag alone. + // + // Getting this all correct is tricky and requires careful reading of the grammar to + // understand when these values should be changed versus when they should be inherited. + // + // Note: it should not be necessary to save/restore these flags during speculative/lookahead + // parsing. These context flags are naturally stored and restored through normal recursive + // descent parsing and unwinding. + var contextFlags; + // Whether or not we've had a parse error since creating the last AST node. If we have + // encountered an error, it will be stored on the next AST node we create. Parse errors + // can be broken down into three categories: + // + // 1) An error that occurred during scanning. For example, an unterminated literal, or a + // character that was completely not understood. + // + // 2) A token was expected, but was not present. This type of error is commonly produced + // by the 'parseExpected' function. + // + // 3) A token was present that no parsing function was able to consume. This type of error + // only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser + // decides to skip the token. + // + // In all of these cases, we want to mark the next node as having had an error before it. + // With this mark, we can know in incremental settings if this node can be reused, or if + // we have to reparse it. If we don't keep this information around, we may just reuse the + // node. in that event we would then not produce the same errors as we did before, causing + // significant confusion problems. + // + // Note: it is necessary that this value be saved/restored during speculative/lookahead + // parsing. During lookahead parsing, we will often create a node. That node will have + // this value attached, and then this value will be set back to 'false'. If we decide to + // rewind, we must get back to the same value we had prior to the lookahead. + // + // Note: any errors at the end of the file that do not precede a regular node, should get + // attached to the EOF token. + var parseErrorBeforeNextFinishedNode = false; + function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes) { + initializeState(fileName, _sourceText, languageVersion, _syntaxCursor); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes); + clearState(); + return result; + } + Parser.parseSourceFile = parseSourceFile; + function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor) { + sourceText = _sourceText; + syntaxCursor = _syntaxCursor; + parseDiagnostics = []; + parsingContext = 0; + identifiers = {}; + identifierCount = 0; + nodeCount = 0; + contextFlags = ts.isJavaScript(fileName) ? 32 /* JavaScriptFile */ : 0 /* None */; + parseErrorBeforeNextFinishedNode = false; + // Initialize and prime the scanner before parsing the source elements. + scanner.setText(sourceText); + scanner.setOnError(scanError); + scanner.setScriptTarget(languageVersion); + scanner.setLanguageVariant(ts.isTsx(fileName) ? 1 /* JSX */ : 0 /* Standard */); + } + function clearState() { + // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. + scanner.setText(""); + scanner.setOnError(undefined); + // Clear any data. We don't want to accidently hold onto it for too long. + parseDiagnostics = undefined; + sourceFile = undefined; + identifiers = undefined; + syntaxCursor = undefined; + sourceText = undefined; + } + function parseSourceFileWorker(fileName, languageVersion, setParentNodes) { + sourceFile = createSourceFile(fileName, languageVersion); + // Prime the scanner. + token = nextToken(); + processReferenceComments(sourceFile); + sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); + ts.Debug.assert(token === 1 /* EndOfFileToken */); + sourceFile.endOfFileToken = parseTokenNode(); + setExternalModuleIndicator(sourceFile); + sourceFile.nodeCount = nodeCount; + sourceFile.identifierCount = identifierCount; + sourceFile.identifiers = identifiers; + sourceFile.parseDiagnostics = parseDiagnostics; + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + // If this is a javascript file, proactively see if we can get JSDoc comments for + // relevant nodes in the file. We'll use these to provide typing informaion if they're + // available. + if (ts.isJavaScript(fileName)) { + addJSDocComments(); + } + return sourceFile; + } + function addJSDocComments() { + forEachChild(sourceFile, visit); + return; + function visit(node) { + // Add additional cases as necessary depending on how we see JSDoc comments used + // in the wild. + switch (node.kind) { + case 193 /* VariableStatement */: + case 213 /* FunctionDeclaration */: + case 138 /* Parameter */: + addJSDocComment(node); + } + forEachChild(node, visit); + } + } + function addJSDocComment(node) { + var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); + if (comments) { + for (var _i = 0; _i < comments.length; _i++) { + var comment = comments[_i]; + var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (jsDocComment) { + node.jsDocComment = jsDocComment; + } + } + } + } + function fixupParentReferences(sourceFile) { + // normally parent references are set during binding. However, for clients that only need + // a syntax tree, and no semantic features, then the binding process is an unnecessary + // overhead. This functions allows us to set all the parents, without all the expense of + // binding. + var parent = sourceFile; + forEachChild(sourceFile, visitNode); + return; + function visitNode(n) { + // walk down setting parents that differ from the parent we think it should be. This + // allows us to quickly bail out of setting parents for subtrees during incremental + // parsing + if (n.parent !== parent) { + n.parent = parent; + var saveParent = parent; + parent = n; + forEachChild(n, visitNode); + parent = saveParent; + } + } + } + Parser.fixupParentReferences = fixupParentReferences; + function createSourceFile(fileName, languageVersion) { + var sourceFile = createNode(248 /* SourceFile */, /*pos*/ 0); + sourceFile.pos = 0; + sourceFile.end = sourceText.length; + sourceFile.text = sourceText; + sourceFile.bindDiagnostics = []; + sourceFile.languageVersion = languageVersion; + sourceFile.fileName = ts.normalizePath(fileName); + sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 8192 /* DeclarationFile */ : 0; + sourceFile.languageVariant = ts.isTsx(sourceFile.fileName) ? 1 /* JSX */ : 0 /* Standard */; + return sourceFile; + } + function setContextFlag(val, flag) { + if (val) { + contextFlags |= flag; + } + else { + contextFlags &= ~flag; + } + } + function setDisallowInContext(val) { + setContextFlag(val, 1 /* DisallowIn */); + } + function setYieldContext(val) { + setContextFlag(val, 2 /* Yield */); + } + function setDecoratorContext(val) { + setContextFlag(val, 4 /* Decorator */); + } + function setAwaitContext(val) { + setContextFlag(val, 8 /* Await */); + } + function doOutsideOfContext(context, func) { + // contextFlagsToClear will contain only the context flags that are + // currently set that we need to temporarily clear + // We don't just blindly reset to the previous flags to ensure + // that we do not mutate cached flags for the incremental + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // HasAggregatedChildData). + var contextFlagsToClear = context & contextFlags; + if (contextFlagsToClear) { + // clear the requested context flags + setContextFlag(false, contextFlagsToClear); + var result = func(); + // restore the context flags we just cleared + setContextFlag(true, contextFlagsToClear); + return result; + } + // no need to do anything special as we are not in any of the requested contexts + return func(); + } + function doInsideOfContext(context, func) { + // contextFlagsToSet will contain only the context flags that + // are not currently set that we need to temporarily enable. + // We don't just blindly reset to the previous flags to ensure + // that we do not mutate cached flags for the incremental + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // HasAggregatedChildData). + var contextFlagsToSet = context & ~contextFlags; + if (contextFlagsToSet) { + // set the requested context flags + setContextFlag(true, contextFlagsToSet); + var result = func(); + // reset the context flags we just set + setContextFlag(false, contextFlagsToSet); + return result; + } + // no need to do anything special as we are already in all of the requested contexts + return func(); + } + function allowInAnd(func) { + return doOutsideOfContext(1 /* DisallowIn */, func); + } + function disallowInAnd(func) { + return doInsideOfContext(1 /* DisallowIn */, func); + } + function doInYieldContext(func) { + return doInsideOfContext(2 /* Yield */, func); + } + function doOutsideOfYieldContext(func) { + return doOutsideOfContext(2 /* Yield */, func); + } + function doInDecoratorContext(func) { + return doInsideOfContext(4 /* Decorator */, func); + } + function doInAwaitContext(func) { + return doInsideOfContext(8 /* Await */, func); + } + function doOutsideOfAwaitContext(func) { + return doOutsideOfContext(8 /* Await */, func); + } + function doInYieldAndAwaitContext(func) { + return doInsideOfContext(2 /* Yield */ | 8 /* Await */, func); + } + function doOutsideOfYieldAndAwaitContext(func) { + return doOutsideOfContext(2 /* Yield */ | 8 /* Await */, func); + } + function inContext(flags) { + return (contextFlags & flags) !== 0; + } + function inYieldContext() { + return inContext(2 /* Yield */); + } + function inDisallowInContext() { + return inContext(1 /* DisallowIn */); + } + function inDecoratorContext() { + return inContext(4 /* Decorator */); + } + function inAwaitContext() { + return inContext(8 /* Await */); + } + function parseErrorAtCurrentToken(message, arg0) { + var start = scanner.getTokenPos(); + var length = scanner.getTextPos() - start; + parseErrorAtPosition(start, length, message, arg0); + } + function parseErrorAtPosition(start, length, message, arg0) { + // Don't report another error if it would just be at the same position as the last error. + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (!lastError || start !== lastError.start) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); + } + // Mark that we've encountered an error. We'll set an appropriate bit on the next + // node we finish so that it can't be reused incrementally. + parseErrorBeforeNextFinishedNode = true; + } + function scanError(message, length) { + var pos = scanner.getTextPos(); + parseErrorAtPosition(pos, length || 0, message); + } + function getNodePos() { + return scanner.getStartPos(); + } + function getNodeEnd() { + return scanner.getStartPos(); + } + function nextToken() { + return token = scanner.scan(); + } + function getTokenPos(pos) { + return ts.skipTrivia(sourceText, pos); + } + function reScanGreaterToken() { + return token = scanner.reScanGreaterToken(); + } + function reScanSlashToken() { + return token = scanner.reScanSlashToken(); + } + function reScanTemplateToken() { + return token = scanner.reScanTemplateToken(); + } + function scanJsxIdentifier() { + return token = scanner.scanJsxIdentifier(); + } + function scanJsxText() { + return token = scanner.scanJsxToken(); + } + function speculationHelper(callback, isLookAhead) { + // Keep track of the state we'll need to rollback to if lookahead fails (or if the + // caller asked us to always reset our state). + var saveToken = token; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + // Note: it is not actually necessary to save/restore the context flags here. That's + // because the saving/restoring of these flags happens naturally through the recursive + // descent nature of our parser. However, we still store this here just so we can + // assert that that invariant holds. + var saveContextFlags = contextFlags; + // If we're only looking ahead, then tell the scanner to only lookahead as well. + // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the + // same. + var result = isLookAhead + ? scanner.lookAhead(callback) + : scanner.tryScan(callback); + ts.Debug.assert(saveContextFlags === contextFlags); + // If our callback returned something 'falsy' or we're just looking ahead, + // then unconditionally restore us to where we were. + if (!result || isLookAhead) { + token = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + } + return result; + } + // Invokes the provided callback then unconditionally restores the parser to the state it + // was in immediately prior to invoking the callback. The result of invoking the callback + // is returned from this function. + function lookAhead(callback) { + return speculationHelper(callback, /*isLookAhead*/ true); + } + // Invokes the provided callback. If the callback returns something falsy, then it restores + // the parser to the state it was in immediately prior to invoking the callback. If the + // callback returns something truthy, then the parser state is not rolled back. The result + // of invoking the callback is returned from this function. + function tryParse(callback) { + return speculationHelper(callback, /*isLookAhead*/ false); + } + // Ignore strict mode flag because we will report an error in type checker instead. + function isIdentifier() { + if (token === 69 /* Identifier */) { + return true; + } + // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is + // considered a keyword and is not an identifier. + if (token === 114 /* YieldKeyword */ && inYieldContext()) { + return false; + } + // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is + // considered a keyword and is not an identifier. + if (token === 119 /* AwaitKeyword */ && inAwaitContext()) { + return false; + } + return token > 105 /* LastReservedWord */; + } + function parseExpected(kind, diagnosticMessage, shouldAdvance) { + if (shouldAdvance === void 0) { shouldAdvance = true; } + if (token === kind) { + if (shouldAdvance) { + nextToken(); + } + return true; + } + // Report specific message if provided with one. Otherwise, report generic fallback message. + if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage); + } + else { + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); + } + return false; + } + function parseOptional(t) { + if (token === t) { + nextToken(); + return true; + } + return false; + } + function parseOptionalToken(t) { + if (token === t) { + return parseTokenNode(); + } + return undefined; + } + function parseExpectedToken(t, reportAtCurrentPosition, diagnosticMessage, arg0) { + return parseOptionalToken(t) || + createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); + } + function parseTokenNode() { + var node = createNode(token); + nextToken(); + return finishNode(node); + } + function canParseSemicolon() { + // If there's a real semicolon, then we can always parse it out. + if (token === 23 /* SemicolonToken */) { + return true; + } + // We can parse out an optional semicolon in ASI cases in the following cases. + return token === 16 /* CloseBraceToken */ || token === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + } + function parseSemicolon() { + if (canParseSemicolon()) { + if (token === 23 /* SemicolonToken */) { + // consume the semicolon if it was explicitly provided. + nextToken(); + } + return true; + } + else { + return parseExpected(23 /* SemicolonToken */); + } + } + function createNode(kind, pos) { + nodeCount++; + var node = new (nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)))(); + if (!(pos >= 0)) { + pos = scanner.getStartPos(); + } + node.pos = pos; + node.end = pos; + return node; + } + function finishNode(node, end) { + node.end = end === undefined ? scanner.getStartPos() : end; + if (contextFlags) { + node.parserContextFlags = contextFlags; + } + // Keep track on the node if we encountered an error while parsing it. If we did, then + // we cannot reuse the node incrementally. Once we've marked this node, clear out the + // flag so that we don't mark any subsequent nodes. + if (parseErrorBeforeNextFinishedNode) { + parseErrorBeforeNextFinishedNode = false; + node.parserContextFlags |= 16 /* ThisNodeHasError */; + } + return node; + } + function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) { + if (reportAtCurrentPosition) { + parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); + } + else { + parseErrorAtCurrentToken(diagnosticMessage, arg0); + } + var result = createNode(kind, scanner.getStartPos()); + result.text = ""; + return finishNode(result); + } + function internIdentifier(text) { + text = ts.escapeIdentifier(text); + return ts.hasProperty(identifiers, text) ? identifiers[text] : (identifiers[text] = text); + } + // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues + // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for + // each identifier in order to reduce memory consumption. + function createIdentifier(isIdentifier, diagnosticMessage) { + identifierCount++; + if (isIdentifier) { + var node = createNode(69 /* Identifier */); + // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker + if (token !== 69 /* Identifier */) { + node.originalKeywordKind = token; + } + node.text = internIdentifier(scanner.getTokenValue()); + nextToken(); + return finishNode(node); + } + return createMissingNode(69 /* Identifier */, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics.Identifier_expected); + } + function parseIdentifier(diagnosticMessage) { + return createIdentifier(isIdentifier(), diagnosticMessage); + } + function parseIdentifierName() { + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token)); + } + function isLiteralPropertyName() { + return ts.tokenIsIdentifierOrKeyword(token) || + token === 9 /* StringLiteral */ || + token === 8 /* NumericLiteral */; + } + function parsePropertyNameWorker(allowComputedPropertyNames) { + if (token === 9 /* StringLiteral */ || token === 8 /* NumericLiteral */) { + return parseLiteralNode(/*internName*/ true); + } + if (allowComputedPropertyNames && token === 19 /* OpenBracketToken */) { + return parseComputedPropertyName(); + } + return parseIdentifierName(); + } + function parsePropertyName() { + return parsePropertyNameWorker(/*allowComputedPropertyNames:*/ true); + } + function parseSimplePropertyName() { + return parsePropertyNameWorker(/*allowComputedPropertyNames:*/ false); + } + function isSimplePropertyName() { + return token === 9 /* StringLiteral */ || token === 8 /* NumericLiteral */ || ts.tokenIsIdentifierOrKeyword(token); + } + function parseComputedPropertyName() { + // PropertyName [Yield]: + // LiteralPropertyName + // ComputedPropertyName[?Yield] + var node = createNode(136 /* ComputedPropertyName */); + parseExpected(19 /* OpenBracketToken */); + // We parse any expression (including a comma expression). But the grammar + // says that only an assignment expression is allowed, so the grammar checker + // will error if it sees a comma expression. + node.expression = allowInAnd(parseExpression); + parseExpected(20 /* CloseBracketToken */); + return finishNode(node); + } + function parseContextualModifier(t) { + return token === t && tryParse(nextTokenCanFollowModifier); + } + function nextTokenCanFollowModifier() { + if (token === 74 /* ConstKeyword */) { + // 'const' is only a modifier if followed by 'enum'. + return nextToken() === 81 /* EnumKeyword */; + } + if (token === 82 /* ExportKeyword */) { + nextToken(); + if (token === 77 /* DefaultKeyword */) { + return lookAhead(nextTokenIsClassOrFunction); + } + return token !== 37 /* AsteriskToken */ && token !== 15 /* OpenBraceToken */ && canFollowModifier(); + } + if (token === 77 /* DefaultKeyword */) { + return nextTokenIsClassOrFunction(); + } + if (token === 113 /* StaticKeyword */) { + nextToken(); + return canFollowModifier(); + } + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } + function parseAnyContextualModifier() { + return ts.isModifier(token) && tryParse(nextTokenCanFollowModifier); + } + function canFollowModifier() { + return token === 19 /* OpenBracketToken */ + || token === 15 /* OpenBraceToken */ + || token === 37 /* AsteriskToken */ + || isLiteralPropertyName(); + } + function nextTokenIsClassOrFunction() { + nextToken(); + return token === 73 /* ClassKeyword */ || token === 87 /* FunctionKeyword */; + } + // True if positioned at the start of a list element + function isListElement(parsingContext, inErrorRecovery) { + var node = currentNode(parsingContext); + if (node) { + return true; + } + switch (parsingContext) { + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + // If we're in error recovery, then we don't want to treat ';' as an empty statement. + // The problem is that ';' can show up in far too many contexts, and if we see one + // and assume it's a statement, then we may bail out inappropriately from whatever + // we're parsing. For example, if we have a semicolon in the middle of a class, then + // we really don't want to assume the class is over and we're on a statement in the + // outer module. We just want to consume and move on. + return !(token === 23 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + case 2 /* SwitchClauses */: + return token === 71 /* CaseKeyword */ || token === 77 /* DefaultKeyword */; + case 4 /* TypeMembers */: + return isStartOfTypeMember(); + case 5 /* ClassMembers */: + // We allow semicolons as class elements (as specified by ES6) as long as we're + // not in error recovery. If we're in error recovery, we don't want an errant + // semicolon to be treated as a class member (since they're almost always used + // for statements. + return lookAhead(isClassMemberStart) || (token === 23 /* SemicolonToken */ && !inErrorRecovery); + case 6 /* EnumMembers */: + // Include open bracket computed properties. This technically also lets in indexers, + // which would be a candidate for improved error reporting. + return token === 19 /* OpenBracketToken */ || isLiteralPropertyName(); + case 12 /* ObjectLiteralMembers */: + return token === 19 /* OpenBracketToken */ || token === 37 /* AsteriskToken */ || isLiteralPropertyName(); + case 9 /* ObjectBindingElements */: + return isLiteralPropertyName(); + case 7 /* HeritageClauseElement */: + // If we see { } then only consume it as an expression if it is followed by , or { + // That way we won't consume the body of a class in its heritage clause. + if (token === 15 /* OpenBraceToken */) { + return lookAhead(isValidHeritageClauseObjectLiteral); + } + if (!inErrorRecovery) { + return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + else { + // If we're in error recovery we tighten up what we're willing to match. + // That way we don't treat something like "this" as a valid heritage clause + // element during recovery. + return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + case 8 /* VariableDeclarations */: + return isIdentifierOrPattern(); + case 10 /* ArrayBindingElements */: + return token === 24 /* CommaToken */ || token === 22 /* DotDotDotToken */ || isIdentifierOrPattern(); + case 17 /* TypeParameters */: + return isIdentifier(); + case 11 /* ArgumentExpressions */: + case 15 /* ArrayLiteralMembers */: + return token === 24 /* CommaToken */ || token === 22 /* DotDotDotToken */ || isStartOfExpression(); + case 16 /* Parameters */: + return isStartOfParameter(); + case 18 /* TypeArguments */: + case 19 /* TupleElementTypes */: + return token === 24 /* CommaToken */ || isStartOfType(); + case 20 /* HeritageClauses */: + return isHeritageClause(); + case 21 /* ImportOrExportSpecifiers */: + return ts.tokenIsIdentifierOrKeyword(token); + case 13 /* JsxAttributes */: + return ts.tokenIsIdentifierOrKeyword(token) || token === 15 /* OpenBraceToken */; + case 14 /* JsxChildren */: + return true; + case 22 /* JSDocFunctionParameters */: + case 23 /* JSDocTypeArguments */: + case 25 /* JSDocTupleTypes */: + return JSDocParser.isJSDocType(); + case 24 /* JSDocRecordMembers */: + return isSimplePropertyName(); + } + ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + } + function isValidHeritageClauseObjectLiteral() { + ts.Debug.assert(token === 15 /* OpenBraceToken */); + if (nextToken() === 16 /* CloseBraceToken */) { + // if we see "extends {}" then only treat the {} as what we're extending (and not + // the class body) if we have: + // + // extends {} { + // extends {}, + // extends {} extends + // extends {} implements + var next = nextToken(); + return next === 24 /* CommaToken */ || next === 15 /* OpenBraceToken */ || next === 83 /* ExtendsKeyword */ || next === 106 /* ImplementsKeyword */; + } + return true; + } + function nextTokenIsIdentifier() { + nextToken(); + return isIdentifier(); + } + function nextTokenIsIdentifierOrKeyword() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token); + } + function isHeritageClauseExtendsOrImplementsKeyword() { + if (token === 106 /* ImplementsKeyword */ || + token === 83 /* ExtendsKeyword */) { + return lookAhead(nextTokenIsStartOfExpression); + } + return false; + } + function nextTokenIsStartOfExpression() { + nextToken(); + return isStartOfExpression(); + } + // True if positioned at a list terminator + function isListTerminator(kind) { + if (token === 1 /* EndOfFileToken */) { + // Being at the end of the file ends all lists. + return true; + } + switch (kind) { + case 1 /* BlockStatements */: + case 2 /* SwitchClauses */: + case 4 /* TypeMembers */: + case 5 /* ClassMembers */: + case 6 /* EnumMembers */: + case 12 /* ObjectLiteralMembers */: + case 9 /* ObjectBindingElements */: + case 21 /* ImportOrExportSpecifiers */: + return token === 16 /* CloseBraceToken */; + case 3 /* SwitchClauseStatements */: + return token === 16 /* CloseBraceToken */ || token === 71 /* CaseKeyword */ || token === 77 /* DefaultKeyword */; + case 7 /* HeritageClauseElement */: + return token === 15 /* OpenBraceToken */ || token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */; + case 8 /* VariableDeclarations */: + return isVariableDeclaratorListTerminator(); + case 17 /* TypeParameters */: + // Tokens other than '>' are here for better error recovery + return token === 27 /* GreaterThanToken */ || token === 17 /* OpenParenToken */ || token === 15 /* OpenBraceToken */ || token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */; + case 11 /* ArgumentExpressions */: + // Tokens other than ')' are here for better error recovery + return token === 18 /* CloseParenToken */ || token === 23 /* SemicolonToken */; + case 15 /* ArrayLiteralMembers */: + case 19 /* TupleElementTypes */: + case 10 /* ArrayBindingElements */: + return token === 20 /* CloseBracketToken */; + case 16 /* Parameters */: + // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery + return token === 18 /* CloseParenToken */ || token === 20 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + case 18 /* TypeArguments */: + // Tokens other than '>' are here for better error recovery + return token === 27 /* GreaterThanToken */ || token === 17 /* OpenParenToken */; + case 20 /* HeritageClauses */: + return token === 15 /* OpenBraceToken */ || token === 16 /* CloseBraceToken */; + case 13 /* JsxAttributes */: + return token === 27 /* GreaterThanToken */ || token === 39 /* SlashToken */; + case 14 /* JsxChildren */: + return token === 25 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + case 22 /* JSDocFunctionParameters */: + return token === 18 /* CloseParenToken */ || token === 54 /* ColonToken */ || token === 16 /* CloseBraceToken */; + case 23 /* JSDocTypeArguments */: + return token === 27 /* GreaterThanToken */ || token === 16 /* CloseBraceToken */; + case 25 /* JSDocTupleTypes */: + return token === 20 /* CloseBracketToken */ || token === 16 /* CloseBraceToken */; + case 24 /* JSDocRecordMembers */: + return token === 16 /* CloseBraceToken */; + } + } + function isVariableDeclaratorListTerminator() { + // If we can consume a semicolon (either explicitly, or with ASI), then consider us done + // with parsing the list of variable declarators. + if (canParseSemicolon()) { + return true; + } + // in the case where we're parsing the variable declarator of a 'for-in' statement, we + // are done if we see an 'in' keyword in front of us. Same with for-of + if (isInOrOfKeyword(token)) { + return true; + } + // ERROR RECOVERY TWEAK: + // For better error recovery, if we see an '=>' then we just stop immediately. We've got an + // arrow function here and it's going to be very unlikely that we'll resynchronize and get + // another variable declaration. + if (token === 34 /* EqualsGreaterThanToken */) { + return true; + } + // Keep trying to parse out variable declarators. + return false; + } + // True if positioned at element or terminator of the current list or any enclosing list + function isInSomeParsingContext() { + for (var kind = 0; kind < 26 /* Count */; kind++) { + if (parsingContext & (1 << kind)) { + if (isListElement(kind, /* inErrorRecovery */ true) || isListTerminator(kind)) { + return true; + } + } + } + return false; + } + // Parses a list of elements + function parseList(kind, parseElement) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var result = []; + result.pos = getNodePos(); + while (!isListTerminator(kind)) { + if (isListElement(kind, /* inErrorRecovery */ false)) { + var element = parseListElement(kind, parseElement); + result.push(element); + continue; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + result.end = getNodeEnd(); + parsingContext = saveParsingContext; + return result; + } + function parseListElement(parsingContext, parseElement) { + var node = currentNode(parsingContext); + if (node) { + return consumeNode(node); + } + return parseElement(); + } + function currentNode(parsingContext) { + // If there is an outstanding parse error that we've encountered, but not attached to + // some node, then we cannot get a node from the old source tree. This is because we + // want to mark the next node we encounter as being unusable. + // + // Note: This may be too conservative. Perhaps we could reuse the node and set the bit + // on it (or its leftmost child) as having the error. For now though, being conservative + // is nice and likely won't ever affect perf. + if (parseErrorBeforeNextFinishedNode) { + return undefined; + } + if (!syntaxCursor) { + // if we don't have a cursor, we could never return a node from the old tree. + return undefined; + } + var node = syntaxCursor.currentNode(scanner.getStartPos()); + // Can't reuse a missing node. + if (ts.nodeIsMissing(node)) { + return undefined; + } + // Can't reuse a node that intersected the change range. + if (node.intersectsChange) { + return undefined; + } + // Can't reuse a node that contains a parse error. This is necessary so that we + // produce the same set of errors again. + if (ts.containsParseError(node)) { + return undefined; + } + // We can only reuse a node if it was parsed under the same strict mode that we're + // currently in. i.e. if we originally parsed a node in non-strict mode, but then + // the user added 'using strict' at the top of the file, then we can't use that node + // again as the presense of strict mode may cause us to parse the tokens in the file + // differetly. + // + // Note: we *can* reuse tokens when the strict mode changes. That's because tokens + // are unaffected by strict mode. It's just the parser will decide what to do with it + // differently depending on what mode it is in. + // + // This also applies to all our other context flags as well. + var nodeContextFlags = node.parserContextFlags & 31 /* ParserGeneratedFlags */; + if (nodeContextFlags !== contextFlags) { + return undefined; + } + // Ok, we have a node that looks like it could be reused. Now verify that it is valid + // in the currest list parsing context that we're currently at. + if (!canReuseNode(node, parsingContext)) { + return undefined; + } + return node; + } + function consumeNode(node) { + // Move the scanner so it is after the node we just consumed. + scanner.setTextPos(node.end); + nextToken(); + return node; + } + function canReuseNode(node, parsingContext) { + switch (parsingContext) { + case 5 /* ClassMembers */: + return isReusableClassMember(node); + case 2 /* SwitchClauses */: + return isReusableSwitchClause(node); + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + return isReusableStatement(node); + case 6 /* EnumMembers */: + return isReusableEnumMember(node); + case 4 /* TypeMembers */: + return isReusableTypeMember(node); + case 8 /* VariableDeclarations */: + return isReusableVariableDeclaration(node); + case 16 /* Parameters */: + return isReusableParameter(node); + // Any other lists we do not care about reusing nodes in. But feel free to add if + // you can do so safely. Danger areas involve nodes that may involve speculative + // parsing. If speculative parsing is involved with the node, then the range the + // parser reached while looking ahead might be in the edited range (see the example + // in canReuseVariableDeclaratorNode for a good case of this). + case 20 /* HeritageClauses */: + // This would probably be safe to reuse. There is no speculative parsing with + // heritage clauses. + case 17 /* TypeParameters */: + // This would probably be safe to reuse. There is no speculative parsing with + // type parameters. Note that that's because type *parameters* only occur in + // unambiguous *type* contexts. While type *arguments* occur in very ambiguous + // *expression* contexts. + case 19 /* TupleElementTypes */: + // This would probably be safe to reuse. There is no speculative parsing with + // tuple types. + // Technically, type argument list types are probably safe to reuse. While + // speculative parsing is involved with them (since type argument lists are only + // produced from speculative parsing a < as a type argument list), we only have + // the types because speculative parsing succeeded. Thus, the lookahead never + // went past the end of the list and rewound. + case 18 /* TypeArguments */: + // Note: these are almost certainly not safe to ever reuse. Expressions commonly + // need a large amount of lookahead, and we should not reuse them as they may + // have actually intersected the edit. + case 11 /* ArgumentExpressions */: + // This is not safe to reuse for the same reason as the 'AssignmentExpression' + // cases. i.e. a property assignment may end with an expression, and thus might + // have lookahead far beyond it's old node. + case 12 /* ObjectLiteralMembers */: + // This is probably not safe to reuse. There can be speculative parsing with + // type names in a heritage clause. There can be generic names in the type + // name list, and there can be left hand side expressions (which can have type + // arguments.) + case 7 /* HeritageClauseElement */: + // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes + // on any given element. Same for children. + case 13 /* JsxAttributes */: + case 14 /* JsxChildren */: + } + return false; + } + function isReusableClassMember(node) { + if (node) { + switch (node.kind) { + case 144 /* Constructor */: + case 149 /* IndexSignature */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 141 /* PropertyDeclaration */: + case 191 /* SemicolonClassElement */: + return true; + case 143 /* MethodDeclaration */: + // Method declarations are not necessarily reusable. An object-literal + // may have a method calls "constructor(...)" and we must reparse that + // into an actual .ConstructorDeclaration. + var methodDeclaration = node; + var nameIsConstructor = methodDeclaration.name.kind === 69 /* Identifier */ && + methodDeclaration.name.originalKeywordKind === 121 /* ConstructorKeyword */; + return !nameIsConstructor; + } + } + return false; + } + function isReusableSwitchClause(node) { + if (node) { + switch (node.kind) { + case 241 /* CaseClause */: + case 242 /* DefaultClause */: + return true; + } + } + return false; + } + function isReusableStatement(node) { + if (node) { + switch (node.kind) { + case 213 /* FunctionDeclaration */: + case 193 /* VariableStatement */: + case 192 /* Block */: + case 196 /* IfStatement */: + case 195 /* ExpressionStatement */: + case 208 /* ThrowStatement */: + case 204 /* ReturnStatement */: + case 206 /* SwitchStatement */: + case 203 /* BreakStatement */: + case 202 /* ContinueStatement */: + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + case 199 /* ForStatement */: + case 198 /* WhileStatement */: + case 205 /* WithStatement */: + case 194 /* EmptyStatement */: + case 209 /* TryStatement */: + case 207 /* LabeledStatement */: + case 197 /* DoStatement */: + case 210 /* DebuggerStatement */: + case 222 /* ImportDeclaration */: + case 221 /* ImportEqualsDeclaration */: + case 228 /* ExportDeclaration */: + case 227 /* ExportAssignment */: + case 218 /* ModuleDeclaration */: + case 214 /* ClassDeclaration */: + case 215 /* InterfaceDeclaration */: + case 217 /* EnumDeclaration */: + case 216 /* TypeAliasDeclaration */: + return true; + } + } + return false; + } + function isReusableEnumMember(node) { + return node.kind === 247 /* EnumMember */; + } + function isReusableTypeMember(node) { + if (node) { + switch (node.kind) { + case 148 /* ConstructSignature */: + case 142 /* MethodSignature */: + case 149 /* IndexSignature */: + case 140 /* PropertySignature */: + case 147 /* CallSignature */: + return true; + } + } + return false; + } + function isReusableVariableDeclaration(node) { + if (node.kind !== 211 /* VariableDeclaration */) { + return false; + } + // Very subtle incremental parsing bug. Consider the following code: + // + // let v = new List < A, B + // + // This is actually legal code. It's a list of variable declarators "v = new List() + // + // then we have a problem. "v = new List= 0) { + // Always preserve a trailing comma by marking it on the NodeArray + result.hasTrailingComma = true; + } + result.end = getNodeEnd(); + parsingContext = saveParsingContext; + return result; + } + function createMissingList() { + var pos = getNodePos(); + var result = []; + result.pos = pos; + result.end = pos; + return result; + } + function parseBracketedList(kind, parseElement, open, close) { + if (parseExpected(open)) { + var result = parseDelimitedList(kind, parseElement); + parseExpected(close); + return result; + } + return createMissingList(); + } + // The allowReservedWords parameter controls whether reserved words are permitted after the first dot + function parseEntityName(allowReservedWords, diagnosticMessage) { + var entity = parseIdentifier(diagnosticMessage); + while (parseOptional(21 /* DotToken */)) { + var node = createNode(135 /* QualifiedName */, entity.pos); + node.left = entity; + node.right = parseRightSideOfDot(allowReservedWords); + entity = finishNode(node); + } + return entity; + } + function parseRightSideOfDot(allowIdentifierNames) { + // Technically a keyword is valid here as all identifiers and keywords are identifier names. + // However, often we'll encounter this in error situations when the identifier or keyword + // is actually starting another valid construct. + // + // So, we check for the following specific case: + // + // name. + // identifierOrKeyword identifierNameOrKeyword + // + // Note: the newlines are important here. For example, if that above code + // were rewritten into: + // + // name.identifierOrKeyword + // identifierNameOrKeyword + // + // Then we would consider it valid. That's because ASI would take effect and + // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword". + // In the first case though, ASI will not take effect because there is not a + // line terminator after the identifier or keyword. + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token)) { + var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + if (matchesPattern) { + // Report that we need an identifier. However, report it right after the dot, + // and not on the next token. This is because the next token might actually + // be an identifier and the error would be quite confusing. + return createMissingNode(69 /* Identifier */, /*reportAtCurrentToken*/ true, ts.Diagnostics.Identifier_expected); + } + } + return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); + } + function parseTemplateExpression() { + var template = createNode(183 /* TemplateExpression */); + template.head = parseLiteralNode(); + ts.Debug.assert(template.head.kind === 12 /* TemplateHead */, "Template head has wrong token kind"); + var templateSpans = []; + templateSpans.pos = getNodePos(); + do { + templateSpans.push(parseTemplateSpan()); + } while (ts.lastOrUndefined(templateSpans).literal.kind === 13 /* TemplateMiddle */); + templateSpans.end = getNodeEnd(); + template.templateSpans = templateSpans; + return finishNode(template); + } + function parseTemplateSpan() { + var span = createNode(190 /* TemplateSpan */); + span.expression = allowInAnd(parseExpression); + var literal; + if (token === 16 /* CloseBraceToken */) { + reScanTemplateToken(); + literal = parseLiteralNode(); + } + else { + literal = parseExpectedToken(14 /* TemplateTail */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(16 /* CloseBraceToken */)); + } + span.literal = literal; + return finishNode(span); + } + function parseLiteralNode(internName) { + var node = createNode(token); + var text = scanner.getTokenValue(); + node.text = internName ? internIdentifier(text) : text; + if (scanner.hasExtendedUnicodeEscape()) { + node.hasExtendedUnicodeEscape = true; + } + if (scanner.isUnterminated()) { + node.isUnterminated = true; + } + var tokenPos = scanner.getTokenPos(); + nextToken(); + finishNode(node); + // Octal literals are not allowed in strict mode or ES5 + // Note that theoretically the following condition would hold true literals like 009, + // which is not octal.But because of how the scanner separates the tokens, we would + // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. + // We also do not need to check for negatives because any prefix operator would be part of a + // parent unary expression. + if (node.kind === 8 /* NumericLiteral */ + && sourceText.charCodeAt(tokenPos) === 48 /* _0 */ + && ts.isOctalDigit(sourceText.charCodeAt(tokenPos + 1))) { + node.flags |= 65536 /* OctalLiteral */; + } + return node; + } + // TYPES + function parseTypeReferenceOrTypePredicate() { + var typeName = parseEntityName(/*allowReservedWords*/ false, ts.Diagnostics.Type_expected); + if (typeName.kind === 69 /* Identifier */ && token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + var node_1 = createNode(150 /* TypePredicate */, typeName.pos); + node_1.parameterName = typeName; + node_1.type = parseType(); + return finishNode(node_1); + } + var node = createNode(151 /* TypeReference */, typeName.pos); + node.typeName = typeName; + if (!scanner.hasPrecedingLineBreak() && token === 25 /* LessThanToken */) { + node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); + } + return finishNode(node); + } + function parseTypeQuery() { + var node = createNode(154 /* TypeQuery */); + parseExpected(101 /* TypeOfKeyword */); + node.exprName = parseEntityName(/*allowReservedWords*/ true); + return finishNode(node); + } + function parseTypeParameter() { + var node = createNode(137 /* TypeParameter */); + node.name = parseIdentifier(); + if (parseOptional(83 /* ExtendsKeyword */)) { + // It's not uncommon for people to write improper constraints to a generic. If the + // user writes a constraint that is an expression and not an actual type, then parse + // it out as an expression (so we can recover well), but report that a type is needed + // instead. + if (isStartOfType() || !isStartOfExpression()) { + node.constraint = parseType(); + } + else { + // It was not a type, and it looked like an expression. Parse out an expression + // here so we recover well. Note: it is important that we call parseUnaryExpression + // and not parseExpression here. If the user has: + // + // + // + // We do *not* want to consume the > as we're consuming the expression for "". + node.expression = parseUnaryExpressionOrHigher(); + } + } + return finishNode(node); + } + function parseTypeParameters() { + if (token === 25 /* LessThanToken */) { + return parseBracketedList(17 /* TypeParameters */, parseTypeParameter, 25 /* LessThanToken */, 27 /* GreaterThanToken */); + } + } + function parseParameterType() { + if (parseOptional(54 /* ColonToken */)) { + return token === 9 /* StringLiteral */ + ? parseLiteralNode(/*internName*/ true) + : parseType(); + } + return undefined; + } + function isStartOfParameter() { + return token === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifier(token) || token === 55 /* AtToken */; + } + function setModifiers(node, modifiers) { + if (modifiers) { + node.flags |= modifiers.flags; + node.modifiers = modifiers; + } + } + function parseParameter() { + var node = createNode(138 /* Parameter */); + node.decorators = parseDecorators(); + setModifiers(node, parseModifiers()); + node.dotDotDotToken = parseOptionalToken(22 /* DotDotDotToken */); + // FormalParameter [Yield,Await]: + // BindingElement[?Yield,?Await] + node.name = parseIdentifierOrPattern(); + if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifier(token)) { + // in cases like + // 'use strict' + // function foo(static) + // isParameter('static') === true, because of isModifier('static') + // however 'static' is not a legal identifier in a strict mode. + // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined) + // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM) + // to avoid this we'll advance cursor to the next token. + nextToken(); + } + node.questionToken = parseOptionalToken(53 /* QuestionToken */); + node.type = parseParameterType(); + node.initializer = parseBindingElementInitializer(/*inParameter*/ true); + // Do not check for initializers in an ambient context for parameters. This is not + // a grammar error because the grammar allows arbitrary call signatures in + // an ambient context. + // It is actually not necessary for this to be an error at all. The reason is that + // function/constructor implementations are syntactically disallowed in ambient + // contexts. In addition, parameter initializers are semantically disallowed in + // overload signatures. So parameter initializers are transitively disallowed in + // ambient contexts. + return finishNode(node); + } + function parseBindingElementInitializer(inParameter) { + return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); + } + function parseParameterInitializer() { + return parseInitializer(/*inParameter*/ true); + } + function fillSignature(returnToken, yieldContext, awaitContext, requireCompleteParameterList, signature) { + var returnTokenRequired = returnToken === 34 /* EqualsGreaterThanToken */; + signature.typeParameters = parseTypeParameters(); + signature.parameters = parseParameterList(yieldContext, awaitContext, requireCompleteParameterList); + if (returnTokenRequired) { + parseExpected(returnToken); + signature.type = parseType(); + } + else if (parseOptional(returnToken)) { + signature.type = parseType(); + } + } + function parseParameterList(yieldContext, awaitContext, requireCompleteParameterList) { + // FormalParameters [Yield,Await]: (modified) + // [empty] + // FormalParameterList[?Yield,Await] + // + // FormalParameter[Yield,Await]: (modified) + // BindingElement[?Yield,Await] + // + // BindingElement [Yield,Await]: (modified) + // SingleNameBinding[?Yield,?Await] + // BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt + // + // SingleNameBinding [Yield,Await]: + // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt + if (parseExpected(17 /* OpenParenToken */)) { + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(yieldContext); + setAwaitContext(awaitContext); + var result = parseDelimitedList(16 /* Parameters */, parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + if (!parseExpected(18 /* CloseParenToken */) && requireCompleteParameterList) { + // Caller insisted that we had to end with a ) We didn't. So just return + // undefined here. + return undefined; + } + return result; + } + // We didn't even have an open paren. If the caller requires a complete parameter list, + // we definitely can't provide that. However, if they're ok with an incomplete one, + // then just return an empty set of parameters. + return requireCompleteParameterList ? undefined : createMissingList(); + } + function parseTypeMemberSemicolon() { + // We allow type members to be separated by commas or (possibly ASI) semicolons. + // First check if it was a comma. If so, we're done with the member. + if (parseOptional(24 /* CommaToken */)) { + return; + } + // Didn't have a comma. We must have a (possible ASI) semicolon. + parseSemicolon(); + } + function parseSignatureMember(kind) { + var node = createNode(kind); + if (kind === 148 /* ConstructSignature */) { + parseExpected(92 /* NewKeyword */); + } + fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function isIndexSignature() { + if (token !== 19 /* OpenBracketToken */) { + return false; + } + return lookAhead(isUnambiguouslyIndexSignature); + } + function isUnambiguouslyIndexSignature() { + // The only allowed sequence is: + // + // [id: + // + // However, for error recovery, we also check the following cases: + // + // [... + // [id, + // [id?, + // [id?: + // [id?] + // [public id + // [private id + // [protected id + // [] + // + nextToken(); + if (token === 22 /* DotDotDotToken */ || token === 20 /* CloseBracketToken */) { + return true; + } + if (ts.isModifier(token)) { + nextToken(); + if (isIdentifier()) { + return true; + } + } + else if (!isIdentifier()) { + return false; + } + else { + // Skip the identifier + nextToken(); + } + // A colon signifies a well formed indexer + // A comma should be a badly formed indexer because comma expressions are not allowed + // in computed properties. + if (token === 54 /* ColonToken */ || token === 24 /* CommaToken */) { + return true; + } + // Question mark could be an indexer with an optional property, + // or it could be a conditional expression in a computed property. + if (token !== 53 /* QuestionToken */) { + return false; + } + // If any of the following tokens are after the question mark, it cannot + // be a conditional expression, so treat it as an indexer. + nextToken(); + return token === 54 /* ColonToken */ || token === 24 /* CommaToken */ || token === 20 /* CloseBracketToken */; + } + function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { + var node = createNode(149 /* IndexSignature */, fullStart); + node.decorators = decorators; + setModifiers(node, modifiers); + node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 19 /* OpenBracketToken */, 20 /* CloseBracketToken */); + node.type = parseTypeAnnotation(); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function parsePropertyOrMethodSignature() { + var fullStart = scanner.getStartPos(); + var name = parsePropertyName(); + var questionToken = parseOptionalToken(53 /* QuestionToken */); + if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { + var method = createNode(142 /* MethodSignature */, fullStart); + method.name = name; + method.questionToken = questionToken; + // Method signatues don't exist in expression contexts. So they have neither + // [Yield] nor [Await] + fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, method); + parseTypeMemberSemicolon(); + return finishNode(method); + } + else { + var property = createNode(140 /* PropertySignature */, fullStart); + property.name = name; + property.questionToken = questionToken; + property.type = parseTypeAnnotation(); + parseTypeMemberSemicolon(); + return finishNode(property); + } + } + function isStartOfTypeMember() { + switch (token) { + case 17 /* OpenParenToken */: + case 25 /* LessThanToken */: + case 19 /* OpenBracketToken */: + return true; + default: + if (ts.isModifier(token)) { + var result = lookAhead(isStartOfIndexSignatureDeclaration); + if (result) { + return result; + } + } + return isLiteralPropertyName() && lookAhead(isTypeMemberWithLiteralPropertyName); + } + } + function isStartOfIndexSignatureDeclaration() { + while (ts.isModifier(token)) { + nextToken(); + } + return isIndexSignature(); + } + function isTypeMemberWithLiteralPropertyName() { + nextToken(); + return token === 17 /* OpenParenToken */ || + token === 25 /* LessThanToken */ || + token === 53 /* QuestionToken */ || + token === 54 /* ColonToken */ || + canParseSemicolon(); + } + function parseTypeMember() { + switch (token) { + case 17 /* OpenParenToken */: + case 25 /* LessThanToken */: + return parseSignatureMember(147 /* CallSignature */); + case 19 /* OpenBracketToken */: + // Indexer or computed property + return isIndexSignature() + ? parseIndexSignatureDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined) + : parsePropertyOrMethodSignature(); + case 92 /* NewKeyword */: + if (lookAhead(isStartOfConstructSignature)) { + return parseSignatureMember(148 /* ConstructSignature */); + } + // fall through. + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return parsePropertyOrMethodSignature(); + default: + // Index declaration as allowed as a type member. But as per the grammar, + // they also allow modifiers. So we have to check for an index declaration + // that might be following modifiers. This ensures that things work properly + // when incrementally parsing as the parser will produce the Index declaration + // if it has the same text regardless of whether it is inside a class or an + // object type. + if (ts.isModifier(token)) { + var result = tryParse(parseIndexSignatureWithModifiers); + if (result) { + return result; + } + } + if (ts.tokenIsIdentifierOrKeyword(token)) { + return parsePropertyOrMethodSignature(); + } + } + } + function parseIndexSignatureWithModifiers() { + var fullStart = scanner.getStartPos(); + var decorators = parseDecorators(); + var modifiers = parseModifiers(); + return isIndexSignature() + ? parseIndexSignatureDeclaration(fullStart, decorators, modifiers) + : undefined; + } + function isStartOfConstructSignature() { + nextToken(); + return token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */; + } + function parseTypeLiteral() { + var node = createNode(155 /* TypeLiteral */); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseObjectTypeMembers() { + var members; + if (parseExpected(15 /* OpenBraceToken */)) { + members = parseList(4 /* TypeMembers */, parseTypeMember); + parseExpected(16 /* CloseBraceToken */); + } + else { + members = createMissingList(); + } + return members; + } + function parseTupleType() { + var node = createNode(157 /* TupleType */); + node.elementTypes = parseBracketedList(19 /* TupleElementTypes */, parseType, 19 /* OpenBracketToken */, 20 /* CloseBracketToken */); + return finishNode(node); + } + function parseParenthesizedType() { + var node = createNode(160 /* ParenthesizedType */); + parseExpected(17 /* OpenParenToken */); + node.type = parseType(); + parseExpected(18 /* CloseParenToken */); + return finishNode(node); + } + function parseFunctionOrConstructorType(kind) { + var node = createNode(kind); + if (kind === 153 /* ConstructorType */) { + parseExpected(92 /* NewKeyword */); + } + fillSignature(34 /* EqualsGreaterThanToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); + return finishNode(node); + } + function parseKeywordAndNoDot() { + var node = parseTokenNode(); + return token === 21 /* DotToken */ ? undefined : node; + } + function parseNonArrayType() { + switch (token) { + case 117 /* AnyKeyword */: + case 130 /* StringKeyword */: + case 128 /* NumberKeyword */: + case 120 /* BooleanKeyword */: + case 131 /* SymbolKeyword */: + // If these are followed by a dot, then parse these out as a dotted type reference instead. + var node = tryParse(parseKeywordAndNoDot); + return node || parseTypeReferenceOrTypePredicate(); + case 103 /* VoidKeyword */: + case 97 /* ThisKeyword */: + return parseTokenNode(); + case 101 /* TypeOfKeyword */: + return parseTypeQuery(); + case 15 /* OpenBraceToken */: + return parseTypeLiteral(); + case 19 /* OpenBracketToken */: + return parseTupleType(); + case 17 /* OpenParenToken */: + return parseParenthesizedType(); + default: + return parseTypeReferenceOrTypePredicate(); + } + } + function isStartOfType() { + switch (token) { + case 117 /* AnyKeyword */: + case 130 /* StringKeyword */: + case 128 /* NumberKeyword */: + case 120 /* BooleanKeyword */: + case 131 /* SymbolKeyword */: + case 103 /* VoidKeyword */: + case 97 /* ThisKeyword */: + case 101 /* TypeOfKeyword */: + case 15 /* OpenBraceToken */: + case 19 /* OpenBracketToken */: + case 25 /* LessThanToken */: + case 92 /* NewKeyword */: + return true; + case 17 /* OpenParenToken */: + // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, + // or something that starts a type. We don't want to consider things like '(1)' a type. + return lookAhead(isStartOfParenthesizedOrFunctionType); + default: + return isIdentifier(); + } + } + function isStartOfParenthesizedOrFunctionType() { + nextToken(); + return token === 18 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); + } + function parseArrayTypeOrHigher() { + var type = parseNonArrayType(); + while (!scanner.hasPrecedingLineBreak() && parseOptional(19 /* OpenBracketToken */)) { + parseExpected(20 /* CloseBracketToken */); + var node = createNode(156 /* ArrayType */, type.pos); + node.elementType = type; + type = finishNode(node); + } + return type; + } + function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { + var type = parseConstituentType(); + if (token === operator) { + var types = [type]; + types.pos = type.pos; + while (parseOptional(operator)) { + types.push(parseConstituentType()); + } + types.end = getNodeEnd(); + var node = createNode(kind, type.pos); + node.types = types; + type = finishNode(node); + } + return type; + } + function parseIntersectionTypeOrHigher() { + return parseUnionOrIntersectionType(159 /* IntersectionType */, parseArrayTypeOrHigher, 46 /* AmpersandToken */); + } + function parseUnionTypeOrHigher() { + return parseUnionOrIntersectionType(158 /* UnionType */, parseIntersectionTypeOrHigher, 47 /* BarToken */); + } + function isStartOfFunctionType() { + if (token === 25 /* LessThanToken */) { + return true; + } + return token === 17 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); + } + function isUnambiguouslyStartOfFunctionType() { + nextToken(); + if (token === 18 /* CloseParenToken */ || token === 22 /* DotDotDotToken */) { + // ( ) + // ( ... + return true; + } + if (isIdentifier() || ts.isModifier(token)) { + nextToken(); + if (token === 54 /* ColonToken */ || token === 24 /* CommaToken */ || + token === 53 /* QuestionToken */ || token === 56 /* EqualsToken */ || + isIdentifier() || ts.isModifier(token)) { + // ( id : + // ( id , + // ( id ? + // ( id = + // ( modifier id + return true; + } + if (token === 18 /* CloseParenToken */) { + nextToken(); + if (token === 34 /* EqualsGreaterThanToken */) { + // ( id ) => + return true; + } + } + } + return false; + } + function parseType() { + // The rules about 'yield' only apply to actual code/expression contexts. They don't + // apply to 'type' contexts. So we disable these parameters here before moving on. + return doOutsideOfContext(10 /* TypeExcludesFlags */, parseTypeWorker); + } + function parseTypeWorker() { + if (isStartOfFunctionType()) { + return parseFunctionOrConstructorType(152 /* FunctionType */); + } + if (token === 92 /* NewKeyword */) { + return parseFunctionOrConstructorType(153 /* ConstructorType */); + } + return parseUnionTypeOrHigher(); + } + function parseTypeAnnotation() { + return parseOptional(54 /* ColonToken */) ? parseType() : undefined; + } + // EXPRESSIONS + function isStartOfLeftHandSideExpression() { + switch (token) { + case 97 /* ThisKeyword */: + case 95 /* SuperKeyword */: + case 93 /* NullKeyword */: + case 99 /* TrueKeyword */: + case 84 /* FalseKeyword */: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 11 /* NoSubstitutionTemplateLiteral */: + case 12 /* TemplateHead */: + case 17 /* OpenParenToken */: + case 19 /* OpenBracketToken */: + case 15 /* OpenBraceToken */: + case 87 /* FunctionKeyword */: + case 73 /* ClassKeyword */: + case 92 /* NewKeyword */: + case 39 /* SlashToken */: + case 61 /* SlashEqualsToken */: + case 69 /* Identifier */: + return true; + default: + return isIdentifier(); + } + } + function isStartOfExpression() { + if (isStartOfLeftHandSideExpression()) { + return true; + } + switch (token) { + case 35 /* PlusToken */: + case 36 /* MinusToken */: + case 50 /* TildeToken */: + case 49 /* ExclamationToken */: + case 78 /* DeleteKeyword */: + case 101 /* TypeOfKeyword */: + case 103 /* VoidKeyword */: + case 41 /* PlusPlusToken */: + case 42 /* MinusMinusToken */: + case 25 /* LessThanToken */: + case 119 /* AwaitKeyword */: + case 114 /* YieldKeyword */: + // Yield/await always starts an expression. Either it is an identifier (in which case + // it is definitely an expression). Or it's a keyword (either because we're in + // a generator or async function, or in strict mode (or both)) and it started a yield or await expression. + return true; + default: + // Error tolerance. If we see the start of some binary operator, we consider + // that the start of an expression. That way we'll parse out a missing identifier, + // give a good message about an identifier being missing, and then consume the + // rest of the binary expression. + if (isBinaryOperator()) { + return true; + } + return isIdentifier(); + } + } + function isStartOfExpressionStatement() { + // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. + return token !== 15 /* OpenBraceToken */ && + token !== 87 /* FunctionKeyword */ && + token !== 73 /* ClassKeyword */ && + token !== 55 /* AtToken */ && + isStartOfExpression(); + } + function allowInAndParseExpression() { + return allowInAnd(parseExpression); + } + function parseExpression() { + // Expression[in]: + // AssignmentExpression[in] + // Expression[in] , AssignmentExpression[in] + // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(false); + } + var expr = parseAssignmentExpressionOrHigher(); + var operatorToken; + while ((operatorToken = parseOptionalToken(24 /* CommaToken */))) { + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); + } + if (saveDecoratorContext) { + setDecoratorContext(true); + } + return expr; + } + function parseInitializer(inParameter) { + if (token !== 56 /* EqualsToken */) { + // It's not uncommon during typing for the user to miss writing the '=' token. Check if + // there is no newline after the last token and if we're on an expression. If so, parse + // this as an equals-value clause with a missing equals. + // NOTE: There are two places where we allow equals-value clauses. The first is in a + // variable declarator. The second is with a parameter. For variable declarators + // it's more likely that a { would be a allowed (as an object literal). While this + // is also allowed for parameters, the risk is that we consume the { as an object + // literal when it really will be for the block following the parameter. + if (scanner.hasPrecedingLineBreak() || (inParameter && token === 15 /* OpenBraceToken */) || !isStartOfExpression()) { + // preceding line break, open brace in a parameter (likely a function body) or current token is not an expression - + // do not try to parse initializer + return undefined; + } + } + // Initializer[In, Yield] : + // = AssignmentExpression[?In, ?Yield] + parseExpected(56 /* EqualsToken */); + return parseAssignmentExpressionOrHigher(); + } + function parseAssignmentExpressionOrHigher() { + // AssignmentExpression[in,yield]: + // 1) ConditionalExpression[?in,?yield] + // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield] + // 3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield] + // 4) ArrowFunctionExpression[?in,?yield] + // 5) [+Yield] YieldExpression[?In] + // + // Note: for ease of implementation we treat productions '2' and '3' as the same thing. + // (i.e. they're both BinaryExpressions with an assignment operator in it). + // First, do the simple check if we have a YieldExpression (production '5'). + if (isYieldExpression()) { + return parseYieldExpression(); + } + // Then, check if we have an arrow function (production '4') that starts with a parenthesized + // parameter list. If we do, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is + // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done + // with AssignmentExpression if we see one. + var arrowExpression = tryParseParenthesizedArrowFunctionExpression(); + if (arrowExpression) { + return arrowExpression; + } + // Now try to see if we're in production '1', '2' or '3'. A conditional expression can + // start with a LogicalOrExpression, while the assignment productions can only start with + // LeftHandSideExpressions. + // + // So, first, we try to just parse out a BinaryExpression. If we get something that is a + // LeftHandSide or higher, then we can try to parse out the assignment expression part. + // Otherwise, we try to parse out the conditional expression bit. We want to allow any + // binary expression here, so we pass in the 'lowest' precedence here so that it matches + // and consumes anything. + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized + // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single + // identifier and the current token is an arrow. + if (expr.kind === 69 /* Identifier */ && token === 34 /* EqualsGreaterThanToken */) { + return parseSimpleArrowFunctionExpression(expr); + } + // Now see if we might be in cases '2' or '3'. + // If the expression was a LHS expression, and we have an assignment operator, then + // we're in '2' or '3'. Consume the assignment and return. + // + // Note: we call reScanGreaterToken so that we get an appropriately merged token + // for cases like > > = becoming >>= + if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); + } + // It wasn't an assignment or a lambda. This is a conditional expression: + return parseConditionalExpressionRest(expr); + } + function isYieldExpression() { + if (token === 114 /* YieldKeyword */) { + // If we have a 'yield' keyword, and htis is a context where yield expressions are + // allowed, then definitely parse out a yield expression. + if (inYieldContext()) { + return true; + } + // We're in a context where 'yield expr' is not allowed. However, if we can + // definitely tell that the user was trying to parse a 'yield expr' and not + // just a normal expr that start with a 'yield' identifier, then parse out + // a 'yield expr'. We can then report an error later that they are only + // allowed in generator expressions. + // + // for example, if we see 'yield(foo)', then we'll have to treat that as an + // invocation expression of something called 'yield'. However, if we have + // 'yield foo' then that is not legal as a normal expression, so we can + // definitely recognize this as a yield expression. + // + // for now we just check if the next token is an identifier. More heuristics + // can be added here later as necessary. We just need to make sure that we + // don't accidently consume something legal. + return lookAhead(nextTokenIsIdentifierOrKeywordOrNumberOnSameLine); + } + return false; + } + function nextTokenIsIdentifierOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && isIdentifier(); + } + function parseYieldExpression() { + var node = createNode(184 /* YieldExpression */); + // YieldExpression[In] : + // yield + // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] + // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] + nextToken(); + if (!scanner.hasPrecedingLineBreak() && + (token === 37 /* AsteriskToken */ || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + else { + // if the next token is not on the same line as yield. or we don't have an '*' or + // the start of an expressin, then this is just a simple "yield" expression. + return finishNode(node); + } + } + function parseSimpleArrowFunctionExpression(identifier) { + ts.Debug.assert(token === 34 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + var node = createNode(174 /* ArrowFunction */, identifier.pos); + var parameter = createNode(138 /* Parameter */, identifier.pos); + parameter.name = identifier; + finishNode(parameter); + node.parameters = [parameter]; + node.parameters.pos = parameter.pos; + node.parameters.end = parameter.end; + node.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, false, ts.Diagnostics._0_expected, "=>"); + node.body = parseArrowFunctionExpressionBody(/*isAsync*/ false); + return finishNode(node); + } + function tryParseParenthesizedArrowFunctionExpression() { + var triState = isParenthesizedArrowFunctionExpression(); + if (triState === 0 /* False */) { + // It's definitely not a parenthesized arrow function expression. + return undefined; + } + // If we definitely have an arrow function, then we can just parse one, not requiring a + // following => or { token. Otherwise, we *might* have an arrow function. Try to parse + // it out, but don't allow any ambiguity, and return 'undefined' if this could be an + // expression instead. + var arrowFunction = triState === 1 /* True */ + ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true) + : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); + if (!arrowFunction) { + // Didn't appear to actually be a parenthesized arrow function. Just bail out. + return undefined; + } + var isAsync = !!(arrowFunction.flags & 512 /* Async */); + // If we have an arrow, then try to parse the body. Even if not, try to parse if we + // have an opening brace, just in case we're in an error state. + var lastToken = token; + arrowFunction.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); + arrowFunction.body = (lastToken === 34 /* EqualsGreaterThanToken */ || lastToken === 15 /* OpenBraceToken */) + ? parseArrowFunctionExpressionBody(isAsync) + : parseIdentifier(); + return finishNode(arrowFunction); + } + // True -> We definitely expect a parenthesized arrow function here. + // False -> There *cannot* be a parenthesized arrow function here. + // Unknown -> There *might* be a parenthesized arrow function here. + // Speculatively look ahead to be sure, and rollback if not. + function isParenthesizedArrowFunctionExpression() { + if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */ || token === 118 /* AsyncKeyword */) { + return lookAhead(isParenthesizedArrowFunctionExpressionWorker); + } + if (token === 34 /* EqualsGreaterThanToken */) { + // ERROR RECOVERY TWEAK: + // If we see a standalone => try to parse it as an arrow function expression as that's + // likely what the user intended to write. + return 1 /* True */; + } + // Definitely not a parenthesized arrow function. + return 0 /* False */; + } + function isParenthesizedArrowFunctionExpressionWorker() { + if (token === 118 /* AsyncKeyword */) { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return 0 /* False */; + } + if (token !== 17 /* OpenParenToken */ && token !== 25 /* LessThanToken */) { + return 0 /* False */; + } + } + var first = token; + var second = nextToken(); + if (first === 17 /* OpenParenToken */) { + if (second === 18 /* CloseParenToken */) { + // Simple cases: "() =>", "(): ", and "() {". + // This is an arrow function with no parameters. + // The last one is not actually an arrow function, + // but this is probably what the user intended. + var third = nextToken(); + switch (third) { + case 34 /* EqualsGreaterThanToken */: + case 54 /* ColonToken */: + case 15 /* OpenBraceToken */: + return 1 /* True */; + default: + return 0 /* False */; + } + } + // If encounter "([" or "({", this could be the start of a binding pattern. + // Examples: + // ([ x ]) => { } + // ({ x }) => { } + // ([ x ]) + // ({ x }) + if (second === 19 /* OpenBracketToken */ || second === 15 /* OpenBraceToken */) { + return 2 /* Unknown */; + } + // Simple case: "(..." + // This is an arrow function with a rest parameter. + if (second === 22 /* DotDotDotToken */) { + return 1 /* True */; + } + // If we had "(" followed by something that's not an identifier, + // then this definitely doesn't look like a lambda. + // Note: we could be a little more lenient and allow + // "(public" or "(private". These would not ever actually be allowed, + // but we could provide a good error message instead of bailing out. + if (!isIdentifier()) { + return 0 /* False */; + } + // If we have something like "(a:", then we must have a + // type-annotated parameter in an arrow function expression. + if (nextToken() === 54 /* ColonToken */) { + return 1 /* True */; + } + // This *could* be a parenthesized arrow function. + // Return Unknown to let the caller know. + return 2 /* Unknown */; + } + else { + ts.Debug.assert(first === 25 /* LessThanToken */); + // If we have "<" not followed by an identifier, + // then this definitely is not an arrow function. + if (!isIdentifier()) { + return 0 /* False */; + } + // JSX overrides + if (sourceFile.languageVariant === 1 /* JSX */) { + var isArrowFunctionInJsx = lookAhead(function () { + var third = nextToken(); + if (third === 83 /* ExtendsKeyword */) { + var fourth = nextToken(); + switch (fourth) { + case 56 /* EqualsToken */: + case 27 /* GreaterThanToken */: + return false; + default: + return true; + } + } + else if (third === 24 /* CommaToken */) { + return true; + } + return false; + }); + if (isArrowFunctionInJsx) { + return 1 /* True */; + } + return 0 /* False */; + } + // This *could* be a parenthesized arrow function. + return 2 /* Unknown */; + } + } + function parsePossibleParenthesizedArrowFunctionExpressionHead() { + return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false); + } + function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { + var node = createNode(174 /* ArrowFunction */); + setModifiers(node, parseModifiersForArrowFunction()); + var isAsync = !!(node.flags & 512 /* Async */); + // Arrow functions are never generators. + // + // If we're speculatively parsing a signature for a parenthesized arrow function, then + // we have to have a complete parameter list. Otherwise we might see something like + // a => (b => c) + // And think that "(b =>" was actually a parenthesized arrow function with a missing + // close paren. + fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ !allowAmbiguity, node); + // If we couldn't get parameters, we definitely could not parse out an arrow function. + if (!node.parameters) { + return undefined; + } + // Parsing a signature isn't enough. + // Parenthesized arrow signatures often look like other valid expressions. + // For instance: + // - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value. + // - "(x,y)" is a comma expression parsed as a signature with two parameters. + // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. + // + // So we need just a bit of lookahead to ensure that it can only be a signature. + if (!allowAmbiguity && token !== 34 /* EqualsGreaterThanToken */ && token !== 15 /* OpenBraceToken */) { + // Returning undefined here will cause our caller to rewind to where we started from. + return undefined; + } + return node; + } + function parseArrowFunctionExpressionBody(isAsync) { + if (token === 15 /* OpenBraceToken */) { + return parseFunctionBlock(/*allowYield*/ false, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); + } + if (token !== 23 /* SemicolonToken */ && + token !== 87 /* FunctionKeyword */ && + token !== 73 /* ClassKeyword */ && + isStartOfStatement() && + !isStartOfExpressionStatement()) { + // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) + // + // Here we try to recover from a potential error situation in the case where the + // user meant to supply a block. For example, if the user wrote: + // + // a => + // let v = 0; + // } + // + // they may be missing an open brace. Check to see if that's the case so we can + // try to recover better. If we don't do this, then the next close curly we see may end + // up preemptively closing the containing construct. + // + // Note: even when 'ignoreMissingOpenBrace' is passed as true, parseBody will still error. + return parseFunctionBlock(/*allowYield*/ false, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ true); + } + return isAsync + ? doInAwaitContext(parseAssignmentExpressionOrHigher) + : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + } + function parseConditionalExpressionRest(leftOperand) { + // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. + var questionToken = parseOptionalToken(53 /* QuestionToken */); + if (!questionToken) { + return leftOperand; + } + // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and + // we do not that for the 'whenFalse' part. + var node = createNode(182 /* ConditionalExpression */, leftOperand.pos); + node.condition = leftOperand; + node.questionToken = questionToken; + node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); + node.colonToken = parseExpectedToken(54 /* ColonToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(54 /* ColonToken */)); + node.whenFalse = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseBinaryExpressionOrHigher(precedence) { + var leftOperand = parseUnaryExpressionOrHigher(); + return parseBinaryExpressionRest(precedence, leftOperand); + } + function isInOrOfKeyword(t) { + return t === 90 /* InKeyword */ || t === 134 /* OfKeyword */; + } + function parseBinaryExpressionRest(precedence, leftOperand) { + while (true) { + // We either have a binary operator here, or we're finished. We call + // reScanGreaterToken so that we merge token sequences like > and = into >= + reScanGreaterToken(); + var newPrecedence = getBinaryOperatorPrecedence(); + // Check the precedence to see if we should "take" this operator + // - For left associative operator (all operator but **), consume the operator, + // recursively call the function below, and parse binaryExpression as a rightOperand + // of the caller if the new precendence of the operator is greater then or equal to the current precendence. + // For example: + // a - b - c; + // ^token; leftOperand = b. Return b to the caller as a rightOperand + // a * b - c + // ^token; leftOperand = b. Return b to the caller as a rightOperand + // a - b * c; + // ^token; leftOperand = b. Return b * c to the caller as a rightOperand + // - For right associative operator (**), consume the operator, recursively call the function + // and parse binaryExpression as a rightOperand of the caller if the new precendence of + // the operator is strictly grater than the current precendence + // For example: + // a ** b ** c; + // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand + // a - b ** c; + // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand + // a ** b - c + // ^token; leftOperand = b. Return b to the caller as a rightOperand + var consumeCurrentOperator = token === 38 /* AsteriskAsteriskToken */ ? + newPrecedence >= precedence : + newPrecedence > precedence; + if (!consumeCurrentOperator) { + break; + } + if (token === 90 /* InKeyword */ && inDisallowInContext()) { + break; + } + if (token === 116 /* AsKeyword */) { + // Make sure we *do* perform ASI for constructs like this: + // var x = foo + // as (Bar) + // This should be parsed as an initialized variable, followed + // by a function call to 'as' with the argument 'Bar' + if (scanner.hasPrecedingLineBreak()) { + break; + } + else { + nextToken(); + leftOperand = makeAsExpression(leftOperand, parseType()); + } + } + else { + leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); + } + } + return leftOperand; + } + function isBinaryOperator() { + if (inDisallowInContext() && token === 90 /* InKeyword */) { + return false; + } + return getBinaryOperatorPrecedence() > 0; + } + function getBinaryOperatorPrecedence() { + switch (token) { + case 52 /* BarBarToken */: + return 1; + case 51 /* AmpersandAmpersandToken */: + return 2; + case 47 /* BarToken */: + return 3; + case 48 /* CaretToken */: + return 4; + case 46 /* AmpersandToken */: + return 5; + case 30 /* EqualsEqualsToken */: + case 31 /* ExclamationEqualsToken */: + case 32 /* EqualsEqualsEqualsToken */: + case 33 /* ExclamationEqualsEqualsToken */: + return 6; + case 25 /* LessThanToken */: + case 27 /* GreaterThanToken */: + case 28 /* LessThanEqualsToken */: + case 29 /* GreaterThanEqualsToken */: + case 91 /* InstanceOfKeyword */: + case 90 /* InKeyword */: + case 116 /* AsKeyword */: + return 7; + case 43 /* LessThanLessThanToken */: + case 44 /* GreaterThanGreaterThanToken */: + case 45 /* GreaterThanGreaterThanGreaterThanToken */: + return 8; + case 35 /* PlusToken */: + case 36 /* MinusToken */: + return 9; + case 37 /* AsteriskToken */: + case 39 /* SlashToken */: + case 40 /* PercentToken */: + return 10; + case 38 /* AsteriskAsteriskToken */: + return 11; + } + // -1 is lower than all other precedences. Returning it will cause binary expression + // parsing to stop. + return -1; + } + function makeBinaryExpression(left, operatorToken, right) { + var node = createNode(181 /* BinaryExpression */, left.pos); + node.left = left; + node.operatorToken = operatorToken; + node.right = right; + return finishNode(node); + } + function makeAsExpression(left, right) { + var node = createNode(189 /* AsExpression */, left.pos); + node.expression = left; + node.type = right; + return finishNode(node); + } + function parsePrefixUnaryExpression() { + var node = createNode(179 /* PrefixUnaryExpression */); + node.operator = token; + nextToken(); + node.operand = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseDeleteExpression() { + var node = createNode(175 /* DeleteExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseTypeOfExpression() { + var node = createNode(176 /* TypeOfExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseVoidExpression() { + var node = createNode(177 /* VoidExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function isAwaitExpression() { + if (token === 119 /* AwaitKeyword */) { + if (inAwaitContext()) { + return true; + } + // here we are using similar heuristics as 'isYieldExpression' + return lookAhead(nextTokenIsIdentifierOnSameLine); + } + return false; + } + function parseAwaitExpression() { + var node = createNode(178 /* AwaitExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + /** + * Parse ES7 unary expression and await expression + * + * ES7 UnaryExpression: + * 1) SimpleUnaryExpression[?yield] + * 2) IncrementExpression[?yield] ** UnaryExpression[?yield] + */ + function parseUnaryExpressionOrHigher() { + if (isAwaitExpression()) { + return parseAwaitExpression(); + } + if (isIncrementExpression()) { + var incrementExpression = parseIncrementExpression(); + return token === 38 /* AsteriskAsteriskToken */ ? + parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : + incrementExpression; + } + var unaryOperator = token; + var simpleUnaryExpression = parseSimpleUnaryExpression(); + if (token === 38 /* AsteriskAsteriskToken */) { + var diagnostic; + var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + if (simpleUnaryExpression.kind === 171 /* TypeAssertionExpression */) { + parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); + } + else { + parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + } + } + return simpleUnaryExpression; + } + /** + * Parse ES7 simple-unary expression or higher: + * + * ES7 SimpleUnaryExpression: + * 1) IncrementExpression[?yield] + * 2) delete UnaryExpression[?yield] + * 3) void UnaryExpression[?yield] + * 4) typeof UnaryExpression[?yield] + * 5) + UnaryExpression[?yield] + * 6) - UnaryExpression[?yield] + * 7) ~ UnaryExpression[?yield] + * 8) ! UnaryExpression[?yield] + */ + function parseSimpleUnaryExpression() { + switch (token) { + case 35 /* PlusToken */: + case 36 /* MinusToken */: + case 50 /* TildeToken */: + case 49 /* ExclamationToken */: + return parsePrefixUnaryExpression(); + case 78 /* DeleteKeyword */: + return parseDeleteExpression(); + case 101 /* TypeOfKeyword */: + return parseTypeOfExpression(); + case 103 /* VoidKeyword */: + return parseVoidExpression(); + case 25 /* LessThanToken */: + // This is modified UnaryExpression grammar in TypeScript + // UnaryExpression (modified): + // < type > UnaryExpression + return parseTypeAssertion(); + default: + return parseIncrementExpression(); + } + } + /** + * Check if the current token can possibly be an ES7 increment expression. + * + * ES7 IncrementExpression: + * LeftHandSideExpression[?Yield] + * LeftHandSideExpression[?Yield][no LineTerminator here]++ + * LeftHandSideExpression[?Yield][no LineTerminator here]-- + * ++LeftHandSideExpression[?Yield] + * --LeftHandSideExpression[?Yield] + */ + function isIncrementExpression() { + // This function is called inside parseUnaryExpression to decide + // whether to call parseSimpleUnaryExpression or call parseIncrmentExpression directly + switch (token) { + case 35 /* PlusToken */: + case 36 /* MinusToken */: + case 50 /* TildeToken */: + case 49 /* ExclamationToken */: + case 78 /* DeleteKeyword */: + case 101 /* TypeOfKeyword */: + case 103 /* VoidKeyword */: + return false; + case 25 /* LessThanToken */: + // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression + if (sourceFile.languageVariant !== 1 /* JSX */) { + return false; + } + // We are in JSX context and the token is part of JSXElement. + // Fall through + default: + return true; + } + } + /** + * Parse ES7 IncrementExpression. IncrementExpression is used instead of ES6's PostFixExpression. + * + * ES7 IncrementExpression[yield]: + * 1) LeftHandSideExpression[?yield] + * 2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++ + * 3) LeftHandSideExpression[?yield] [[no LineTerminator here]]-- + * 4) ++LeftHandSideExpression[?yield] + * 5) --LeftHandSideExpression[?yield] + * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression + */ + function parseIncrementExpression() { + if (token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) { + var node = createNode(179 /* PrefixUnaryExpression */); + node.operator = token; + nextToken(); + node.operand = parseLeftHandSideExpressionOrHigher(); + return finishNode(node); + } + else if (sourceFile.languageVariant === 1 /* JSX */ && token === 25 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { + // JSXElement is part of primaryExpression + return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); + } + var expression = parseLeftHandSideExpressionOrHigher(); + ts.Debug.assert(ts.isLeftHandSideExpression(expression)); + if ((token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(180 /* PostfixUnaryExpression */, expression.pos); + node.operand = expression; + node.operator = token; + nextToken(); + return finishNode(node); + } + return expression; + } + function parseLeftHandSideExpressionOrHigher() { + // Original Ecma: + // LeftHandSideExpression: See 11.2 + // NewExpression + // CallExpression + // + // Our simplification: + // + // LeftHandSideExpression: See 11.2 + // MemberExpression + // CallExpression + // + // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with + // MemberExpression to make our lives easier. + // + // to best understand the below code, it's important to see how CallExpression expands + // out into its own productions: + // + // CallExpression: + // MemberExpression Arguments + // CallExpression Arguments + // CallExpression[Expression] + // CallExpression.IdentifierName + // super ( ArgumentListopt ) + // super.IdentifierName + // + // Because of the recursion in these calls, we need to bottom out first. There are two + // bottom out states we can run into. Either we see 'super' which must start either of + // the last two CallExpression productions. Or we have a MemberExpression which either + // completes the LeftHandSideExpression, or starts the beginning of the first four + // CallExpression productions. + var expression = token === 95 /* SuperKeyword */ + ? parseSuperExpression() + : parseMemberExpressionOrHigher(); + // Now, we *may* be complete. However, we might have consumed the start of a + // CallExpression. As such, we need to consume the rest of it here to be complete. + return parseCallExpressionRest(expression); + } + function parseMemberExpressionOrHigher() { + // Note: to make our lives simpler, we decompose the the NewExpression productions and + // place ObjectCreationExpression and FunctionExpression into PrimaryExpression. + // like so: + // + // PrimaryExpression : See 11.1 + // this + // Identifier + // Literal + // ArrayLiteral + // ObjectLiteral + // (Expression) + // FunctionExpression + // new MemberExpression Arguments? + // + // MemberExpression : See 11.2 + // PrimaryExpression + // MemberExpression[Expression] + // MemberExpression.IdentifierName + // + // CallExpression : See 11.2 + // MemberExpression + // CallExpression Arguments + // CallExpression[Expression] + // CallExpression.IdentifierName + // + // Technically this is ambiguous. i.e. CallExpression defines: + // + // CallExpression: + // CallExpression Arguments + // + // If you see: "new Foo()" + // + // Then that could be treated as a single ObjectCreationExpression, or it could be + // treated as the invocation of "new Foo". We disambiguate that in code (to match + // the original grammar) by making sure that if we see an ObjectCreationExpression + // we always consume arguments if they are there. So we treat "new Foo()" as an + // object creation only, and not at all as an invocation) Another way to think + // about this is that for every "new" that we see, we will consume an argument list if + // it is there as part of the *associated* object creation node. Any additional + // argument lists we see, will become invocation expressions. + // + // Because there are no other places in the grammar now that refer to FunctionExpression + // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression + // production. + // + // Because CallExpression and MemberExpression are left recursive, we need to bottom out + // of the recursion immediately. So we parse out a primary expression to start with. + var expression = parsePrimaryExpression(); + return parseMemberExpressionRest(expression); + } + function parseSuperExpression() { + var expression = parseTokenNode(); + if (token === 17 /* OpenParenToken */ || token === 21 /* DotToken */ || token === 19 /* OpenBracketToken */) { + return expression; + } + // If we have seen "super" it must be followed by '(' or '.'. + // If it wasn't then just try to parse out a '.' and report an error. + var node = createNode(166 /* PropertyAccessExpression */, expression.pos); + node.expression = expression; + node.dotToken = parseExpectedToken(21 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + return finishNode(node); + } + function parseJsxElementOrSelfClosingElement(inExpressionContext) { + var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); + if (opening.kind === 235 /* JsxOpeningElement */) { + var node = createNode(233 /* JsxElement */, opening.pos); + node.openingElement = opening; + node.children = parseJsxChildren(node.openingElement.tagName); + node.closingElement = parseJsxClosingElement(inExpressionContext); + return finishNode(node); + } + else { + ts.Debug.assert(opening.kind === 234 /* JsxSelfClosingElement */); + // Nothing else to do for self-closing elements + return opening; + } + } + function parseJsxText() { + var node = createNode(236 /* JsxText */, scanner.getStartPos()); + token = scanner.scanJsxToken(); + return finishNode(node); + } + function parseJsxChild() { + switch (token) { + case 236 /* JsxText */: + return parseJsxText(); + case 15 /* OpenBraceToken */: + return parseJsxExpression(/*inExpressionContext*/ false); + case 25 /* LessThanToken */: + return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ false); + } + ts.Debug.fail("Unknown JSX child kind " + token); + } + function parseJsxChildren(openingTagName) { + var result = []; + result.pos = scanner.getStartPos(); + var saveParsingContext = parsingContext; + parsingContext |= 1 << 14 /* JsxChildren */; + while (true) { + token = scanner.reScanJsxToken(); + if (token === 26 /* LessThanSlashToken */) { + break; + } + else if (token === 1 /* EndOfFileToken */) { + parseErrorAtCurrentToken(ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + break; + } + result.push(parseJsxChild()); + } + result.end = scanner.getTokenPos(); + parsingContext = saveParsingContext; + return result; + } + function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { + var fullStart = scanner.getStartPos(); + parseExpected(25 /* LessThanToken */); + var tagName = parseJsxElementName(); + var attributes = parseList(13 /* JsxAttributes */, parseJsxAttribute); + var node; + if (token === 27 /* GreaterThanToken */) { + // Closing tag, so scan the immediately-following text with the JSX scanning instead + // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate + // scanning errors + node = createNode(235 /* JsxOpeningElement */, fullStart); + scanJsxText(); + } + else { + parseExpected(39 /* SlashToken */); + if (inExpressionContext) { + parseExpected(27 /* GreaterThanToken */); + } + else { + parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*advance*/ false); + scanJsxText(); + } + node = createNode(234 /* JsxSelfClosingElement */, fullStart); + } + node.tagName = tagName; + node.attributes = attributes; + return finishNode(node); + } + function parseJsxElementName() { + scanJsxIdentifier(); + var elementName = parseIdentifierName(); + while (parseOptional(21 /* DotToken */)) { + scanJsxIdentifier(); + var node = createNode(135 /* QualifiedName */, elementName.pos); + node.left = elementName; + node.right = parseIdentifierName(); + elementName = finishNode(node); + } + return elementName; + } + function parseJsxExpression(inExpressionContext) { + var node = createNode(240 /* JsxExpression */); + parseExpected(15 /* OpenBraceToken */); + if (token !== 16 /* CloseBraceToken */) { + node.expression = parseExpression(); + } + if (inExpressionContext) { + parseExpected(16 /* CloseBraceToken */); + } + else { + parseExpected(16 /* CloseBraceToken */, /*message*/ undefined, /*advance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxAttribute() { + if (token === 15 /* OpenBraceToken */) { + return parseJsxSpreadAttribute(); + } + scanJsxIdentifier(); + var node = createNode(238 /* JsxAttribute */); + node.name = parseIdentifierName(); + if (parseOptional(56 /* EqualsToken */)) { + switch (token) { + case 9 /* StringLiteral */: + node.initializer = parseLiteralNode(); + break; + default: + node.initializer = parseJsxExpression(/*inExpressionContext*/ true); + break; + } + } + return finishNode(node); + } + function parseJsxSpreadAttribute() { + var node = createNode(239 /* JsxSpreadAttribute */); + parseExpected(15 /* OpenBraceToken */); + parseExpected(22 /* DotDotDotToken */); + node.expression = parseExpression(); + parseExpected(16 /* CloseBraceToken */); + return finishNode(node); + } + function parseJsxClosingElement(inExpressionContext) { + var node = createNode(237 /* JsxClosingElement */); + parseExpected(26 /* LessThanSlashToken */); + node.tagName = parseJsxElementName(); + if (inExpressionContext) { + parseExpected(27 /* GreaterThanToken */); + } + else { + parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*advance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseTypeAssertion() { + var node = createNode(171 /* TypeAssertionExpression */); + parseExpected(25 /* LessThanToken */); + node.type = parseType(); + parseExpected(27 /* GreaterThanToken */); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseMemberExpressionRest(expression) { + while (true) { + var dotToken = parseOptionalToken(21 /* DotToken */); + if (dotToken) { + var propertyAccess = createNode(166 /* PropertyAccessExpression */, expression.pos); + propertyAccess.expression = expression; + propertyAccess.dotToken = dotToken; + propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + expression = finishNode(propertyAccess); + continue; + } + // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName + if (!inDecoratorContext() && parseOptional(19 /* OpenBracketToken */)) { + var indexedAccess = createNode(167 /* ElementAccessExpression */, expression.pos); + indexedAccess.expression = expression; + // It's not uncommon for a user to write: "new Type[]". + // Check for that common pattern and report a better error message. + if (token !== 20 /* CloseBracketToken */) { + indexedAccess.argumentExpression = allowInAnd(parseExpression); + if (indexedAccess.argumentExpression.kind === 9 /* StringLiteral */ || indexedAccess.argumentExpression.kind === 8 /* NumericLiteral */) { + var literal = indexedAccess.argumentExpression; + literal.text = internIdentifier(literal.text); + } + } + parseExpected(20 /* CloseBracketToken */); + expression = finishNode(indexedAccess); + continue; + } + if (token === 11 /* NoSubstitutionTemplateLiteral */ || token === 12 /* TemplateHead */) { + var tagExpression = createNode(170 /* TaggedTemplateExpression */, expression.pos); + tagExpression.tag = expression; + tagExpression.template = token === 11 /* NoSubstitutionTemplateLiteral */ + ? parseLiteralNode() + : parseTemplateExpression(); + expression = finishNode(tagExpression); + continue; + } + return expression; + } + } + function parseCallExpressionRest(expression) { + while (true) { + expression = parseMemberExpressionRest(expression); + if (token === 25 /* LessThanToken */) { + // See if this is the start of a generic invocation. If so, consume it and + // keep checking for postfix expressions. Otherwise, it's just a '<' that's + // part of an arithmetic expression. Break out so we consume it higher in the + // stack. + var typeArguments = tryParse(parseTypeArgumentsInExpression); + if (!typeArguments) { + return expression; + } + var callExpr = createNode(168 /* CallExpression */, expression.pos); + callExpr.expression = expression; + callExpr.typeArguments = typeArguments; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + else if (token === 17 /* OpenParenToken */) { + var callExpr = createNode(168 /* CallExpression */, expression.pos); + callExpr.expression = expression; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + return expression; + } + } + function parseArgumentList() { + parseExpected(17 /* OpenParenToken */); + var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); + parseExpected(18 /* CloseParenToken */); + return result; + } + function parseTypeArgumentsInExpression() { + if (!parseOptional(25 /* LessThanToken */)) { + return undefined; + } + var typeArguments = parseDelimitedList(18 /* TypeArguments */, parseType); + if (!parseExpected(27 /* GreaterThanToken */)) { + // If it doesn't have the closing > then it's definitely not an type argument list. + return undefined; + } + // If we have a '<', then only parse this as a arugment list if the type arguments + // are complete and we have an open paren. if we don't, rewind and return nothing. + return typeArguments && canFollowTypeArgumentsInExpression() + ? typeArguments + : undefined; + } + function canFollowTypeArgumentsInExpression() { + switch (token) { + case 17 /* OpenParenToken */: // foo( + // this case are the only case where this token can legally follow a type argument + // list. So we definitely want to treat this as a type arg list. + case 21 /* DotToken */: // foo. + case 18 /* CloseParenToken */: // foo) + case 20 /* CloseBracketToken */: // foo] + case 54 /* ColonToken */: // foo: + case 23 /* SemicolonToken */: // foo; + case 53 /* QuestionToken */: // foo? + case 30 /* EqualsEqualsToken */: // foo == + case 32 /* EqualsEqualsEqualsToken */: // foo === + case 31 /* ExclamationEqualsToken */: // foo != + case 33 /* ExclamationEqualsEqualsToken */: // foo !== + case 51 /* AmpersandAmpersandToken */: // foo && + case 52 /* BarBarToken */: // foo || + case 48 /* CaretToken */: // foo ^ + case 46 /* AmpersandToken */: // foo & + case 47 /* BarToken */: // foo | + case 16 /* CloseBraceToken */: // foo } + case 1 /* EndOfFileToken */: + // these cases can't legally follow a type arg list. However, they're not legal + // expressions either. The user is probably in the middle of a generic type. So + // treat it as such. + return true; + case 24 /* CommaToken */: // foo, + case 15 /* OpenBraceToken */: // foo { + // We don't want to treat these as type arguments. Otherwise we'll parse this + // as an invocation expression. Instead, we want to parse out the expression + // in isolation from the type arguments. + default: + // Anything else treat as an expression. + return false; + } + } + function parsePrimaryExpression() { + switch (token) { + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 11 /* NoSubstitutionTemplateLiteral */: + return parseLiteralNode(); + case 97 /* ThisKeyword */: + case 95 /* SuperKeyword */: + case 93 /* NullKeyword */: + case 99 /* TrueKeyword */: + case 84 /* FalseKeyword */: + return parseTokenNode(); + case 17 /* OpenParenToken */: + return parseParenthesizedExpression(); + case 19 /* OpenBracketToken */: + return parseArrayLiteralExpression(); + case 15 /* OpenBraceToken */: + return parseObjectLiteralExpression(); + case 118 /* AsyncKeyword */: + // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. + // If we encounter `async [no LineTerminator here] function` then this is an async + // function; otherwise, its an identifier. + if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { + break; + } + return parseFunctionExpression(); + case 73 /* ClassKeyword */: + return parseClassExpression(); + case 87 /* FunctionKeyword */: + return parseFunctionExpression(); + case 92 /* NewKeyword */: + return parseNewExpression(); + case 39 /* SlashToken */: + case 61 /* SlashEqualsToken */: + if (reScanSlashToken() === 10 /* RegularExpressionLiteral */) { + return parseLiteralNode(); + } + break; + case 12 /* TemplateHead */: + return parseTemplateExpression(); + } + return parseIdentifier(ts.Diagnostics.Expression_expected); + } + function parseParenthesizedExpression() { + var node = createNode(172 /* ParenthesizedExpression */); + parseExpected(17 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(18 /* CloseParenToken */); + return finishNode(node); + } + function parseSpreadElement() { + var node = createNode(185 /* SpreadElementExpression */); + parseExpected(22 /* DotDotDotToken */); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseArgumentOrArrayLiteralElement() { + return token === 22 /* DotDotDotToken */ ? parseSpreadElement() : + token === 24 /* CommaToken */ ? createNode(187 /* OmittedExpression */) : + parseAssignmentExpressionOrHigher(); + } + function parseArgumentExpression() { + return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); + } + function parseArrayLiteralExpression() { + var node = createNode(164 /* ArrayLiteralExpression */); + parseExpected(19 /* OpenBracketToken */); + if (scanner.hasPrecedingLineBreak()) + node.flags |= 2048 /* MultiLine */; + node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); + parseExpected(20 /* CloseBracketToken */); + return finishNode(node); + } + function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { + if (parseContextualModifier(123 /* GetKeyword */)) { + return parseAccessorDeclaration(145 /* GetAccessor */, fullStart, decorators, modifiers); + } + else if (parseContextualModifier(129 /* SetKeyword */)) { + return parseAccessorDeclaration(146 /* SetAccessor */, fullStart, decorators, modifiers); + } + return undefined; + } + function parseObjectLiteralElement() { + var fullStart = scanner.getStartPos(); + var decorators = parseDecorators(); + var modifiers = parseModifiers(); + var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); + if (accessor) { + return accessor; + } + var asteriskToken = parseOptionalToken(37 /* AsteriskToken */); + var tokenIsIdentifier = isIdentifier(); + var nameToken = token; + var propertyName = parsePropertyName(); + // Disallowing of optional property assignments happens in the grammar checker. + var questionToken = parseOptionalToken(53 /* QuestionToken */); + if (asteriskToken || token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { + return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); + } + // check if it is short-hand property assignment or normal property assignment + // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production + // CoverInitializedName[Yield] : + // IdentifierReference[?Yield] Initializer[In, ?Yield] + // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern + var isShorthandPropertyAssignment = tokenIsIdentifier && (token === 24 /* CommaToken */ || token === 16 /* CloseBraceToken */ || token === 56 /* EqualsToken */); + if (isShorthandPropertyAssignment) { + var shorthandDeclaration = createNode(246 /* ShorthandPropertyAssignment */, fullStart); + shorthandDeclaration.name = propertyName; + shorthandDeclaration.questionToken = questionToken; + var equalsToken = parseOptionalToken(56 /* EqualsToken */); + if (equalsToken) { + shorthandDeclaration.equalsToken = equalsToken; + shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); + } + return finishNode(shorthandDeclaration); + } + else { + var propertyAssignment = createNode(245 /* PropertyAssignment */, fullStart); + propertyAssignment.name = propertyName; + propertyAssignment.questionToken = questionToken; + parseExpected(54 /* ColonToken */); + propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); + return finishNode(propertyAssignment); + } + } + function parseObjectLiteralExpression() { + var node = createNode(165 /* ObjectLiteralExpression */); + parseExpected(15 /* OpenBraceToken */); + if (scanner.hasPrecedingLineBreak()) { + node.flags |= 2048 /* MultiLine */; + } + node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimeter*/ true); + parseExpected(16 /* CloseBraceToken */); + return finishNode(node); + } + function parseFunctionExpression() { + // GeneratorExpression: + // function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody } + // + // FunctionExpression: + // function BindingIdentifier[opt](FormalParameters){ FunctionBody } + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(false); + } + var node = createNode(173 /* FunctionExpression */); + setModifiers(node, parseModifiers()); + parseExpected(87 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); + var isGenerator = !!node.asteriskToken; + var isAsync = !!(node.flags & 512 /* Async */); + node.name = + isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : + isGenerator ? doInYieldContext(parseOptionalIdentifier) : + isAsync ? doInAwaitContext(parseOptionalIdentifier) : + parseOptionalIdentifier(); + fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); + node.body = parseFunctionBlock(/*allowYield*/ isGenerator, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); + if (saveDecoratorContext) { + setDecoratorContext(true); + } + return finishNode(node); + } + function parseOptionalIdentifier() { + return isIdentifier() ? parseIdentifier() : undefined; + } + function parseNewExpression() { + var node = createNode(169 /* NewExpression */); + parseExpected(92 /* NewKeyword */); + node.expression = parseMemberExpressionOrHigher(); + node.typeArguments = tryParse(parseTypeArgumentsInExpression); + if (node.typeArguments || token === 17 /* OpenParenToken */) { + node.arguments = parseArgumentList(); + } + return finishNode(node); + } + // STATEMENTS + function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { + var node = createNode(192 /* Block */); + if (parseExpected(15 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { + node.statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpected(16 /* CloseBraceToken */); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseFunctionBlock(allowYield, allowAwait, ignoreMissingOpenBrace, diagnosticMessage) { + var savedYieldContext = inYieldContext(); + setYieldContext(allowYield); + var savedAwaitContext = inAwaitContext(); + setAwaitContext(allowAwait); + // We may be in a [Decorator] context when parsing a function expression or + // arrow function. The body of the function is not in [Decorator] context. + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(false); + } + var block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); + if (saveDecoratorContext) { + setDecoratorContext(true); + } + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return block; + } + function parseEmptyStatement() { + var node = createNode(194 /* EmptyStatement */); + parseExpected(23 /* SemicolonToken */); + return finishNode(node); + } + function parseIfStatement() { + var node = createNode(196 /* IfStatement */); + parseExpected(88 /* IfKeyword */); + parseExpected(17 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(18 /* CloseParenToken */); + node.thenStatement = parseStatement(); + node.elseStatement = parseOptional(80 /* ElseKeyword */) ? parseStatement() : undefined; + return finishNode(node); + } + function parseDoStatement() { + var node = createNode(197 /* DoStatement */); + parseExpected(79 /* DoKeyword */); + node.statement = parseStatement(); + parseExpected(104 /* WhileKeyword */); + parseExpected(17 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(18 /* CloseParenToken */); + // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html + // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in + // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby + // do;while(0)x will have a semicolon inserted before x. + parseOptional(23 /* SemicolonToken */); + return finishNode(node); + } + function parseWhileStatement() { + var node = createNode(198 /* WhileStatement */); + parseExpected(104 /* WhileKeyword */); + parseExpected(17 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(18 /* CloseParenToken */); + node.statement = parseStatement(); + return finishNode(node); + } + function parseForOrForInOrForOfStatement() { + var pos = getNodePos(); + parseExpected(86 /* ForKeyword */); + parseExpected(17 /* OpenParenToken */); + var initializer = undefined; + if (token !== 23 /* SemicolonToken */) { + if (token === 102 /* VarKeyword */ || token === 108 /* LetKeyword */ || token === 74 /* ConstKeyword */) { + initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); + } + else { + initializer = disallowInAnd(parseExpression); + } + } + var forOrForInOrForOfStatement; + if (parseOptional(90 /* InKeyword */)) { + var forInStatement = createNode(200 /* ForInStatement */, pos); + forInStatement.initializer = initializer; + forInStatement.expression = allowInAnd(parseExpression); + parseExpected(18 /* CloseParenToken */); + forOrForInOrForOfStatement = forInStatement; + } + else if (parseOptional(134 /* OfKeyword */)) { + var forOfStatement = createNode(201 /* ForOfStatement */, pos); + forOfStatement.initializer = initializer; + forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); + parseExpected(18 /* CloseParenToken */); + forOrForInOrForOfStatement = forOfStatement; + } + else { + var forStatement = createNode(199 /* ForStatement */, pos); + forStatement.initializer = initializer; + parseExpected(23 /* SemicolonToken */); + if (token !== 23 /* SemicolonToken */ && token !== 18 /* CloseParenToken */) { + forStatement.condition = allowInAnd(parseExpression); + } + parseExpected(23 /* SemicolonToken */); + if (token !== 18 /* CloseParenToken */) { + forStatement.incrementor = allowInAnd(parseExpression); + } + parseExpected(18 /* CloseParenToken */); + forOrForInOrForOfStatement = forStatement; + } + forOrForInOrForOfStatement.statement = parseStatement(); + return finishNode(forOrForInOrForOfStatement); + } + function parseBreakOrContinueStatement(kind) { + var node = createNode(kind); + parseExpected(kind === 203 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */); + if (!canParseSemicolon()) { + node.label = parseIdentifier(); + } + parseSemicolon(); + return finishNode(node); + } + function parseReturnStatement() { + var node = createNode(204 /* ReturnStatement */); + parseExpected(94 /* ReturnKeyword */); + if (!canParseSemicolon()) { + node.expression = allowInAnd(parseExpression); + } + parseSemicolon(); + return finishNode(node); + } + function parseWithStatement() { + var node = createNode(205 /* WithStatement */); + parseExpected(105 /* WithKeyword */); + parseExpected(17 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(18 /* CloseParenToken */); + node.statement = parseStatement(); + return finishNode(node); + } + function parseCaseClause() { + var node = createNode(241 /* CaseClause */); + parseExpected(71 /* CaseKeyword */); + node.expression = allowInAnd(parseExpression); + parseExpected(54 /* ColonToken */); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); + return finishNode(node); + } + function parseDefaultClause() { + var node = createNode(242 /* DefaultClause */); + parseExpected(77 /* DefaultKeyword */); + parseExpected(54 /* ColonToken */); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); + return finishNode(node); + } + function parseCaseOrDefaultClause() { + return token === 71 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + } + function parseSwitchStatement() { + var node = createNode(206 /* SwitchStatement */); + parseExpected(96 /* SwitchKeyword */); + parseExpected(17 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(18 /* CloseParenToken */); + var caseBlock = createNode(220 /* CaseBlock */, scanner.getStartPos()); + parseExpected(15 /* OpenBraceToken */); + caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); + parseExpected(16 /* CloseBraceToken */); + node.caseBlock = finishNode(caseBlock); + return finishNode(node); + } + function parseThrowStatement() { + // ThrowStatement[Yield] : + // throw [no LineTerminator here]Expression[In, ?Yield]; + // Because of automatic semicolon insertion, we need to report error if this + // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' + // directly as that might consume an expression on the following line. + // We just return 'undefined' in that case. The actual error will be reported in the + // grammar walker. + var node = createNode(208 /* ThrowStatement */); + parseExpected(98 /* ThrowKeyword */); + node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); + parseSemicolon(); + return finishNode(node); + } + // TODO: Review for error recovery + function parseTryStatement() { + var node = createNode(209 /* TryStatement */); + parseExpected(100 /* TryKeyword */); + node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); + node.catchClause = token === 72 /* CatchKeyword */ ? parseCatchClause() : undefined; + // If we don't have a catch clause, then we must have a finally clause. Try to parse + // one out no matter what. + if (!node.catchClause || token === 85 /* FinallyKeyword */) { + parseExpected(85 /* FinallyKeyword */); + node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); + } + return finishNode(node); + } + function parseCatchClause() { + var result = createNode(244 /* CatchClause */); + parseExpected(72 /* CatchKeyword */); + if (parseExpected(17 /* OpenParenToken */)) { + result.variableDeclaration = parseVariableDeclaration(); + } + parseExpected(18 /* CloseParenToken */); + result.block = parseBlock(/*ignoreMissingOpenBrace*/ false); + return finishNode(result); + } + function parseDebuggerStatement() { + var node = createNode(210 /* DebuggerStatement */); + parseExpected(76 /* DebuggerKeyword */); + parseSemicolon(); + return finishNode(node); + } + function parseExpressionOrLabeledStatement() { + // Avoiding having to do the lookahead for a labeled statement by just trying to parse + // out an expression, seeing if it is identifier and then seeing if it is followed by + // a colon. + var fullStart = scanner.getStartPos(); + var expression = allowInAnd(parseExpression); + if (expression.kind === 69 /* Identifier */ && parseOptional(54 /* ColonToken */)) { + var labeledStatement = createNode(207 /* LabeledStatement */, fullStart); + labeledStatement.label = expression; + labeledStatement.statement = parseStatement(); + return finishNode(labeledStatement); + } + else { + var expressionStatement = createNode(195 /* ExpressionStatement */, fullStart); + expressionStatement.expression = expression; + parseSemicolon(); + return finishNode(expressionStatement); + } + } + function nextTokenIsIdentifierOrKeywordOnSameLine() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token) && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsFunctionKeywordOnSameLine() { + nextToken(); + return token === 87 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { + nextToken(); + return (ts.tokenIsIdentifierOrKeyword(token) || token === 8 /* NumericLiteral */) && !scanner.hasPrecedingLineBreak(); + } + function isDeclaration() { + while (true) { + switch (token) { + case 102 /* VarKeyword */: + case 108 /* LetKeyword */: + case 74 /* ConstKeyword */: + case 87 /* FunctionKeyword */: + case 73 /* ClassKeyword */: + case 81 /* EnumKeyword */: + return true; + // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; + // however, an identifier cannot be followed by another identifier on the same line. This is what we + // count on to parse out the respective declarations. For instance, we exploit this to say that + // + // namespace n + // + // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees + // + // namespace + // n + // + // as the identifier 'namespace' on one line followed by the identifier 'n' on another. + // We need to look one token ahead to see if it permissible to try parsing a declaration. + // + // *Note*: 'interface' is actually a strict mode reserved word. So while + // + // "use strict" + // interface + // I {} + // + // could be legal, it would add complexity for very little gain. + case 107 /* InterfaceKeyword */: + case 132 /* TypeKeyword */: + return nextTokenIsIdentifierOnSameLine(); + case 125 /* ModuleKeyword */: + case 126 /* NamespaceKeyword */: + return nextTokenIsIdentifierOrStringLiteralOnSameLine(); + case 115 /* AbstractKeyword */: + case 118 /* AsyncKeyword */: + case 122 /* DeclareKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + case 112 /* PublicKeyword */: + nextToken(); + // ASI takes effect for this modifier. + if (scanner.hasPrecedingLineBreak()) { + return false; + } + continue; + case 89 /* ImportKeyword */: + nextToken(); + return token === 9 /* StringLiteral */ || token === 37 /* AsteriskToken */ || + token === 15 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token); + case 82 /* ExportKeyword */: + nextToken(); + if (token === 56 /* EqualsToken */ || token === 37 /* AsteriskToken */ || + token === 15 /* OpenBraceToken */ || token === 77 /* DefaultKeyword */) { + return true; + } + continue; + case 113 /* StaticKeyword */: + nextToken(); + continue; + default: + return false; + } + } + } + function isStartOfDeclaration() { + return lookAhead(isDeclaration); + } + function isStartOfStatement() { + switch (token) { + case 55 /* AtToken */: + case 23 /* SemicolonToken */: + case 15 /* OpenBraceToken */: + case 102 /* VarKeyword */: + case 108 /* LetKeyword */: + case 87 /* FunctionKeyword */: + case 73 /* ClassKeyword */: + case 81 /* EnumKeyword */: + case 88 /* IfKeyword */: + case 79 /* DoKeyword */: + case 104 /* WhileKeyword */: + case 86 /* ForKeyword */: + case 75 /* ContinueKeyword */: + case 70 /* BreakKeyword */: + case 94 /* ReturnKeyword */: + case 105 /* WithKeyword */: + case 96 /* SwitchKeyword */: + case 98 /* ThrowKeyword */: + case 100 /* TryKeyword */: + case 76 /* DebuggerKeyword */: + // 'catch' and 'finally' do not actually indicate that the code is part of a statement, + // however, we say they are here so that we may gracefully parse them and error later. + case 72 /* CatchKeyword */: + case 85 /* FinallyKeyword */: + return true; + case 74 /* ConstKeyword */: + case 82 /* ExportKeyword */: + case 89 /* ImportKeyword */: + return isStartOfDeclaration(); + case 118 /* AsyncKeyword */: + case 122 /* DeclareKeyword */: + case 107 /* InterfaceKeyword */: + case 125 /* ModuleKeyword */: + case 126 /* NamespaceKeyword */: + case 132 /* TypeKeyword */: + // When these don't start a declaration, they're an identifier in an expression statement + return true; + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + case 113 /* StaticKeyword */: + // When these don't start a declaration, they may be the start of a class member if an identifier + // immediately follows. Otherwise they're an identifier in an expression statement. + return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + default: + return isStartOfExpression(); + } + } + function nextTokenIsIdentifierOrStartOfDestructuring() { + nextToken(); + return isIdentifier() || token === 15 /* OpenBraceToken */ || token === 19 /* OpenBracketToken */; + } + function isLetDeclaration() { + // In ES6 'let' always starts a lexical declaration if followed by an identifier or { + // or [. + return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); + } + function parseStatement() { + switch (token) { + case 23 /* SemicolonToken */: + return parseEmptyStatement(); + case 15 /* OpenBraceToken */: + return parseBlock(/*ignoreMissingOpenBrace*/ false); + case 102 /* VarKeyword */: + return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + case 108 /* LetKeyword */: + if (isLetDeclaration()) { + return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + } + break; + case 87 /* FunctionKeyword */: + return parseFunctionDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + case 73 /* ClassKeyword */: + return parseClassDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + case 88 /* IfKeyword */: + return parseIfStatement(); + case 79 /* DoKeyword */: + return parseDoStatement(); + case 104 /* WhileKeyword */: + return parseWhileStatement(); + case 86 /* ForKeyword */: + return parseForOrForInOrForOfStatement(); + case 75 /* ContinueKeyword */: + return parseBreakOrContinueStatement(202 /* ContinueStatement */); + case 70 /* BreakKeyword */: + return parseBreakOrContinueStatement(203 /* BreakStatement */); + case 94 /* ReturnKeyword */: + return parseReturnStatement(); + case 105 /* WithKeyword */: + return parseWithStatement(); + case 96 /* SwitchKeyword */: + return parseSwitchStatement(); + case 98 /* ThrowKeyword */: + return parseThrowStatement(); + case 100 /* TryKeyword */: + // Include 'catch' and 'finally' for error recovery. + case 72 /* CatchKeyword */: + case 85 /* FinallyKeyword */: + return parseTryStatement(); + case 76 /* DebuggerKeyword */: + return parseDebuggerStatement(); + case 55 /* AtToken */: + return parseDeclaration(); + case 118 /* AsyncKeyword */: + case 107 /* InterfaceKeyword */: + case 132 /* TypeKeyword */: + case 125 /* ModuleKeyword */: + case 126 /* NamespaceKeyword */: + case 122 /* DeclareKeyword */: + case 74 /* ConstKeyword */: + case 81 /* EnumKeyword */: + case 82 /* ExportKeyword */: + case 89 /* ImportKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + case 112 /* PublicKeyword */: + case 115 /* AbstractKeyword */: + case 113 /* StaticKeyword */: + if (isStartOfDeclaration()) { + return parseDeclaration(); + } + break; + } + return parseExpressionOrLabeledStatement(); + } + function parseDeclaration() { + var fullStart = getNodePos(); + var decorators = parseDecorators(); + var modifiers = parseModifiers(); + switch (token) { + case 102 /* VarKeyword */: + case 108 /* LetKeyword */: + case 74 /* ConstKeyword */: + return parseVariableStatement(fullStart, decorators, modifiers); + case 87 /* FunctionKeyword */: + return parseFunctionDeclaration(fullStart, decorators, modifiers); + case 73 /* ClassKeyword */: + return parseClassDeclaration(fullStart, decorators, modifiers); + case 107 /* InterfaceKeyword */: + return parseInterfaceDeclaration(fullStart, decorators, modifiers); + case 132 /* TypeKeyword */: + return parseTypeAliasDeclaration(fullStart, decorators, modifiers); + case 81 /* EnumKeyword */: + return parseEnumDeclaration(fullStart, decorators, modifiers); + case 125 /* ModuleKeyword */: + case 126 /* NamespaceKeyword */: + return parseModuleDeclaration(fullStart, decorators, modifiers); + case 89 /* ImportKeyword */: + return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + case 82 /* ExportKeyword */: + nextToken(); + return token === 77 /* DefaultKeyword */ || token === 56 /* EqualsToken */ ? + parseExportAssignment(fullStart, decorators, modifiers) : + parseExportDeclaration(fullStart, decorators, modifiers); + default: + if (decorators || modifiers) { + // We reached this point because we encountered decorators and/or modifiers and assumed a declaration + // would follow. For recovery and error reporting purposes, return an incomplete declaration. + var node = createMissingNode(231 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + node.pos = fullStart; + node.decorators = decorators; + setModifiers(node, modifiers); + return finishNode(node); + } + } + } + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token === 9 /* StringLiteral */); + } + function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { + if (token !== 15 /* OpenBraceToken */ && canParseSemicolon()) { + parseSemicolon(); + return; + } + return parseFunctionBlock(isGenerator, isAsync, /*ignoreMissingOpenBrace*/ false, diagnosticMessage); + } + // DECLARATIONS + function parseArrayBindingElement() { + if (token === 24 /* CommaToken */) { + return createNode(187 /* OmittedExpression */); + } + var node = createNode(163 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(22 /* DotDotDotToken */); + node.name = parseIdentifierOrPattern(); + node.initializer = parseBindingElementInitializer(/*inParameter*/ false); + return finishNode(node); + } + function parseObjectBindingElement() { + var node = createNode(163 /* BindingElement */); + // TODO(andersh): Handle computed properties + var tokenIsIdentifier = isIdentifier(); + var propertyName = parsePropertyName(); + if (tokenIsIdentifier && token !== 54 /* ColonToken */) { + node.name = propertyName; + } + else { + parseExpected(54 /* ColonToken */); + node.propertyName = propertyName; + node.name = parseIdentifierOrPattern(); + } + node.initializer = parseBindingElementInitializer(/*inParameter*/ false); + return finishNode(node); + } + function parseObjectBindingPattern() { + var node = createNode(161 /* ObjectBindingPattern */); + parseExpected(15 /* OpenBraceToken */); + node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); + parseExpected(16 /* CloseBraceToken */); + return finishNode(node); + } + function parseArrayBindingPattern() { + var node = createNode(162 /* ArrayBindingPattern */); + parseExpected(19 /* OpenBracketToken */); + node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); + parseExpected(20 /* CloseBracketToken */); + return finishNode(node); + } + function isIdentifierOrPattern() { + return token === 15 /* OpenBraceToken */ || token === 19 /* OpenBracketToken */ || isIdentifier(); + } + function parseIdentifierOrPattern() { + if (token === 19 /* OpenBracketToken */) { + return parseArrayBindingPattern(); + } + if (token === 15 /* OpenBraceToken */) { + return parseObjectBindingPattern(); + } + return parseIdentifier(); + } + function parseVariableDeclaration() { + var node = createNode(211 /* VariableDeclaration */); + node.name = parseIdentifierOrPattern(); + node.type = parseTypeAnnotation(); + if (!isInOrOfKeyword(token)) { + node.initializer = parseInitializer(/*inParameter*/ false); + } + return finishNode(node); + } + function parseVariableDeclarationList(inForStatementInitializer) { + var node = createNode(212 /* VariableDeclarationList */); + switch (token) { + case 102 /* VarKeyword */: + break; + case 108 /* LetKeyword */: + node.flags |= 16384 /* Let */; + break; + case 74 /* ConstKeyword */: + node.flags |= 32768 /* Const */; + break; + default: + ts.Debug.fail(); + } + nextToken(); + // The user may have written the following: + // + // for (let of X) { } + // + // In this case, we want to parse an empty declaration list, and then parse 'of' + // as a keyword. The reason this is not automatic is that 'of' is a valid identifier. + // So we need to look ahead to determine if 'of' should be treated as a keyword in + // this context. + // The checker will then give an error that there is an empty declaration list. + if (token === 134 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + node.declarations = createMissingList(); + } + else { + var savedDisallowIn = inDisallowInContext(); + setDisallowInContext(inForStatementInitializer); + node.declarations = parseDelimitedList(8 /* VariableDeclarations */, parseVariableDeclaration); + setDisallowInContext(savedDisallowIn); + } + return finishNode(node); + } + function canFollowContextualOfKeyword() { + return nextTokenIsIdentifier() && nextToken() === 18 /* CloseParenToken */; + } + function parseVariableStatement(fullStart, decorators, modifiers) { + var node = createNode(193 /* VariableStatement */, fullStart); + node.decorators = decorators; + setModifiers(node, modifiers); + node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); + parseSemicolon(); + return finishNode(node); + } + function parseFunctionDeclaration(fullStart, decorators, modifiers) { + var node = createNode(213 /* FunctionDeclaration */, fullStart); + node.decorators = decorators; + setModifiers(node, modifiers); + parseExpected(87 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); + node.name = node.flags & 1024 /* Default */ ? parseOptionalIdentifier() : parseIdentifier(); + var isGenerator = !!node.asteriskToken; + var isAsync = !!(node.flags & 512 /* Async */); + fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); + return finishNode(node); + } + function parseConstructorDeclaration(pos, decorators, modifiers) { + var node = createNode(144 /* Constructor */, pos); + node.decorators = decorators; + setModifiers(node, modifiers); + parseExpected(121 /* ConstructorKeyword */); + fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); + node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false, ts.Diagnostics.or_expected); + return finishNode(node); + } + function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { + var method = createNode(143 /* MethodDeclaration */, fullStart); + method.decorators = decorators; + setModifiers(method, modifiers); + method.asteriskToken = asteriskToken; + method.name = name; + method.questionToken = questionToken; + var isGenerator = !!asteriskToken; + var isAsync = !!(method.flags & 512 /* Async */); + fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, method); + method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); + return finishNode(method); + } + function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { + var property = createNode(141 /* PropertyDeclaration */, fullStart); + property.decorators = decorators; + setModifiers(property, modifiers); + property.name = name; + property.questionToken = questionToken; + property.type = parseTypeAnnotation(); + // For instance properties specifically, since they are evaluated inside the constructor, + // we do *not * want to parse yield expressions, so we specifically turn the yield context + // off. The grammar would look something like this: + // + // MemberVariableDeclaration[Yield]: + // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initialiser_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initialiser_opt[In, ?Yield]; + // + // The checker may still error in the static case to explicitly disallow the yield expression. + property.initializer = modifiers && modifiers.flags & 128 /* Static */ + ? allowInAnd(parseNonParameterInitializer) + : doOutsideOfContext(2 /* Yield */ | 1 /* DisallowIn */, parseNonParameterInitializer); + parseSemicolon(); + return finishNode(property); + } + function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { + var asteriskToken = parseOptionalToken(37 /* AsteriskToken */); + var name = parsePropertyName(); + // Note: this is not legal as per the grammar. But we allow it in the parser and + // report an error in the grammar checker. + var questionToken = parseOptionalToken(53 /* QuestionToken */); + if (asteriskToken || token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { + return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); + } + else { + return parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken); + } + } + function parseNonParameterInitializer() { + return parseInitializer(/*inParameter*/ false); + } + function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { + var node = createNode(kind, fullStart); + node.decorators = decorators; + setModifiers(node, modifiers); + node.name = parsePropertyName(); + fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); + node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false); + return finishNode(node); + } + function isClassMemberModifier(idToken) { + switch (idToken) { + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + case 113 /* StaticKeyword */: + return true; + default: + return false; + } + } + function isClassMemberStart() { + var idToken; + if (token === 55 /* AtToken */) { + return true; + } + // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. + while (ts.isModifier(token)) { + idToken = token; + // If the idToken is a class modifier (protected, private, public, and static), it is + // certain that we are starting to parse class member. This allows better error recovery + // Example: + // public foo() ... // true + // public @dec blah ... // true; we will then report an error later + // export public ... // true; we will then report an error later + if (isClassMemberModifier(idToken)) { + return true; + } + nextToken(); + } + if (token === 37 /* AsteriskToken */) { + return true; + } + // Try to get the first property-like token following all modifiers. + // This can either be an identifier or the 'get' or 'set' keywords. + if (isLiteralPropertyName()) { + idToken = token; + nextToken(); + } + // Index signatures and computed properties are class members; we can parse. + if (token === 19 /* OpenBracketToken */) { + return true; + } + // If we were able to get any potential identifier... + if (idToken !== undefined) { + // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. + if (!ts.isKeyword(idToken) || idToken === 129 /* SetKeyword */ || idToken === 123 /* GetKeyword */) { + return true; + } + // If it *is* a keyword, but not an accessor, check a little farther along + // to see if it should actually be parsed as a class member. + switch (token) { + case 17 /* OpenParenToken */: // Method declaration + case 25 /* LessThanToken */: // Generic Method declaration + case 54 /* ColonToken */: // Type Annotation for declaration + case 56 /* EqualsToken */: // Initializer for declaration + case 53 /* QuestionToken */: + return true; + default: + // Covers + // - Semicolons (declaration termination) + // - Closing braces (end-of-class, must be declaration) + // - End-of-files (not valid, but permitted so that it gets caught later on) + // - Line-breaks (enabling *automatic semicolon insertion*) + return canParseSemicolon(); + } + } + return false; + } + function parseDecorators() { + var decorators; + while (true) { + var decoratorStart = getNodePos(); + if (!parseOptional(55 /* AtToken */)) { + break; + } + if (!decorators) { + decorators = []; + decorators.pos = scanner.getStartPos(); + } + var decorator = createNode(139 /* Decorator */, decoratorStart); + decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); + decorators.push(finishNode(decorator)); + } + if (decorators) { + decorators.end = getNodeEnd(); + } + return decorators; + } + function parseModifiers() { + var flags = 0; + var modifiers; + while (true) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token; + if (!parseAnyContextualModifier()) { + break; + } + if (!modifiers) { + modifiers = []; + modifiers.pos = modifierStart; + } + flags |= ts.modifierToFlag(modifierKind); + modifiers.push(finishNode(createNode(modifierKind, modifierStart))); + } + if (modifiers) { + modifiers.flags = flags; + modifiers.end = scanner.getStartPos(); + } + return modifiers; + } + function parseModifiersForArrowFunction() { + var flags = 0; + var modifiers; + if (token === 118 /* AsyncKeyword */) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token; + nextToken(); + modifiers = []; + modifiers.pos = modifierStart; + flags |= ts.modifierToFlag(modifierKind); + modifiers.push(finishNode(createNode(modifierKind, modifierStart))); + modifiers.flags = flags; + modifiers.end = scanner.getStartPos(); + } + return modifiers; + } + function parseClassElement() { + if (token === 23 /* SemicolonToken */) { + var result = createNode(191 /* SemicolonClassElement */); + nextToken(); + return finishNode(result); + } + var fullStart = getNodePos(); + var decorators = parseDecorators(); + var modifiers = parseModifiers(); + var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); + if (accessor) { + return accessor; + } + if (token === 121 /* ConstructorKeyword */) { + return parseConstructorDeclaration(fullStart, decorators, modifiers); + } + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); + } + // It is very important that we check this *after* checking indexers because + // the [ token can start an index signature or a computed property name + if (ts.tokenIsIdentifierOrKeyword(token) || + token === 9 /* StringLiteral */ || + token === 8 /* NumericLiteral */ || + token === 37 /* AsteriskToken */ || + token === 19 /* OpenBracketToken */) { + return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); + } + if (decorators || modifiers) { + // treat this as a property declaration with a missing name. + var name_7 = createMissingNode(69 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_7, /*questionToken*/ undefined); + } + // 'isClassMemberStart' should have hinted not to attempt parsing. + ts.Debug.fail("Should not have attempted to parse class member declaration."); + } + function parseClassExpression() { + return parseClassDeclarationOrExpression( + /*fullStart*/ scanner.getStartPos(), + /*decorators*/ undefined, + /*modifiers*/ undefined, 186 /* ClassExpression */); + } + function parseClassDeclaration(fullStart, decorators, modifiers) { + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 214 /* ClassDeclaration */); + } + function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { + var node = createNode(kind, fullStart); + node.decorators = decorators; + setModifiers(node, modifiers); + parseExpected(73 /* ClassKeyword */); + node.name = parseNameOfClassDeclarationOrExpression(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(/*isClassHeritageClause*/ true); + if (parseExpected(15 /* OpenBraceToken */)) { + // ClassTail[Yield,Await] : (Modified) See 14.5 + // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } + node.members = parseClassMembers(); + parseExpected(16 /* CloseBraceToken */); + } + else { + node.members = createMissingList(); + } + return finishNode(node); + } + function parseNameOfClassDeclarationOrExpression() { + // implements is a future reserved word so + // 'class implements' might mean either + // - class expression with omitted name, 'implements' starts heritage clause + // - class with name 'implements' + // 'isImplementsClause' helps to disambiguate between these two cases + return isIdentifier() && !isImplementsClause() + ? parseIdentifier() + : undefined; + } + function isImplementsClause() { + return token === 106 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + } + function parseHeritageClauses(isClassHeritageClause) { + // ClassTail[Yield,Await] : (Modified) See 14.5 + // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } + if (isHeritageClause()) { + return parseList(20 /* HeritageClauses */, parseHeritageClause); + } + return undefined; + } + function parseHeritageClausesWorker() { + return parseList(20 /* HeritageClauses */, parseHeritageClause); + } + function parseHeritageClause() { + if (token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */) { + var node = createNode(243 /* HeritageClause */); + node.token = token; + nextToken(); + node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); + return finishNode(node); + } + return undefined; + } + function parseExpressionWithTypeArguments() { + var node = createNode(188 /* ExpressionWithTypeArguments */); + node.expression = parseLeftHandSideExpressionOrHigher(); + if (token === 25 /* LessThanToken */) { + node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); + } + return finishNode(node); + } + function isHeritageClause() { + return token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */; + } + function parseClassMembers() { + return parseList(5 /* ClassMembers */, parseClassElement); + } + function parseInterfaceDeclaration(fullStart, decorators, modifiers) { + var node = createNode(215 /* InterfaceDeclaration */, fullStart); + node.decorators = decorators; + setModifiers(node, modifiers); + parseExpected(107 /* InterfaceKeyword */); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(/*isClassHeritageClause*/ false); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { + var node = createNode(216 /* TypeAliasDeclaration */, fullStart); + node.decorators = decorators; + setModifiers(node, modifiers); + parseExpected(132 /* TypeKeyword */); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + parseExpected(56 /* EqualsToken */); + node.type = parseType(); + parseSemicolon(); + return finishNode(node); + } + // In an ambient declaration, the grammar only allows integer literals as initializers. + // In a non-ambient declaration, the grammar allows uninitialized members only in a + // ConstantEnumMemberSection, which starts at the beginning of an enum declaration + // or any time an integer literal initializer is encountered. + function parseEnumMember() { + var node = createNode(247 /* EnumMember */, scanner.getStartPos()); + node.name = parsePropertyName(); + node.initializer = allowInAnd(parseNonParameterInitializer); + return finishNode(node); + } + function parseEnumDeclaration(fullStart, decorators, modifiers) { + var node = createNode(217 /* EnumDeclaration */, fullStart); + node.decorators = decorators; + setModifiers(node, modifiers); + parseExpected(81 /* EnumKeyword */); + node.name = parseIdentifier(); + if (parseExpected(15 /* OpenBraceToken */)) { + node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); + parseExpected(16 /* CloseBraceToken */); + } + else { + node.members = createMissingList(); + } + return finishNode(node); + } + function parseModuleBlock() { + var node = createNode(219 /* ModuleBlock */, scanner.getStartPos()); + if (parseExpected(15 /* OpenBraceToken */)) { + node.statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpected(16 /* CloseBraceToken */); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { + var node = createNode(218 /* ModuleDeclaration */, fullStart); + // If we are parsing a dotted namespace name, we want to + // propagate the 'Namespace' flag across the names if set. + var namespaceFlag = flags & 131072 /* Namespace */; + node.decorators = decorators; + setModifiers(node, modifiers); + node.flags |= flags; + node.name = parseIdentifier(); + node.body = parseOptional(21 /* DotToken */) + ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 1 /* Export */ | namespaceFlag) + : parseModuleBlock(); + return finishNode(node); + } + function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { + var node = createNode(218 /* ModuleDeclaration */, fullStart); + node.decorators = decorators; + setModifiers(node, modifiers); + node.name = parseLiteralNode(/*internName*/ true); + node.body = parseModuleBlock(); + return finishNode(node); + } + function parseModuleDeclaration(fullStart, decorators, modifiers) { + var flags = modifiers ? modifiers.flags : 0; + if (parseOptional(126 /* NamespaceKeyword */)) { + flags |= 131072 /* Namespace */; + } + else { + parseExpected(125 /* ModuleKeyword */); + if (token === 9 /* StringLiteral */) { + return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + } + } + return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); + } + function isExternalModuleReference() { + return token === 127 /* RequireKeyword */ && + lookAhead(nextTokenIsOpenParen); + } + function nextTokenIsOpenParen() { + return nextToken() === 17 /* OpenParenToken */; + } + function nextTokenIsSlash() { + return nextToken() === 39 /* SlashToken */; + } + function nextTokenIsCommaOrFromKeyword() { + nextToken(); + return token === 24 /* CommaToken */ || + token === 133 /* FromKeyword */; + } + function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { + parseExpected(89 /* ImportKeyword */); + var afterImportPos = scanner.getStartPos(); + var identifier; + if (isIdentifier()) { + identifier = parseIdentifier(); + if (token !== 24 /* CommaToken */ && token !== 133 /* FromKeyword */) { + // ImportEquals declaration of type: + // import x = require("mod"); or + // import x = M.x; + var importEqualsDeclaration = createNode(221 /* ImportEqualsDeclaration */, fullStart); + importEqualsDeclaration.decorators = decorators; + setModifiers(importEqualsDeclaration, modifiers); + importEqualsDeclaration.name = identifier; + parseExpected(56 /* EqualsToken */); + importEqualsDeclaration.moduleReference = parseModuleReference(); + parseSemicolon(); + return finishNode(importEqualsDeclaration); + } + } + // Import statement + var importDeclaration = createNode(222 /* ImportDeclaration */, fullStart); + importDeclaration.decorators = decorators; + setModifiers(importDeclaration, modifiers); + // ImportDeclaration: + // import ImportClause from ModuleSpecifier ; + // import ModuleSpecifier; + if (identifier || + token === 37 /* AsteriskToken */ || + token === 15 /* OpenBraceToken */) { + importDeclaration.importClause = parseImportClause(identifier, afterImportPos); + parseExpected(133 /* FromKeyword */); + } + importDeclaration.moduleSpecifier = parseModuleSpecifier(); + parseSemicolon(); + return finishNode(importDeclaration); + } + function parseImportClause(identifier, fullStart) { + // ImportClause: + // ImportedDefaultBinding + // NameSpaceImport + // NamedImports + // ImportedDefaultBinding, NameSpaceImport + // ImportedDefaultBinding, NamedImports + var importClause = createNode(223 /* ImportClause */, fullStart); + if (identifier) { + // ImportedDefaultBinding: + // ImportedBinding + importClause.name = identifier; + } + // If there was no default import or if there is comma token after default import + // parse namespace or named imports + if (!importClause.name || + parseOptional(24 /* CommaToken */)) { + importClause.namedBindings = token === 37 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(225 /* NamedImports */); + } + return finishNode(importClause); + } + function parseModuleReference() { + return isExternalModuleReference() + ? parseExternalModuleReference() + : parseEntityName(/*allowReservedWords*/ false); + } + function parseExternalModuleReference() { + var node = createNode(232 /* ExternalModuleReference */); + parseExpected(127 /* RequireKeyword */); + parseExpected(17 /* OpenParenToken */); + node.expression = parseModuleSpecifier(); + parseExpected(18 /* CloseParenToken */); + return finishNode(node); + } + function parseModuleSpecifier() { + // We allow arbitrary expressions here, even though the grammar only allows string + // literals. We check to ensure that it is only a string literal later in the grammar + // walker. + var result = parseExpression(); + // Ensure the string being required is in our 'identifier' table. This will ensure + // that features like 'find refs' will look inside this file when search for its name. + if (result.kind === 9 /* StringLiteral */) { + internIdentifier(result.text); + } + return result; + } + function parseNamespaceImport() { + // NameSpaceImport: + // * as ImportedBinding + var namespaceImport = createNode(224 /* NamespaceImport */); + parseExpected(37 /* AsteriskToken */); + parseExpected(116 /* AsKeyword */); + namespaceImport.name = parseIdentifier(); + return finishNode(namespaceImport); + } + function parseNamedImportsOrExports(kind) { + var node = createNode(kind); + // NamedImports: + // { } + // { ImportsList } + // { ImportsList, } + // ImportsList: + // ImportSpecifier + // ImportsList, ImportSpecifier + node.elements = parseBracketedList(21 /* ImportOrExportSpecifiers */, kind === 225 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 15 /* OpenBraceToken */, 16 /* CloseBraceToken */); + return finishNode(node); + } + function parseExportSpecifier() { + return parseImportOrExportSpecifier(230 /* ExportSpecifier */); + } + function parseImportSpecifier() { + return parseImportOrExportSpecifier(226 /* ImportSpecifier */); + } + function parseImportOrExportSpecifier(kind) { + var node = createNode(kind); + // ImportSpecifier: + // BindingIdentifier + // IdentifierName as BindingIdentifier + // ExportSpecififer: + // IdentifierName + // IdentifierName as IdentifierName + var checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); + var checkIdentifierStart = scanner.getTokenPos(); + var checkIdentifierEnd = scanner.getTextPos(); + var identifierName = parseIdentifierName(); + if (token === 116 /* AsKeyword */) { + node.propertyName = identifierName; + parseExpected(116 /* AsKeyword */); + checkIdentifierIsKeyword = ts.isKeyword(token) && !isIdentifier(); + checkIdentifierStart = scanner.getTokenPos(); + checkIdentifierEnd = scanner.getTextPos(); + node.name = parseIdentifierName(); + } + else { + node.name = identifierName; + } + if (kind === 226 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + // Report error identifier expected + parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); + } + return finishNode(node); + } + function parseExportDeclaration(fullStart, decorators, modifiers) { + var node = createNode(228 /* ExportDeclaration */, fullStart); + node.decorators = decorators; + setModifiers(node, modifiers); + if (parseOptional(37 /* AsteriskToken */)) { + parseExpected(133 /* FromKeyword */); + node.moduleSpecifier = parseModuleSpecifier(); + } + else { + node.exportClause = parseNamedImportsOrExports(229 /* NamedExports */); + // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, + // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) + // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. + if (token === 133 /* FromKeyword */ || (token === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(133 /* FromKeyword */); + node.moduleSpecifier = parseModuleSpecifier(); + } + } + parseSemicolon(); + return finishNode(node); + } + function parseExportAssignment(fullStart, decorators, modifiers) { + var node = createNode(227 /* ExportAssignment */, fullStart); + node.decorators = decorators; + setModifiers(node, modifiers); + if (parseOptional(56 /* EqualsToken */)) { + node.isExportEquals = true; + } + else { + parseExpected(77 /* DefaultKeyword */); + } + node.expression = parseAssignmentExpressionOrHigher(); + parseSemicolon(); + return finishNode(node); + } + function processReferenceComments(sourceFile) { + var triviaScanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); + var referencedFiles = []; + var amdDependencies = []; + var amdModuleName; + // Keep scanning all the leading trivia in the file until we get to something that + // isn't trivia. Any single line comment will be analyzed to see if it is a + // reference comment. + while (true) { + var kind = triviaScanner.scan(); + if (kind === 5 /* WhitespaceTrivia */ || kind === 4 /* NewLineTrivia */ || kind === 3 /* MultiLineCommentTrivia */) { + continue; + } + if (kind !== 2 /* SingleLineCommentTrivia */) { + break; + } + var range = { pos: triviaScanner.getTokenPos(), end: triviaScanner.getTextPos(), kind: triviaScanner.getToken() }; + var comment = sourceText.substring(range.pos, range.end); + var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range); + if (referencePathMatchResult) { + var fileReference = referencePathMatchResult.fileReference; + sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; + var diagnosticMessage = referencePathMatchResult.diagnosticMessage; + if (fileReference) { + referencedFiles.push(fileReference); + } + if (diagnosticMessage) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); + } + } + else { + var amdModuleNameRegEx = /^\/\/\/\s*".length; + return parseErrorAtPosition(start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); + } + } + function parseQualifiedName(left) { + var result = createNode(135 /* QualifiedName */, left.pos); + result.left = left; + result.right = parseIdentifierName(); + return finishNode(result); + } + function parseJSDocRecordType() { + var result = createNode(257 /* JSDocRecordType */); + nextToken(); + result.members = parseDelimitedList(24 /* JSDocRecordMembers */, parseJSDocRecordMember); + checkForTrailingComma(result.members); + parseExpected(16 /* CloseBraceToken */); + return finishNode(result); + } + function parseJSDocRecordMember() { + var result = createNode(258 /* JSDocRecordMember */); + result.name = parseSimplePropertyName(); + if (token === 54 /* ColonToken */) { + nextToken(); + result.type = parseJSDocType(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(256 /* JSDocNonNullableType */); + nextToken(); + result.type = parseJSDocType(); + return finishNode(result); + } + function parseJSDocTupleType() { + var result = createNode(254 /* JSDocTupleType */); + nextToken(); + result.types = parseDelimitedList(25 /* JSDocTupleTypes */, parseJSDocType); + checkForTrailingComma(result.types); + parseExpected(20 /* CloseBracketToken */); + return finishNode(result); + } + function checkForTrailingComma(list) { + if (parseDiagnostics.length === 0 && list.hasTrailingComma) { + var start = list.end - ",".length; + parseErrorAtPosition(start, ",".length, ts.Diagnostics.Trailing_comma_not_allowed); + } + } + function parseJSDocUnionType() { + var result = createNode(253 /* JSDocUnionType */); + nextToken(); + result.types = parseJSDocTypeList(parseJSDocType()); + parseExpected(18 /* CloseParenToken */); + return finishNode(result); + } + function parseJSDocTypeList(firstType) { + ts.Debug.assert(!!firstType); + var types = []; + types.pos = firstType.pos; + types.push(firstType); + while (parseOptional(47 /* BarToken */)) { + types.push(parseJSDocType()); + } + types.end = scanner.getStartPos(); + return types; + } + function parseJSDocAllType() { + var result = createNode(250 /* JSDocAllType */); + nextToken(); + return finishNode(result); + } + function parseJSDocUnknownOrNullableType() { + var pos = scanner.getStartPos(); + // skip the ? + nextToken(); + // Need to lookahead to decide if this is a nullable or unknown type. + // Here are cases where we'll pick the unknown type: + // + // Foo(?, + // { a: ? } + // Foo(?) + // Foo + // Foo(?= + // (?| + if (token === 24 /* CommaToken */ || + token === 16 /* CloseBraceToken */ || + token === 18 /* CloseParenToken */ || + token === 27 /* GreaterThanToken */ || + token === 56 /* EqualsToken */ || + token === 47 /* BarToken */) { + var result = createNode(251 /* JSDocUnknownType */, pos); + return finishNode(result); + } + else { + var result = createNode(255 /* JSDocNullableType */, pos); + result.type = parseJSDocType(); + return finishNode(result); + } + } + function parseIsolatedJSDocComment(content, start, length) { + initializeState("file.js", content, 2 /* Latest */, /*_syntaxCursor:*/ undefined); + var jsDocComment = parseJSDocComment(/*parent:*/ undefined, start, length); + var diagnostics = parseDiagnostics; + clearState(); + return jsDocComment ? { jsDocComment: jsDocComment, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + function parseJSDocComment(parent, start, length) { + var comment = parseJSDocCommentWorker(start, length); + if (comment) { + fixupParentReferences(comment); + comment.parent = parent; + } + return comment; + } + JSDocParser.parseJSDocComment = parseJSDocComment; + function parseJSDocCommentWorker(start, length) { + var content = sourceText; + start = start || 0; + var end = length === undefined ? content.length : start + length; + length = end - start; + ts.Debug.assert(start >= 0); + ts.Debug.assert(start <= end); + ts.Debug.assert(end <= content.length); + var tags; + var pos; + // NOTE(cyrusn): This is essentially a handwritten scanner for JSDocComments. I + // considered using an actual Scanner, but this would complicate things. The + // scanner would need to know it was in a Doc Comment. Otherwise, it would then + // produce comments *inside* the doc comment. In the end it was just easier to + // write a simple scanner rather than go that route. + if (length >= "/** */".length) { + if (content.charCodeAt(start) === 47 /* slash */ && + content.charCodeAt(start + 1) === 42 /* asterisk */ && + content.charCodeAt(start + 2) === 42 /* asterisk */ && + content.charCodeAt(start + 3) !== 42 /* asterisk */) { + // Initially we can parse out a tag. We also have seen a starting asterisk. + // This is so that /** * @type */ doesn't parse. + var canParseTag = true; + var seenAsterisk = true; + for (pos = start + "/**".length; pos < end;) { + var ch = content.charCodeAt(pos); + pos++; + if (ch === 64 /* at */ && canParseTag) { + parseTag(); + // Once we parse out a tag, we cannot keep parsing out tags on this line. + canParseTag = false; + continue; + } + if (ts.isLineBreak(ch)) { + // After a line break, we can parse a tag, and we haven't seen as asterisk + // on the next line yet. + canParseTag = true; + seenAsterisk = false; + continue; + } + if (ts.isWhiteSpace(ch)) { + // Whitespace doesn't affect any of our parsing. + continue; + } + // Ignore the first asterisk on a line. + if (ch === 42 /* asterisk */) { + if (seenAsterisk) { + // If we've already seen an asterisk, then we can no longer parse a tag + // on this line. + canParseTag = false; + } + seenAsterisk = true; + continue; + } + // Anything else is doc comment text. We can't do anything with it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. + canParseTag = false; + } + } + } + return createJSDocComment(); + function createJSDocComment() { + if (!tags) { + return undefined; + } + var result = createNode(265 /* JSDocComment */, start); + result.tags = tags; + return finishNode(result, end); + } + function skipWhitespace() { + while (pos < end && ts.isWhiteSpace(content.charCodeAt(pos))) { + pos++; + } + } + function parseTag() { + ts.Debug.assert(content.charCodeAt(pos - 1) === 64 /* at */); + var atToken = createNode(55 /* AtToken */, pos - 1); + atToken.end = pos; + var tagName = scanIdentifier(); + if (!tagName) { + return; + } + var tag = handleTag(atToken, tagName) || handleUnknownTag(atToken, tagName); + addTag(tag); + } + function handleTag(atToken, tagName) { + if (tagName) { + switch (tagName.text) { + case "param": + return handleParamTag(atToken, tagName); + case "return": + case "returns": + return handleReturnTag(atToken, tagName); + case "template": + return handleTemplateTag(atToken, tagName); + case "type": + return handleTypeTag(atToken, tagName); + } + } + return undefined; + } + function handleUnknownTag(atToken, tagName) { + var result = createNode(266 /* JSDocTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + return finishNode(result, pos); + } + function addTag(tag) { + if (tag) { + if (!tags) { + tags = []; + tags.pos = tag.pos; + } + tags.push(tag); + tags.end = tag.end; + } + } + function tryParseTypeExpression() { + skipWhitespace(); + if (content.charCodeAt(pos) !== 123 /* openBrace */) { + return undefined; + } + var typeExpression = parseJSDocTypeExpression(pos, end - pos); + pos = typeExpression.end; + return typeExpression; + } + function handleParamTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + skipWhitespace(); + var name; + var isBracketed; + if (content.charCodeAt(pos) === 91 /* openBracket */) { + pos++; + skipWhitespace(); + name = scanIdentifier(); + isBracketed = true; + } + else { + name = scanIdentifier(); + } + if (!name) { + parseErrorAtPosition(pos, 0, ts.Diagnostics.Identifier_expected); + } + var preName, postName; + if (typeExpression) { + postName = name; + } + else { + preName = name; + } + if (!typeExpression) { + typeExpression = tryParseTypeExpression(); + } + var result = createNode(267 /* JSDocParameterTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.preParameterName = preName; + result.typeExpression = typeExpression; + result.postParameterName = postName; + result.isBracketed = isBracketed; + return finishNode(result, pos); + } + function handleReturnTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 268 /* JSDocReturnTag */; })) { + parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + } + var result = createNode(268 /* JSDocReturnTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result, pos); + } + function handleTypeTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 269 /* JSDocTypeTag */; })) { + parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + } + var result = createNode(269 /* JSDocTypeTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result, pos); + } + function handleTemplateTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 270 /* JSDocTemplateTag */; })) { + parseErrorAtPosition(tagName.pos, pos - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + } + var typeParameters = []; + typeParameters.pos = pos; + while (true) { + skipWhitespace(); + var startPos = pos; + var name_8 = scanIdentifier(); + if (!name_8) { + parseErrorAtPosition(startPos, 0, ts.Diagnostics.Identifier_expected); + return undefined; + } + var typeParameter = createNode(137 /* TypeParameter */, name_8.pos); + typeParameter.name = name_8; + finishNode(typeParameter, pos); + typeParameters.push(typeParameter); + skipWhitespace(); + if (content.charCodeAt(pos) !== 44 /* comma */) { + break; + } + pos++; + } + typeParameters.end = pos; + var result = createNode(270 /* JSDocTemplateTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeParameters = typeParameters; + return finishNode(result, pos); + } + function scanIdentifier() { + var startPos = pos; + for (; pos < end; pos++) { + var ch = content.charCodeAt(pos); + if (pos === startPos && ts.isIdentifierStart(ch, 2 /* Latest */)) { + continue; + } + else if (pos > startPos && ts.isIdentifierPart(ch, 2 /* Latest */)) { + continue; + } + break; + } + if (startPos === pos) { + return undefined; + } + var result = createNode(69 /* Identifier */, startPos); + result.text = content.substring(startPos, pos); + return finishNode(result, pos); + } + } + JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; + })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); + })(Parser || (Parser = {})); + var IncrementalParser; + (function (IncrementalParser) { + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */); + checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); + if (ts.textChangeRangeIsUnchanged(textChangeRange)) { + // if the text didn't change, then we can just return our current source file as-is. + return sourceFile; + } + if (sourceFile.statements.length === 0) { + // If we don't have any statements in the current source file, then there's no real + // way to incrementally parse. So just do a full parse instead. + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setNodeParents*/ true); + } + // Make sure we're not trying to incrementally update a source file more than once. Once + // we do an update the original source file is considered unusbale from that point onwards. + // + // This is because we do incremental parsing in-place. i.e. we take nodes from the old + // tree and give them new positions and parents. From that point on, trusting the old + // tree at all is not possible as far too much of it may violate invariants. + var incrementalSourceFile = sourceFile; + ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); + incrementalSourceFile.hasBeenIncrementallyParsed = true; + var oldText = sourceFile.text; + var syntaxCursor = createSyntaxCursor(sourceFile); + // Make the actual change larger so that we know to reparse anything whose lookahead + // might have intersected the change. + var changeRange = extendToAffectedRange(sourceFile, textChangeRange); + checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); + // Ensure that extending the affected range only moved the start of the change range + // earlier in the file. + ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start); + ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span)); + ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); + // The is the amount the nodes after the edit range need to be adjusted. It can be + // positive (if the edit added characters), negative (if the edit deleted characters) + // or zero (if this was a pure overwrite with nothing added/removed). + var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + // If we added or removed characters during the edit, then we need to go and adjust all + // the nodes after the edit. Those nodes may move forward (if we inserted chars) or they + // may move backward (if we deleted chars). + // + // Doing this helps us out in two ways. First, it means that any nodes/tokens we want + // to reuse are already at the appropriate position in the new text. That way when we + // reuse them, we don't have to figure out if they need to be adjusted. Second, it makes + // it very easy to determine if we can reuse a node. If the node's position is at where + // we are in the text, then we can reuse it. Otherwise we can't. If the node's position + // is ahead of us, then we'll need to rescan tokens. If the node's position is behind + // us, then we'll need to skip it or crumble it as appropriate + // + // We will also adjust the positions of nodes that intersect the change range as well. + // By doing this, we ensure that all the positions in the old tree are consistent, not + // just the positions of nodes entirely before/after the change range. By being + // consistent, we can then easily map from positions to nodes in the old tree easily. + // + // Also, mark any syntax elements that intersect the changed span. We know, up front, + // that we cannot reuse these elements. + updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); + // Now that we've set up our internal incremental state just proceed and parse the + // source file in the normal fashion. When possible the parser will retrieve and + // reuse nodes from the old tree. + // + // Note: passing in 'true' for setNodeParents is very important. When incrementally + // parsing, we will be reusing nodes from the old tree, and placing it into new + // parents. If we don't set the parents now, we'll end up with an observably + // inconsistent tree. Setting the parents on the new tree should be very fast. We + // will immediately bail out of walking any subtrees when we can see that their parents + // are already correct. + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /* setParentNode */ true); + return result; + } + IncrementalParser.updateSourceFile = updateSourceFile; + function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { + if (isArray) { + visitArray(element); + } + else { + visitNode(element); + } + return; + function visitNode(node) { + var text = ""; + if (aggressiveChecks && shouldCheckNode(node)) { + text = oldText.substring(node.pos, node.end); + } + // Ditch any existing LS children we may have created. This way we can avoid + // moving them forward. + if (node._children) { + node._children = undefined; + } + if (node.jsDocComment) { + node.jsDocComment = undefined; + } + node.pos += delta; + node.end += delta; + if (aggressiveChecks && shouldCheckNode(node)) { + ts.Debug.assert(text === newText.substring(node.pos, node.end)); + } + forEachChild(node, visitNode, visitArray); + checkNodePositions(node, aggressiveChecks); + } + function visitArray(array) { + array._children = undefined; + array.pos += delta; + array.end += delta; + for (var _i = 0; _i < array.length; _i++) { + var node = array[_i]; + visitNode(node); + } + } + } + function shouldCheckNode(node) { + switch (node.kind) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 69 /* Identifier */: + return true; + } + return false; + } + function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { + ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); + ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); + ts.Debug.assert(element.pos <= element.end); + // We have an element that intersects the change range in some way. It may have its + // start, or its end (or both) in the changed range. We want to adjust any part + // that intersects such that the final tree is in a consistent state. i.e. all + // chlidren have spans within the span of their parent, and all siblings are ordered + // properly. + // We may need to update both the 'pos' and the 'end' of the element. + // If the 'pos' is before the start of the change, then we don't need to touch it. + // If it isn't, then the 'pos' must be inside the change. How we update it will + // depend if delta is positive or negative. If delta is positive then we have + // something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that started in the change range to still be + // starting at the same position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that started in the 'X' range will keep its position. + // However any element htat started after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that started in the 'Y' range will + // be adjusted to have their start at the end of the 'Z' range. + // + // The element will keep its position if possible. Or Move backward to the new-end + // if it's in the 'Y' range. + element.pos = Math.min(element.pos, changeRangeNewEnd); + // If the 'end' is after the change range, then we always adjust it by the delta + // amount. However, if the end is in the change range, then how we adjust it + // will depend on if delta is positive or negative. If delta is positive then we + // have something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that ended inside the change range to keep its + // end position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that ended in the 'X' range will keep its position. + // However any element htat ended after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that ended in the 'Y' range will + // be adjusted to have their end at the end of the 'Z' range. + if (element.end >= changeRangeOldEnd) { + // Element ends after the change range. Always adjust the end pos. + element.end += delta; + } + else { + // Element ends in the change range. The element will keep its position if + // possible. Or Move backward to the new-end if it's in the 'Y' range. + element.end = Math.min(element.end, changeRangeNewEnd); + } + ts.Debug.assert(element.pos <= element.end); + if (element.parent) { + ts.Debug.assert(element.pos >= element.parent.pos); + ts.Debug.assert(element.end <= element.parent.end); + } + } + function checkNodePositions(node, aggressiveChecks) { + if (aggressiveChecks) { + var pos = node.pos; + forEachChild(node, function (child) { + ts.Debug.assert(child.pos >= pos); + pos = child.end; + }); + ts.Debug.assert(pos <= node.end); + } + } + function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { + visitNode(sourceFile); + return; + function visitNode(child) { + ts.Debug.assert(child.pos <= child.end); + if (child.pos > changeRangeOldEnd) { + // Node is entirely past the change range. We need to move both its pos and + // end, forward or backward appropriately. + moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks); + return; + } + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. + var fullEnd = child.end; + if (fullEnd >= changeStart) { + child.intersectsChange = true; + child._children = undefined; + // Adjust the pos or end (or both) of the intersecting element accordingly. + adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + forEachChild(child, visitNode, visitArray); + checkNodePositions(child, aggressiveChecks); + return; + } + // Otherwise, the node is entirely before the change range. No need to do anything with it. + ts.Debug.assert(fullEnd < changeStart); + } + function visitArray(array) { + ts.Debug.assert(array.pos <= array.end); + if (array.pos > changeRangeOldEnd) { + // Array is entirely after the change range. We need to move it, and move any of + // its children. + moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks); + return; + } + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. + var fullEnd = array.end; + if (fullEnd >= changeStart) { + array.intersectsChange = true; + array._children = undefined; + // Adjust the pos or end (or both) of the intersecting array accordingly. + adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + for (var _i = 0; _i < array.length; _i++) { + var node = array[_i]; + visitNode(node); + } + return; + } + // Otherwise, the array is entirely before the change range. No need to do anything with it. + ts.Debug.assert(fullEnd < changeStart); + } + } + function extendToAffectedRange(sourceFile, changeRange) { + // Consider the following code: + // void foo() { /; } + // + // If the text changes with an insertion of / just before the semicolon then we end up with: + // void foo() { //; } + // + // If we were to just use the changeRange a is, then we would not rescan the { token + // (as it does not intersect the actual original change range). Because an edit may + // change the token touching it, we actually need to look back *at least* one token so + // that the prior token sees that change. + var maxLookahead = 1; + var start = changeRange.span.start; + // the first iteration aligns us with the change start. subsequent iteration move us to + // the left by maxLookahead tokens. We only need to do this as long as we're not at the + // start of the tree. + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); + ts.Debug.assert(nearestNode.pos <= start); + var position = nearestNode.pos; + start = Math.max(0, position - 1); + } + var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); + var finalLength = changeRange.newLength + (changeRange.span.start - start); + return ts.createTextChangeRange(finalSpan, finalLength); + } + function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) { + var bestResult = sourceFile; + var lastNodeEntirelyBeforePosition; + forEachChild(sourceFile, visit); + if (lastNodeEntirelyBeforePosition) { + var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { + bestResult = lastChildOfLastEntireNodeBeforePosition; + } + } + return bestResult; + function getLastChild(node) { + while (true) { + var lastChild = getLastChildWorker(node); + if (lastChild) { + node = lastChild; + } + else { + return node; + } + } + } + function getLastChildWorker(node) { + var last = undefined; + forEachChild(node, function (child) { + if (ts.nodeIsPresent(child)) { + last = child; + } + }); + return last; + } + function visit(child) { + if (ts.nodeIsMissing(child)) { + // Missing nodes are effectively invisible to us. We never even consider them + // When trying to find the nearest node before us. + return; + } + // If the child intersects this position, then this node is currently the nearest + // node that starts before the position. + if (child.pos <= position) { + if (child.pos >= bestResult.pos) { + // This node starts before the position, and is closer to the position than + // the previous best node we found. It is now the new best node. + bestResult = child; + } + // Now, the node may overlap the position, or it may end entirely before the + // position. If it overlaps with the position, then either it, or one of its + // children must be the nearest node before the position. So we can just + // recurse into this child to see if we can find something better. + if (position < child.end) { + // The nearest node is either this child, or one of the children inside + // of it. We've already marked this child as the best so far. Recurse + // in case one of the children is better. + forEachChild(child, visit); + // Once we look at the children of this node, then there's no need to + // continue any further. + return true; + } + else { + ts.Debug.assert(child.end <= position); + // The child ends entirely before this position. Say you have the following + // (where $ is the position) + // + // ? $ : <...> <...> + // + // We would want to find the nearest preceding node in "complex expr 2". + // To support that, we keep track of this node, and once we're done searching + // for a best node, we recurse down this node to see if we can find a good + // result in it. + // + // This approach allows us to quickly skip over nodes that are entirely + // before the position, while still allowing us to find any nodes in the + // last one that might be what we want. + lastNodeEntirelyBeforePosition = child; + } + } + else { + ts.Debug.assert(child.pos > position); + // We're now at a node that is entirely past the position we're searching for. + // This node (and all following nodes) could never contribute to the result, + // so just skip them by returning 'true' here. + return true; + } + } + } + function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) { + var oldText = sourceFile.text; + if (textChangeRange) { + ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); + if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) { + var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); + var newTextPrefix = newText.substr(0, textChangeRange.span.start); + ts.Debug.assert(oldTextPrefix === newTextPrefix); + var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length); + var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length); + ts.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + } + function createSyntaxCursor(sourceFile) { + var currentArray = sourceFile.statements; + var currentArrayIndex = 0; + ts.Debug.assert(currentArrayIndex < currentArray.length); + var current = currentArray[currentArrayIndex]; + var lastQueriedPosition = -1 /* Value */; + return { + currentNode: function (position) { + // Only compute the current node if the position is different than the last time + // we were asked. The parser commonly asks for the node at the same position + // twice. Once to know if can read an appropriate list element at a certain point, + // and then to actually read and consume the node. + if (position !== lastQueriedPosition) { + // Much of the time the parser will need the very next node in the array that + // we just returned a node from.So just simply check for that case and move + // forward in the array instead of searching for the node again. + if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { + currentArrayIndex++; + current = currentArray[currentArrayIndex]; + } + // If we don't have a node, or the node we have isn't in the right position, + // then try to find a viable node at the position requested. + if (!current || current.pos !== position) { + findHighestListElementThatStartsAtPosition(position); + } + } + // Cache this query so that we don't do any extra work if the parser calls back + // into us. Note: this is very common as the parser will make pairs of calls like + // 'isListElement -> parseListElement'. If we were unable to find a node when + // called with 'isListElement', we don't want to redo the work when parseListElement + // is called immediately after. + lastQueriedPosition = position; + // Either we don'd have a node, or we have a node at the position being asked for. + ts.Debug.assert(!current || current.pos === position); + return current; + } + }; + // Finds the highest element in the tree we can find that starts at the provided position. + // The element must be a direct child of some node list in the tree. This way after we + // return it, we can easily return its next sibling in the list. + function findHighestListElementThatStartsAtPosition(position) { + // Clear out any cached state about the last node we found. + currentArray = undefined; + currentArrayIndex = -1 /* Value */; + current = undefined; + // Recurse into the source file to find the highest node at this position. + forEachChild(sourceFile, visitNode, visitArray); + return; + function visitNode(node) { + if (position >= node.pos && position < node.end) { + // Position was within this node. Keep searching deeper to find the node. + forEachChild(node, visitNode, visitArray); + // don't procede any futher in the search. + return true; + } + // position wasn't in this node, have to keep searching. + return false; + } + function visitArray(array) { + if (position >= array.pos && position < array.end) { + // position was in this array. Search through this array to see if we find a + // viable element. + for (var i = 0, n = array.length; i < n; i++) { + var child = array[i]; + if (child) { + if (child.pos === position) { + // Found the right node. We're done. + currentArray = array; + currentArrayIndex = i; + current = child; + return true; + } + else { + if (child.pos < position && position < child.end) { + // Position in somewhere within this child. Search in it and + // stop searching in this array. + forEachChild(child, visitNode, visitArray); + return true; + } + } + } + } + } + // position wasn't in this array, have to keep searching. + return false; + } + } + } + var InvalidPosition; + (function (InvalidPosition) { + InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; + })(InvalidPosition || (InvalidPosition = {})); + })(IncrementalParser || (IncrementalParser = {})); +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + var nextSymbolId = 1; + var nextNodeId = 1; + var nextMergeId = 1; + function getNodeId(node) { + if (!node.id) + node.id = nextNodeId++; + return node.id; + } + ts.getNodeId = getNodeId; + ts.checkTime = 0; + function getSymbolId(symbol) { + if (!symbol.id) { + symbol.id = nextSymbolId++; + } + return symbol.id; + } + ts.getSymbolId = getSymbolId; + function createTypeChecker(host, produceDiagnostics) { + // Cancellation that controls whether or not we can cancel in the middle of type checking. + // In general cancelling is *not* safe for the type checker. We might be in the middle of + // computing something, and we will leave our internals in an inconsistent state. Callers + // who set the cancellation token should catch if a cancellation exception occurs, and + // should throw away and create a new TypeChecker. + // + // Currently we only support setting the cancellation token when getting diagnostics. This + // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if + // they no longer need the information (for example, if the user started editing again). + var cancellationToken; + var Symbol = ts.objectAllocator.getSymbolConstructor(); + var Type = ts.objectAllocator.getTypeConstructor(); + var Signature = ts.objectAllocator.getSignatureConstructor(); + var typeCount = 0; + var symbolCount = 0; + var emptyArray = []; + var emptySymbols = {}; + var compilerOptions = host.getCompilerOptions(); + var languageVersion = compilerOptions.target || 0 /* ES3 */; + var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 /* ES6 */ ? 5 /* ES6 */ : 0 /* None */; + var emitResolver = createResolver(); + var undefinedSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "undefined"); + var argumentsSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "arguments"); + var checker = { + getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, + getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, + getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, + getTypeCount: function () { return typeCount; }, + isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, + isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, + getDiagnostics: getDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + // The language service will always care about the narrowed type of a symbol, because that is + // the type the language says the symbol should have. + getTypeOfSymbolAtLocation: getNarrowedTypeOfSymbol, + getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, + getPropertiesOfType: getPropertiesOfType, + getPropertyOfType: getPropertyOfType, + getSignaturesOfType: getSignaturesOfType, + getIndexTypeOfType: getIndexTypeOfType, + getBaseTypes: getBaseTypes, + getReturnTypeOfSignature: getReturnTypeOfSignature, + getSymbolsInScope: getSymbolsInScope, + getSymbolAtLocation: getSymbolAtLocation, + getShorthandAssignmentValueSymbol: getShorthandAssignmentValueSymbol, + getTypeAtLocation: getTypeOfNode, + typeToString: typeToString, + getSymbolDisplayBuilder: getSymbolDisplayBuilder, + symbolToString: symbolToString, + getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, + getRootSymbols: getRootSymbols, + getContextualType: getContextualType, + getFullyQualifiedName: getFullyQualifiedName, + getResolvedSignature: getResolvedSignature, + getConstantValue: getConstantValue, + isValidPropertyAccess: isValidPropertyAccess, + getSignatureFromDeclaration: getSignatureFromDeclaration, + isImplementationOfOverload: isImplementationOfOverload, + getAliasedSymbol: resolveAlias, + getEmitResolver: getEmitResolver, + getExportsOfModule: getExportsOfModuleAsArray, + getJsxElementAttributesType: getJsxElementAttributesType, + getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, + isOptionalParameter: isOptionalParameter + }; + var unknownSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "unknown"); + var resolvingSymbol = createSymbol(67108864 /* Transient */, "__resolving__"); + var anyType = createIntrinsicType(1 /* Any */, "any"); + var stringType = createIntrinsicType(2 /* String */, "string"); + var numberType = createIntrinsicType(4 /* Number */, "number"); + var booleanType = createIntrinsicType(8 /* Boolean */, "boolean"); + var esSymbolType = createIntrinsicType(16777216 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(16 /* Void */, "void"); + var undefinedType = createIntrinsicType(32 /* Undefined */ | 2097152 /* ContainsUndefinedOrNull */, "undefined"); + var nullType = createIntrinsicType(64 /* Null */ | 2097152 /* ContainsUndefinedOrNull */, "null"); + var unknownType = createIntrinsicType(1 /* Any */, "unknown"); + var circularType = createIntrinsicType(1 /* Any */, "__circular__"); + var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + emptyGenericType.instantiations = {}; + var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated + // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. + anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; + var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + var anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); + var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); + var globals = {}; + var globalESSymbolConstructorSymbol; + var getGlobalPromiseConstructorSymbol; + var globalObjectType; + var globalFunctionType; + var globalArrayType; + var globalStringType; + var globalNumberType; + var globalBooleanType; + var globalRegExpType; + var globalTemplateStringsArrayType; + var globalESSymbolType; + var jsxElementType; + /** Lazily loaded, use getJsxIntrinsicElementType() */ + var jsxIntrinsicElementsType; + var globalIterableType; + var globalIteratorType; + var globalIterableIteratorType; + var anyArrayType; + var getGlobalClassDecoratorType; + var getGlobalParameterDecoratorType; + var getGlobalPropertyDecoratorType; + var getGlobalMethodDecoratorType; + var getGlobalTypedPropertyDescriptorType; + var getGlobalPromiseType; + var tryGetGlobalPromiseType; + var getGlobalPromiseLikeType; + var getInstantiatedGlobalPromiseLikeType; + var getGlobalPromiseConstructorLikeType; + var getGlobalThenableType; + var tupleTypes = {}; + var unionTypes = {}; + var intersectionTypes = {}; + var stringLiteralTypes = {}; + var emitExtends = false; + var emitDecorate = false; + var emitParam = false; + var emitAwaiter = false; + var emitGenerator = false; + var resolutionTargets = []; + var resolutionResults = []; + var resolutionPropertyNames = []; + var mergedSymbols = []; + var symbolLinks = []; + var nodeLinks = []; + var potentialThisCollisions = []; + var awaitedTypeStack = []; + var diagnostics = ts.createDiagnosticCollection(); + var primitiveTypeInfo = { + "string": { + type: stringType, + flags: 258 /* StringLike */ + }, + "number": { + type: numberType, + flags: 132 /* NumberLike */ + }, + "boolean": { + type: booleanType, + flags: 8 /* Boolean */ + }, + "symbol": { + type: esSymbolType, + flags: 16777216 /* ESSymbol */ + } + }; + var JsxNames = { + JSX: "JSX", + IntrinsicElements: "IntrinsicElements", + ElementClass: "ElementClass", + ElementAttributesPropertyNameContainer: "ElementAttributesProperty", + Element: "Element" + }; + var subtypeRelation = {}; + var assignableRelation = {}; + var identityRelation = {}; + // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. + var _displayBuilder; + var TypeSystemPropertyName; + (function (TypeSystemPropertyName) { + TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; + TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; + TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; + })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); + initializeTypeChecker(); + return checker; + function getEmitResolver(sourceFile, cancellationToken) { + // Ensure we have all the type information in place for this file so that all the + // emitter questions of this resolver will return the right information. + getDiagnostics(sourceFile, cancellationToken); + return emitResolver; + } + function error(location, message, arg0, arg1, arg2) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2); + diagnostics.add(diagnostic); + } + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); + } + function getExcludedSymbolFlags(flags) { + var result = 0; + if (flags & 2 /* BlockScopedVariable */) + result |= 107455 /* BlockScopedVariableExcludes */; + if (flags & 1 /* FunctionScopedVariable */) + result |= 107454 /* FunctionScopedVariableExcludes */; + if (flags & 4 /* Property */) + result |= 107455 /* PropertyExcludes */; + if (flags & 8 /* EnumMember */) + result |= 107455 /* EnumMemberExcludes */; + if (flags & 16 /* Function */) + result |= 106927 /* FunctionExcludes */; + if (flags & 32 /* Class */) + result |= 899519 /* ClassExcludes */; + if (flags & 64 /* Interface */) + result |= 792960 /* InterfaceExcludes */; + if (flags & 256 /* RegularEnum */) + result |= 899327 /* RegularEnumExcludes */; + if (flags & 128 /* ConstEnum */) + result |= 899967 /* ConstEnumExcludes */; + if (flags & 512 /* ValueModule */) + result |= 106639 /* ValueModuleExcludes */; + if (flags & 8192 /* Method */) + result |= 99263 /* MethodExcludes */; + if (flags & 32768 /* GetAccessor */) + result |= 41919 /* GetAccessorExcludes */; + if (flags & 65536 /* SetAccessor */) + result |= 74687 /* SetAccessorExcludes */; + if (flags & 262144 /* TypeParameter */) + result |= 530912 /* TypeParameterExcludes */; + if (flags & 524288 /* TypeAlias */) + result |= 793056 /* TypeAliasExcludes */; + if (flags & 8388608 /* Alias */) + result |= 8388608 /* AliasExcludes */; + return result; + } + function recordMergedSymbol(target, source) { + if (!source.mergeId) + source.mergeId = nextMergeId++; + mergedSymbols[source.mergeId] = target; + } + function cloneSymbol(symbol) { + var result = createSymbol(symbol.flags | 33554432 /* Merged */, symbol.name); + result.declarations = symbol.declarations.slice(0); + result.parent = symbol.parent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = cloneSymbolTable(symbol.members); + if (symbol.exports) + result.exports = cloneSymbolTable(symbol.exports); + recordMergedSymbol(result, symbol); + return result; + } + function mergeSymbol(target, source) { + if (!(target.flags & getExcludedSymbolFlags(source.flags))) { + if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { + // reset flag when merging instantiated module into value module that has only const enums + target.constEnumOnlyModule = false; + } + target.flags |= source.flags; + if (!target.valueDeclaration && source.valueDeclaration) + target.valueDeclaration = source.valueDeclaration; + ts.forEach(source.declarations, function (node) { + target.declarations.push(node); + }); + if (source.members) { + if (!target.members) + target.members = {}; + mergeSymbolTable(target.members, source.members); + } + if (source.exports) { + if (!target.exports) + target.exports = {}; + mergeSymbolTable(target.exports, source.exports); + } + recordMergedSymbol(target, source); + } + else { + var message = target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */ + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + ts.forEach(source.declarations, function (node) { + error(node.name ? node.name : node, message, symbolToString(source)); + }); + ts.forEach(target.declarations, function (node) { + error(node.name ? node.name : node, message, symbolToString(source)); + }); + } + } + function cloneSymbolTable(symbolTable) { + var result = {}; + for (var id in symbolTable) { + if (ts.hasProperty(symbolTable, id)) { + result[id] = symbolTable[id]; + } + } + return result; + } + function mergeSymbolTable(target, source) { + for (var id in source) { + if (ts.hasProperty(source, id)) { + if (!ts.hasProperty(target, id)) { + target[id] = source[id]; + } + else { + var symbol = target[id]; + if (!(symbol.flags & 33554432 /* Merged */)) { + target[id] = symbol = cloneSymbol(symbol); + } + mergeSymbol(symbol, source[id]); + } + } + } + } + function getSymbolLinks(symbol) { + if (symbol.flags & 67108864 /* Transient */) + return symbol; + var id = getSymbolId(symbol); + return symbolLinks[id] || (symbolLinks[id] = {}); + } + function getNodeLinks(node) { + var nodeId = getNodeId(node); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); + } + function getSourceFile(node) { + return ts.getAncestor(node, 248 /* SourceFile */); + } + function isGlobalSourceFile(node) { + return node.kind === 248 /* SourceFile */ && !ts.isExternalModule(node); + } + function getSymbol(symbols, name, meaning) { + if (meaning && ts.hasProperty(symbols, name)) { + var symbol = symbols[name]; + ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { + return symbol; + } + if (symbol.flags & 8388608 /* Alias */) { + var target = resolveAlias(symbol); + // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors + if (target === unknownSymbol || target.flags & meaning) { + return symbol; + } + } + } + // return undefined if we can't find a symbol. + } + function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { + var declarationFile = ts.getSourceFileOfNode(declaration); + var useFile = ts.getSourceFileOfNode(usage); + if (declarationFile !== useFile) { + if (modulekind || (!compilerOptions.outFile && !compilerOptions.out)) { + // nodes are in different files and order cannot be determines + return true; + } + var sourceFiles = host.getSourceFiles(); + return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); + } + if (declaration.pos <= usage.pos) { + // declaration is before usage + // still might be illegal if usage is in the initializer of the variable declaration + return declaration.kind !== 211 /* VariableDeclaration */ || + !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); + } + // declaration is after usage + // can be legal if usage is deferred (i.e. inside function or in initializer of instance property) + return isUsedInFunctionOrNonStaticProperty(declaration, usage); + function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { + var container = ts.getEnclosingBlockScopeContainer(declaration); + if (declaration.parent.parent.kind === 193 /* VariableStatement */ || + declaration.parent.parent.kind === 199 /* ForStatement */) { + // variable statement/for statement case, + // use site should not be inside variable declaration (initializer of declaration or binding element) + return isSameScopeDescendentOf(usage, declaration, container); + } + else if (declaration.parent.parent.kind === 201 /* ForOfStatement */ || + declaration.parent.parent.kind === 200 /* ForInStatement */) { + // ForIn/ForOf case - use site should not be used in expression part + var expression = declaration.parent.parent.expression; + return isSameScopeDescendentOf(usage, expression, container); + } + } + function isUsedInFunctionOrNonStaticProperty(declaration, usage) { + var container = ts.getEnclosingBlockScopeContainer(declaration); + var current = usage; + while (current) { + if (current === container) { + return false; + } + if (ts.isFunctionLike(current)) { + return true; + } + var initializerOfNonStaticProperty = current.parent && + current.parent.kind === 141 /* PropertyDeclaration */ && + (current.parent.flags & 128 /* Static */) === 0 && + current.parent.initializer === current; + if (initializerOfNonStaticProperty) { + return true; + } + current = current.parent; + } + return false; + } + } + // Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and + // the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with + // the given name can be found. + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { + var result; + var lastLocation; + var propertyWithInvalidInitializer; + var errorLocation = location; + var grandparent; + loop: while (location) { + // Locals of a source file are not in scope (because they get merged into the global symbol table) + if (location.locals && !isGlobalSourceFile(location)) { + if (result = getSymbol(location.locals, name, meaning)) { + // Type parameters of a function are in scope in the entire function declaration, including the parameter + // list and return type. However, local types are only in scope in the function body. + if (!(meaning & 793056 /* Type */) || + !(result.flags & (793056 /* Type */ & ~262144 /* TypeParameter */)) || + !ts.isFunctionLike(location) || + lastLocation === location.body) { + break loop; + } + result = undefined; + } + } + switch (location.kind) { + case 248 /* SourceFile */: + if (!ts.isExternalModule(location)) + break; + case 218 /* ModuleDeclaration */: + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 248 /* SourceFile */ || + (location.kind === 218 /* ModuleDeclaration */ && location.name.kind === 9 /* StringLiteral */)) { + // It's an external module. Because of module/namespace merging, a module's exports are in scope, + // yet we never want to treat an export specifier as putting a member in scope. Therefore, + // if the name we find is purely an export specifier, it is not actually considered in scope. + // Two things to note about this: + // 1. We have to check this without calling getSymbol. The problem with calling getSymbol + // on an export specifier is that it might find the export specifier itself, and try to + // resolve it as an alias. This will cause the checker to consider the export specifier + // a circular alias reference when it might not be. + // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely* + // an alias. If we used &, we'd be throwing out symbols that have non alias aspects, + // which is not the desired behavior. + if (ts.hasProperty(moduleExports, name) && + moduleExports[name].flags === 8388608 /* Alias */ && + ts.getDeclarationOfKind(moduleExports[name], 230 /* ExportSpecifier */)) { + break; + } + result = moduleExports["default"]; + var localSymbol = ts.getLocalSymbolForExportDefault(result); + if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) { + break loop; + } + result = undefined; + } + if (result = getSymbol(moduleExports, name, meaning & 8914931 /* ModuleMember */)) { + break loop; + } + break; + case 217 /* EnumDeclaration */: + if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { + break loop; + } + break; + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + // TypeScript 1.0 spec (April 2014): 8.4.1 + // Initializer expressions for instance member variables are evaluated in the scope + // of the class constructor body but are not permitted to reference parameters or + // local variables of the constructor. This effectively means that entities from outer scopes + // by the same name as a constructor parameter or local variable are inaccessible + // in initializer expressions for instance member variables. + if (ts.isClassLike(location.parent) && !(location.flags & 128 /* Static */)) { + var ctor = findConstructorDeclaration(location.parent); + if (ctor && ctor.locals) { + if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) { + // Remember the property node, it will be used later to report appropriate error + propertyWithInvalidInitializer = location; + } + } + } + break; + case 214 /* ClassDeclaration */: + case 186 /* ClassExpression */: + case 215 /* InterfaceDeclaration */: + if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056 /* Type */)) { + if (lastLocation && lastLocation.flags & 128 /* Static */) { + // TypeScript 1.0 spec (April 2014): 3.4.1 + // The scope of a type parameter extends over the entire declaration with which the type + // parameter list is associated, with the exception of static member declarations in classes. + error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); + return undefined; + } + break loop; + } + if (location.kind === 186 /* ClassExpression */ && meaning & 32 /* Class */) { + var className = location.name; + if (className && name === className.text) { + result = location.symbol; + break loop; + } + } + break; + // It is not legal to reference a class's own type parameters from a computed property name that + // belongs to the class. For example: + // + // function foo() { return '' } + // class C { // <-- Class's own type parameter T + // [foo()]() { } // <-- Reference to T from class's own computed property + // } + // + case 136 /* ComputedPropertyName */: + grandparent = location.parent.parent; + if (ts.isClassLike(grandparent) || grandparent.kind === 215 /* InterfaceDeclaration */) { + // A reference to this grandparent's type parameters would be an error + if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056 /* Type */)) { + error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); + return undefined; + } + } + break; + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 144 /* Constructor */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 213 /* FunctionDeclaration */: + case 174 /* ArrowFunction */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + break; + case 173 /* FunctionExpression */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + if (meaning & 16 /* Function */) { + var functionName = location.name; + if (functionName && name === functionName.text) { + result = location.symbol; + break loop; + } + } + break; + case 139 /* Decorator */: + // Decorators are resolved at the class declaration. Resolving at the parameter + // or member would result in looking up locals in the method. + // + // function y() {} + // class C { + // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. + // } + // + if (location.parent && location.parent.kind === 138 /* Parameter */) { + location = location.parent; + } + // + // function y() {} + // class C { + // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method. + // } + // + if (location.parent && ts.isClassElement(location.parent)) { + location = location.parent; + } + break; + } + lastLocation = location; + location = location.parent; + } + if (!result) { + result = getSymbol(globals, name, meaning); + } + if (!result) { + if (nameNotFoundMessage) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } + return undefined; + } + // Perform extra checks only if error reporting was requested + if (nameNotFoundMessage) { + if (propertyWithInvalidInitializer) { + // We have a match, but the reference occurred within a property initializer and the identifier also binds + // to a local variable in the constructor where the code will be emitted. + var propertyName = propertyWithInvalidInitializer.name; + error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + return undefined; + } + // Only check for block-scoped variable if we are looking for the + // name with variable meaning + // For example, + // declare module foo { + // interface bar {} + // } + // let foo/*1*/: foo/*2*/.bar; + // The foo at /*1*/ and /*2*/ will share same symbol with two meaning + // block - scope variable and namespace module. However, only when we + // try to resolve name in /*1*/ which is used in variable position, + // we want to check for block- scoped + if (meaning & 2 /* BlockScopedVariable */) { + var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); + if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */) { + checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); + } + } + } + return result; + } + function checkResolvedBlockScopedVariable(result, errorLocation) { + ts.Debug.assert((result.flags & 2 /* BlockScopedVariable */) !== 0); + // Block-scoped variables cannot be used before their definition + var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); + ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); + if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 211 /* VariableDeclaration */), errorLocation)) { + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + } + } + /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached. + * If at any point current node is equal to 'parent' node - return true. + * Return false if 'stopAt' node is reached or isFunctionLike(current) === true. + */ + function isSameScopeDescendentOf(initial, parent, stopAt) { + if (!parent) { + return false; + } + for (var current = initial; current && current !== stopAt && !ts.isFunctionLike(current); current = current.parent) { + if (current === parent) { + return true; + } + } + return false; + } + function getAnyImportSyntax(node) { + if (ts.isAliasSymbolDeclaration(node)) { + if (node.kind === 221 /* ImportEqualsDeclaration */) { + return node; + } + while (node && node.kind !== 222 /* ImportDeclaration */) { + node = node.parent; + } + return node; + } + } + function getDeclarationOfAliasSymbol(symbol) { + return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; }); + } + function getTargetOfImportEqualsDeclaration(node) { + if (node.moduleReference.kind === 232 /* ExternalModuleReference */) { + return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); + } + return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); + } + function getTargetOfImportClause(node) { + var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); + if (moduleSymbol) { + var exportDefaultSymbol = resolveSymbol(moduleSymbol.exports["default"]); + if (!exportDefaultSymbol) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } + return exportDefaultSymbol; + } + } + function getTargetOfNamespaceImport(node) { + var moduleSpecifier = node.parent.parent.moduleSpecifier; + return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier); + } + function getMemberOfModuleVariable(moduleSymbol, name) { + if (moduleSymbol.flags & 3 /* Variable */) { + var typeAnnotation = moduleSymbol.valueDeclaration.type; + if (typeAnnotation) { + return getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name); + } + } + } + // This function creates a synthetic symbol that combines the value side of one symbol with the + // type/namespace side of another symbol. Consider this example: + // + // declare module graphics { + // interface Point { + // x: number; + // y: number; + // } + // } + // declare var graphics: { + // Point: new (x: number, y: number) => graphics.Point; + // } + // declare module "graphics" { + // export = graphics; + // } + // + // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point' + // property with the type/namespace side interface 'Point'. + function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { + if (valueSymbol.flags & (793056 /* Type */ | 1536 /* Namespace */)) { + return valueSymbol; + } + var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); + result.declarations = ts.concatenate(valueSymbol.declarations, typeSymbol.declarations); + result.parent = valueSymbol.parent || typeSymbol.parent; + if (valueSymbol.valueDeclaration) + result.valueDeclaration = valueSymbol.valueDeclaration; + if (typeSymbol.members) + result.members = typeSymbol.members; + if (valueSymbol.exports) + result.exports = valueSymbol.exports; + return result; + } + function getExportOfModule(symbol, name) { + if (symbol.flags & 1536 /* Module */) { + var exports = getExportsOfSymbol(symbol); + if (ts.hasProperty(exports, name)) { + return resolveSymbol(exports[name]); + } + } + } + function getPropertyOfVariable(symbol, name) { + if (symbol.flags & 3 /* Variable */) { + var typeAnnotation = symbol.valueDeclaration.type; + if (typeAnnotation) { + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); + } + } + } + function getExternalModuleMember(node, specifier) { + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); + if (targetSymbol) { + var name_9 = specifier.propertyName || specifier.name; + if (name_9.text) { + var symbolFromModule = getExportOfModule(targetSymbol, name_9.text); + var symbolFromVariable = getPropertyOfVariable(targetSymbol, name_9.text); + var symbol = symbolFromModule && symbolFromVariable ? + combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : + symbolFromModule || symbolFromVariable; + if (!symbol) { + error(name_9, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_9)); + } + return symbol; + } + } + } + function getTargetOfImportSpecifier(node) { + return getExternalModuleMember(node.parent.parent.parent, node); + } + function getTargetOfExportSpecifier(node) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : + resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */); + } + function getTargetOfExportAssignment(node) { + return resolveEntityName(node.expression, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */); + } + function getTargetOfAliasDeclaration(node) { + switch (node.kind) { + case 221 /* ImportEqualsDeclaration */: + return getTargetOfImportEqualsDeclaration(node); + case 223 /* ImportClause */: + return getTargetOfImportClause(node); + case 224 /* NamespaceImport */: + return getTargetOfNamespaceImport(node); + case 226 /* ImportSpecifier */: + return getTargetOfImportSpecifier(node); + case 230 /* ExportSpecifier */: + return getTargetOfExportSpecifier(node); + case 227 /* ExportAssignment */: + return getTargetOfExportAssignment(node); + } + } + function resolveSymbol(symbol) { + return symbol && symbol.flags & 8388608 /* Alias */ && !(symbol.flags & (107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */)) ? resolveAlias(symbol) : symbol; + } + function resolveAlias(symbol) { + ts.Debug.assert((symbol.flags & 8388608 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.target) { + links.target = resolvingSymbol; + var node = getDeclarationOfAliasSymbol(symbol); + var target = getTargetOfAliasDeclaration(node); + if (links.target === resolvingSymbol) { + links.target = target || unknownSymbol; + } + else { + error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); + } + } + else if (links.target === resolvingSymbol) { + links.target = unknownSymbol; + } + return links.target; + } + function markExportAsReferenced(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target) { + var markAlias = (target === unknownSymbol && compilerOptions.isolatedModules) || + (target !== unknownSymbol && (target.flags & 107455 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + if (markAlias) { + markAliasSymbolAsReferenced(symbol); + } + } + } + // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until + // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of + // the alias as an expression (which recursively takes us back here if the target references another alias). + function markAliasSymbolAsReferenced(symbol) { + var links = getSymbolLinks(symbol); + if (!links.referenced) { + links.referenced = true; + var node = getDeclarationOfAliasSymbol(symbol); + if (node.kind === 227 /* ExportAssignment */) { + // export default + checkExpressionCached(node.expression); + } + else if (node.kind === 230 /* ExportSpecifier */) { + // export { } or export { as foo } + checkExpressionCached(node.propertyName || node.name); + } + else if (ts.isInternalModuleImportEqualsDeclaration(node)) { + // import foo = + checkExpressionCached(node.moduleReference); + } + } + } + // This function is only for imports with entity names + function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration) { + if (!importDeclaration) { + importDeclaration = ts.getAncestor(entityName, 221 /* ImportEqualsDeclaration */); + ts.Debug.assert(importDeclaration !== undefined); + } + // There are three things we might try to look for. In the following examples, + // the search term is enclosed in |...|: + // + // import a = |b|; // Namespace + // import a = |b.c|; // Value, type, namespace + // import a = |b.c|.d; // Namespace + if (entityName.kind === 69 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + // Check for case 1 and 3 in the above example + if (entityName.kind === 69 /* Identifier */ || entityName.parent.kind === 135 /* QualifiedName */) { + return resolveEntityName(entityName, 1536 /* Namespace */); + } + else { + // Case 2 in above example + // entityName.kind could be a QualifiedName or a Missing identifier + ts.Debug.assert(entityName.parent.kind === 221 /* ImportEqualsDeclaration */); + return resolveEntityName(entityName, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */); + } + } + function getFullyQualifiedName(symbol) { + return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + } + // Resolves a qualified name and any involved aliases + function resolveEntityName(name, meaning, ignoreErrors) { + if (ts.nodeIsMissing(name)) { + return undefined; + } + var symbol; + if (name.kind === 69 /* Identifier */) { + var message = meaning === 1536 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + symbol = resolveName(name, name.text, meaning, ignoreErrors ? undefined : message, name); + if (!symbol) { + return undefined; + } + } + else if (name.kind === 135 /* QualifiedName */ || name.kind === 166 /* PropertyAccessExpression */) { + var left = name.kind === 135 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 135 /* QualifiedName */ ? name.right : name.name; + var namespace = resolveEntityName(left, 1536 /* Namespace */, ignoreErrors); + if (!namespace || namespace === unknownSymbol || ts.nodeIsMissing(right)) { + return undefined; + } + symbol = getSymbol(getExportsOfSymbol(namespace), right.text, meaning); + if (!symbol) { + if (!ignoreErrors) { + error(right, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + } + return undefined; + } + } + else { + ts.Debug.fail("Unknown entity name kind."); + } + ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + return symbol.flags & meaning ? symbol : resolveAlias(symbol); + } + function resolveExternalModuleName(location, moduleReferenceExpression) { + if (moduleReferenceExpression.kind !== 9 /* StringLiteral */) { + return; + } + var moduleReferenceLiteral = moduleReferenceExpression; + var searchPath = ts.getDirectoryPath(getSourceFile(location).fileName); + // Module names are escaped in our symbol table. However, string literal values aren't. + // Escape the name in the "require(...)" clause to ensure we find the right symbol. + var moduleName = ts.escapeIdentifier(moduleReferenceLiteral.text); + if (moduleName === undefined) { + return; + } + var isRelative = ts.isExternalModuleNameRelative(moduleName); + if (!isRelative) { + var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512 /* ValueModule */); + if (symbol) { + return symbol; + } + } + var resolvedModule = ts.getResolvedModule(getSourceFile(location), moduleReferenceLiteral.text); + var sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); + if (sourceFile) { + if (sourceFile.symbol) { + return sourceFile.symbol; + } + error(moduleReferenceLiteral, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + return; + } + error(moduleReferenceLiteral, ts.Diagnostics.Cannot_find_module_0, moduleName); + } + // An external module with an 'export =' declaration resolves to the target of the 'export =' declaration, + // and an external module with no 'export =' declaration resolves to the module itself. + function resolveExternalModuleSymbol(moduleSymbol) { + return moduleSymbol && resolveSymbol(moduleSymbol.exports["export="]) || moduleSymbol; + } + // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export =' + // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may + // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable). + function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression) { + var symbol = resolveExternalModuleSymbol(moduleSymbol); + if (symbol && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { + error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + symbol = undefined; + } + return symbol; + } + function getExportAssignmentSymbol(moduleSymbol) { + return moduleSymbol.exports["export="]; + } + function getExportsOfModuleAsArray(moduleSymbol) { + return symbolsToArray(getExportsOfModule(moduleSymbol)); + } + function getExportsOfSymbol(symbol) { + return symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; + } + function getExportsOfModule(moduleSymbol) { + var links = getSymbolLinks(moduleSymbol); + return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol)); + } + function extendExportSymbols(target, source) { + for (var id in source) { + if (id !== "default" && !ts.hasProperty(target, id)) { + target[id] = source[id]; + } + } + } + function getExportsForModule(moduleSymbol) { + var result; + var visitedSymbols = []; + visit(moduleSymbol); + return result || moduleSymbol.exports; + // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, + // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. + function visit(symbol) { + if (symbol && symbol.flags & 1952 /* HasExports */ && !ts.contains(visitedSymbols, symbol)) { + visitedSymbols.push(symbol); + if (symbol !== moduleSymbol) { + if (!result) { + result = cloneSymbolTable(moduleSymbol.exports); + } + extendExportSymbols(result, symbol.exports); + } + // All export * declarations are collected in an __export symbol by the binder + var exportStars = symbol.exports["__export"]; + if (exportStars) { + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + visit(resolveExternalModuleName(node, node.moduleSpecifier)); + } + } + } + } + } + function getMergedSymbol(symbol) { + var merged; + return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; + } + function getSymbolOfNode(node) { + return getMergedSymbol(node.symbol); + } + function getParentOfSymbol(symbol) { + return getMergedSymbol(symbol.parent); + } + function getExportSymbolOfValueSymbolIfExported(symbol) { + return symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 + ? getMergedSymbol(symbol.exportSymbol) + : symbol; + } + function symbolIsValue(symbol) { + // If it is an instantiated symbol, then it is a value if the symbol it is an + // instantiation of is a value. + if (symbol.flags & 16777216 /* Instantiated */) { + return symbolIsValue(getSymbolLinks(symbol).target); + } + // If the symbol has the value flag, it is trivially a value. + if (symbol.flags & 107455 /* Value */) { + return true; + } + // If it is an alias, then it is a value if the symbol it resolves to is a value. + if (symbol.flags & 8388608 /* Alias */) { + return (resolveAlias(symbol).flags & 107455 /* Value */) !== 0; + } + return false; + } + function findConstructorDeclaration(node) { + var members = node.members; + for (var _i = 0; _i < members.length; _i++) { + var member = members[_i]; + if (member.kind === 144 /* Constructor */ && ts.nodeIsPresent(member.body)) { + return member; + } + } + } + function createType(flags) { + var result = new Type(checker, flags); + result.id = typeCount++; + return result; + } + function createIntrinsicType(kind, intrinsicName) { + var type = createType(kind); + type.intrinsicName = intrinsicName; + return type; + } + function createObjectType(kind, symbol) { + var type = createType(kind); + type.symbol = symbol; + return type; + } + // A reserved member name starts with two underscores, but the third character cannot be an underscore + // or the @ symbol. A third underscore indicates an escaped form of an identifer that started + // with at least two underscores. The @ character indicates that the name is denoted by a well known ES + // Symbol instance. + function isReservedMemberName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) !== 95 /* _ */ && + name.charCodeAt(2) !== 64 /* at */; + } + function getNamedMembers(members) { + var result; + for (var id in members) { + if (ts.hasProperty(members, id)) { + if (!isReservedMemberName(id)) { + if (!result) + result = []; + var symbol = members[id]; + if (symbolIsValue(symbol)) { + result.push(symbol); + } + } + } + } + return result || emptyArray; + } + function setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType) { + type.members = members; + type.properties = getNamedMembers(members); + type.callSignatures = callSignatures; + type.constructSignatures = constructSignatures; + if (stringIndexType) + type.stringIndexType = stringIndexType; + if (numberIndexType) + type.numberIndexType = numberIndexType; + return type; + } + function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexType, numberIndexType) { + return setObjectTypeMembers(createObjectType(65536 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexType, numberIndexType); + } + function forEachSymbolTableInScope(enclosingDeclaration, callback) { + var result; + for (var location_1 = enclosingDeclaration; location_1; location_1 = location_1.parent) { + // Locals of a source file are not in scope (because they get merged into the global symbol table) + if (location_1.locals && !isGlobalSourceFile(location_1)) { + if (result = callback(location_1.locals)) { + return result; + } + } + switch (location_1.kind) { + case 248 /* SourceFile */: + if (!ts.isExternalModule(location_1)) { + break; + } + case 218 /* ModuleDeclaration */: + if (result = callback(getSymbolOfNode(location_1).exports)) { + return result; + } + break; + case 214 /* ClassDeclaration */: + case 215 /* InterfaceDeclaration */: + if (result = callback(getSymbolOfNode(location_1).members)) { + return result; + } + break; + } + } + return callback(globals); + } + function getQualifiedLeftMeaning(rightMeaning) { + // If we are looking in value space, the parent meaning is value, other wise it is namespace + return rightMeaning === 107455 /* Value */ ? 107455 /* Value */ : 1536 /* Namespace */; + } + function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { + function getAccessibleSymbolChainFromSymbolTable(symbols) { + function canQualifySymbol(symbolFromSymbolTable, meaning) { + // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible + if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { + return true; + } + // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too + var accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); + return !!accessibleParent; + } + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { + if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { + // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) + // and if symbolfrom symbolTable or alias resolution matches the symbol, + // check the symbol can be qualified, it is only then this symbol is accessible + return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + canQualifySymbol(symbolFromSymbolTable, meaning); + } + } + // If symbol is directly available by its name in the symbol table + if (isAccessible(ts.lookUp(symbols, symbol.name))) { + return [symbol]; + } + // Check if symbol is any of the alias + return ts.forEachValue(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 8388608 /* Alias */ + && symbolFromSymbolTable.name !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 230 /* ExportSpecifier */)) { + if (!useOnlyExternalAliasing || + // Is this external alias, then use it to name + ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { + return [symbolFromSymbolTable]; + } + // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain + // but only if the symbolFromSymbolTable can be qualified + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } + } + } + }); + } + if (symbol) { + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + } + } + function needsQualification(symbol, enclosingDeclaration, meaning) { + var qualify = false; + forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { + // If symbol of this name is not available in the symbol table we are ok + if (!ts.hasProperty(symbolTable, symbol.name)) { + // Continue to the next symbol table + return false; + } + // If the symbol with this name is present it should refer to the symbol + var symbolFromSymbolTable = symbolTable[symbol.name]; + if (symbolFromSymbolTable === symbol) { + // No need to qualify + return true; + } + // Qualify if the symbol from symbol table has same meaning as expected + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 230 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + if (symbolFromSymbolTable.flags & meaning) { + qualify = true; + return true; + } + // Continue to the next symbol table + return false; + }); + return qualify; + } + function isSymbolAccessible(symbol, enclosingDeclaration, meaning) { + if (symbol && enclosingDeclaration && !(symbol.flags & 262144 /* TypeParameter */)) { + var initialSymbol = symbol; + var meaningToLook = meaning; + while (symbol) { + // Symbol is accessible if it by itself is accessible + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); + if (accessibleSymbolChain) { + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); + if (!hasAccessibleDeclarations) { + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1536 /* Namespace */) : undefined + }; + } + return hasAccessibleDeclarations; + } + // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. + // It could be a qualified symbol and hence verify the path + // e.g.: + // module m { + // export class c { + // } + // } + // let x: typeof m.c + // In the above example when we start with checking if typeof m.c symbol is accessible, + // we are going to see if c can be accessed in scope directly. + // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible + // It is accessible if the parent m is accessible because then m.c can be accessed through qualification + meaningToLook = getQualifiedLeftMeaning(meaning); + symbol = getParentOfSymbol(symbol); + } + // This could be a symbol that is not exported in the external module + // or it could be a symbol from different external module that is not aliased and hence cannot be named + var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); + if (symbolExternalModule) { + var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); + if (symbolExternalModule !== enclosingExternalModule) { + // name from different external module that is not visible + return { + accessibility: 2 /* CannotBeNamed */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: symbolToString(symbolExternalModule) + }; + } + } + // Just a local name that is not accessible + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning) + }; + } + return { accessibility: 0 /* Accessible */ }; + function getExternalModuleContainer(declaration) { + for (; declaration; declaration = declaration.parent) { + if (hasExternalModuleSymbol(declaration)) { + return getSymbolOfNode(declaration); + } + } + } + } + function hasExternalModuleSymbol(declaration) { + return (declaration.kind === 218 /* ModuleDeclaration */ && declaration.name.kind === 9 /* StringLiteral */) || + (declaration.kind === 248 /* SourceFile */ && ts.isExternalModule(declaration)); + } + function hasVisibleDeclarations(symbol) { + var aliasesToMakeVisible; + if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { + return undefined; + } + return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible }; + function getIsDeclarationVisible(declaration) { + if (!isDeclarationVisible(declaration)) { + // Mark the unexported alias as visible if its parent is visible + // because these kind of aliases can be used to name types in declaration file + var anyImportSyntax = getAnyImportSyntax(declaration); + if (anyImportSyntax && + !(anyImportSyntax.flags & 1 /* Export */) && + isDeclarationVisible(anyImportSyntax.parent)) { + getNodeLinks(declaration).isVisible = true; + if (aliasesToMakeVisible) { + if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { + aliasesToMakeVisible.push(anyImportSyntax); + } + } + else { + aliasesToMakeVisible = [anyImportSyntax]; + } + return true; + } + // Declaration is not visible + return false; + } + return true; + } + } + function isEntityNameVisible(entityName, enclosingDeclaration) { + // get symbol of the first identifier of the entityName + var meaning; + if (entityName.parent.kind === 154 /* TypeQuery */) { + // Typeof value + meaning = 107455 /* Value */ | 1048576 /* ExportValue */; + } + else if (entityName.kind === 135 /* QualifiedName */ || entityName.kind === 166 /* PropertyAccessExpression */ || + entityName.parent.kind === 221 /* ImportEqualsDeclaration */) { + // Left identifier from type reference or TypeAlias + // Entity name of the import declaration + meaning = 1536 /* Namespace */; + } + else { + // Type Reference or TypeAlias entity = Identifier + meaning = 793056 /* Type */; + } + var firstIdentifier = getFirstIdentifier(entityName); + var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); + // Verify if the symbol is accessible + return (symbol && hasVisibleDeclarations(symbol)) || { + accessibility: 1 /* NotAccessible */, + errorSymbolName: ts.getTextOfNode(firstIdentifier), + errorNode: firstIdentifier + }; + } + function writeKeyword(writer, kind) { + writer.writeKeyword(ts.tokenToString(kind)); + } + function writePunctuation(writer, kind) { + writer.writePunctuation(ts.tokenToString(kind)); + } + function writeSpace(writer) { + writer.writeSpace(" "); + } + function symbolToString(symbol, enclosingDeclaration, meaning) { + var writer = ts.getSingleLineStringWriter(); + getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); + var result = writer.string(); + ts.releaseStringWriter(writer); + return result; + } + function signatureToString(signature, enclosingDeclaration, flags) { + var writer = ts.getSingleLineStringWriter(); + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + var result = writer.string(); + ts.releaseStringWriter(writer); + return result; + } + function typeToString(type, enclosingDeclaration, flags) { + var writer = ts.getSingleLineStringWriter(); + getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + var result = writer.string(); + ts.releaseStringWriter(writer); + var maxLength = compilerOptions.noErrorTruncation || flags & 4 /* NoTruncation */ ? undefined : 100; + if (maxLength && result.length >= maxLength) { + result = result.substr(0, maxLength - "...".length) + "..."; + } + return result; + } + function getTypeAliasForTypeLiteral(type) { + if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { + var node = type.symbol.declarations[0].parent; + while (node.kind === 160 /* ParenthesizedType */) { + node = node.parent; + } + if (node.kind === 216 /* TypeAliasDeclaration */) { + return getSymbolOfNode(node); + } + } + return undefined; + } + function getSymbolDisplayBuilder() { + function getNameOfSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { + var declaration = symbol.declarations[0]; + if (declaration.name) { + return ts.declarationNameToString(declaration.name); + } + switch (declaration.kind) { + case 186 /* ClassExpression */: + return "(Anonymous class)"; + case 173 /* FunctionExpression */: + case 174 /* ArrowFunction */: + return "(Anonymous function)"; + } + } + return symbol.name; + } + /** + * Writes only the name of the symbol out to the writer. Uses the original source text + * for the name of the symbol if it is available to match how the user inputted the name. + */ + function appendSymbolNameOnly(symbol, writer) { + writer.writeSymbol(getNameOfSymbol(symbol), symbol); + } + /** + * Enclosing declaration is optional when we don't want to get qualified name in the enclosing declaration scope + * Meaning needs to be specified if the enclosing declaration is given + */ + function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { + var parentSymbol; + function appendParentTypeArgumentsAndSymbolName(symbol) { + if (parentSymbol) { + // Write type arguments of instantiated class/interface here + if (flags & 1 /* WriteTypeParametersOrArguments */) { + if (symbol.flags & 16777216 /* Instantiated */) { + buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); + } + else { + buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); + } + } + writePunctuation(writer, 21 /* DotToken */); + } + parentSymbol = symbol; + appendSymbolNameOnly(symbol, writer); + } + // Let the writer know we just wrote out a symbol. The declaration emitter writer uses + // this to determine if an import it has previously seen (and not written out) needs + // to be written to the file once the walk of the tree is complete. + // + // NOTE(cyrusn): This approach feels somewhat unfortunate. A simple pass over the tree + // up front (for example, during checking) could determine if we need to emit the imports + // and we could then access that data during declaration emit. + writer.trackSymbol(symbol, enclosingDeclaration, meaning); + function walkSymbol(symbol, meaning) { + if (symbol) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2 /* UseOnlyExternalAliasing */)); + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + // Go up and add our parent. + walkSymbol(getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol), getQualifiedLeftMeaning(meaning)); + } + if (accessibleSymbolChain) { + for (var _i = 0; _i < accessibleSymbolChain.length; _i++) { + var accessibleSymbol = accessibleSymbolChain[_i]; + appendParentTypeArgumentsAndSymbolName(accessibleSymbol); + } + } + else { + // If we didn't find accessible symbol chain for this symbol, break if this is external module + if (!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) { + return; + } + // if this is anonymous type break + if (symbol.flags & 2048 /* TypeLiteral */ || symbol.flags & 4096 /* ObjectLiteral */) { + return; + } + appendParentTypeArgumentsAndSymbolName(symbol); + } + } + } + // Get qualified name if the symbol is not a type parameter + // and there is an enclosing declaration or we specifically + // asked for it + var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; + var typeFormatFlag = 128 /* UseFullyQualifiedType */ & typeFlags; + if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { + walkSymbol(symbol, meaning); + return; + } + return appendParentTypeArgumentsAndSymbolName(symbol); + } + function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { + var globalFlagsToPass = globalFlags & 16 /* WriteOwnNameForAnyLike */; + var inObjectTypeLiteral = false; + return writeType(type, globalFlags); + function writeType(type, flags) { + // Write undefined/null type as any + if (type.flags & 16777343 /* Intrinsic */) { + // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving + writer.writeKeyword(!(globalFlags & 16 /* WriteOwnNameForAnyLike */) && isTypeAny(type) + ? "any" + : type.intrinsicName); + } + else if (type.flags & 33554432 /* ThisType */) { + if (inObjectTypeLiteral) { + writer.reportInaccessibleThisError(); + } + writer.writeKeyword("this"); + } + else if (type.flags & 4096 /* Reference */) { + writeTypeReference(type, flags); + } + else if (type.flags & (1024 /* Class */ | 2048 /* Interface */ | 128 /* Enum */ | 512 /* TypeParameter */)) { + // The specified symbol flags need to be reinterpreted as type flags + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793056 /* Type */, 0 /* None */, flags); + } + else if (type.flags & 8192 /* Tuple */) { + writeTupleType(type); + } + else if (type.flags & 49152 /* UnionOrIntersection */) { + writeUnionOrIntersectionType(type, flags); + } + else if (type.flags & 65536 /* Anonymous */) { + writeAnonymousType(type, flags); + } + else if (type.flags & 256 /* StringLiteral */) { + writer.writeStringLiteral(type.text); + } + else { + // Should never get here + // { ... } + writePunctuation(writer, 15 /* OpenBraceToken */); + writeSpace(writer); + writePunctuation(writer, 22 /* DotDotDotToken */); + writeSpace(writer); + writePunctuation(writer, 16 /* CloseBraceToken */); + } + } + function writeTypeList(types, delimiter) { + for (var i = 0; i < types.length; i++) { + if (i > 0) { + if (delimiter !== 24 /* CommaToken */) { + writeSpace(writer); + } + writePunctuation(writer, delimiter); + writeSpace(writer); + } + writeType(types[i], delimiter === 24 /* CommaToken */ ? 0 /* None */ : 64 /* InElementType */); + } + } + function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { + // Unnamed function expressions and arrow functions have reserved names that we don't want to display + if (symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.name)) { + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793056 /* Type */, 0 /* None */, flags); + } + if (pos < end) { + writePunctuation(writer, 25 /* LessThanToken */); + writeType(typeArguments[pos++], 0 /* None */); + while (pos < end) { + writePunctuation(writer, 24 /* CommaToken */); + writeSpace(writer); + writeType(typeArguments[pos++], 0 /* None */); + } + writePunctuation(writer, 27 /* GreaterThanToken */); + } + } + function writeTypeReference(type, flags) { + var typeArguments = type.typeArguments || emptyArray; + if (type.target === globalArrayType && !(flags & 1 /* WriteArrayAsGenericType */)) { + writeType(typeArguments[0], 64 /* InElementType */); + writePunctuation(writer, 19 /* OpenBracketToken */); + writePunctuation(writer, 20 /* CloseBracketToken */); + } + else { + // Write the type reference in the format f.g.C where A and B are type arguments + // for outer type parameters, and f and g are the respective declaring containers of those + // type parameters. + var outerTypeParameters = type.target.outerTypeParameters; + var i = 0; + if (outerTypeParameters) { + var length_1 = outerTypeParameters.length; + while (i < length_1) { + // Find group of type arguments for type parameters with the same declaring container. + var start = i; + var parent_3 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_3); + // When type parameters are their own type arguments for the whole group (i.e. we have + // the default outer type arguments), we don't show the group. + if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { + writeSymbolTypeReference(parent_3, typeArguments, start, i, flags); + writePunctuation(writer, 21 /* DotToken */); + } + } + } + var typeParameterCount = (type.target.typeParameters || emptyArray).length; + writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); + } + } + function writeTupleType(type) { + writePunctuation(writer, 19 /* OpenBracketToken */); + writeTypeList(type.elementTypes, 24 /* CommaToken */); + writePunctuation(writer, 20 /* CloseBracketToken */); + } + function writeUnionOrIntersectionType(type, flags) { + if (flags & 64 /* InElementType */) { + writePunctuation(writer, 17 /* OpenParenToken */); + } + writeTypeList(type.types, type.flags & 16384 /* Union */ ? 47 /* BarToken */ : 46 /* AmpersandToken */); + if (flags & 64 /* InElementType */) { + writePunctuation(writer, 18 /* CloseParenToken */); + } + } + function writeAnonymousType(type, flags) { + var symbol = type.symbol; + if (symbol) { + // Always use 'typeof T' for type of class, enum, and module objects + if (symbol.flags & (32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + writeTypeofSymbol(type, flags); + } + else if (shouldWriteTypeOfFunctionSymbol()) { + writeTypeofSymbol(type, flags); + } + else if (ts.contains(symbolStack, symbol)) { + // If type is an anonymous type literal in a type alias declaration, use type alias name + var typeAlias = getTypeAliasForTypeLiteral(type); + if (typeAlias) { + // The specified symbol flags need to be reinterpreted as type flags + buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793056 /* Type */, 0 /* None */, flags); + } + else { + // Recursive usage, use any + writeKeyword(writer, 117 /* AnyKeyword */); + } + } + else { + // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead + // of types allows us to catch circular references to instantiations of the same anonymous type + if (!symbolStack) { + symbolStack = []; + } + symbolStack.push(symbol); + writeLiteralType(type, flags); + symbolStack.pop(); + } + } + else { + // Anonymous types with no symbol are never circular + writeLiteralType(type, flags); + } + function shouldWriteTypeOfFunctionSymbol() { + var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && + ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 128 /* Static */; })); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && + (symbol.parent || + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 248 /* SourceFile */ || declaration.parent.kind === 219 /* ModuleBlock */; + })); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + // typeof is allowed only for static/non local functions + return !!(flags & 2 /* UseTypeOfFunction */) || + (ts.contains(symbolStack, symbol)); // it is type of the symbol uses itself recursively + } + } + } + function writeTypeofSymbol(type, typeFormatFlags) { + writeKeyword(writer, 101 /* TypeOfKeyword */); + writeSpace(writer); + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); + } + function getIndexerParameterName(type, indexKind, fallbackName) { + var declaration = getIndexDeclarationOfSymbol(type.symbol, indexKind); + if (!declaration) { + // declaration might not be found if indexer was added from the contextual type. + // in this case use fallback name + return fallbackName; + } + ts.Debug.assert(declaration.parameters.length !== 0); + return ts.declarationNameToString(declaration.parameters[0].name); + } + function writeLiteralType(type, flags) { + var resolved = resolveStructuredTypeMembers(type); + if (!resolved.properties.length && !resolved.stringIndexType && !resolved.numberIndexType) { + if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + writePunctuation(writer, 15 /* OpenBraceToken */); + writePunctuation(writer, 16 /* CloseBraceToken */); + return; + } + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { + if (flags & 64 /* InElementType */) { + writePunctuation(writer, 17 /* OpenParenToken */); + } + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, symbolStack); + if (flags & 64 /* InElementType */) { + writePunctuation(writer, 18 /* CloseParenToken */); + } + return; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { + if (flags & 64 /* InElementType */) { + writePunctuation(writer, 17 /* OpenParenToken */); + } + writeKeyword(writer, 92 /* NewKeyword */); + writeSpace(writer); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, symbolStack); + if (flags & 64 /* InElementType */) { + writePunctuation(writer, 18 /* CloseParenToken */); + } + return; + } + } + var saveInObjectTypeLiteral = inObjectTypeLiteral; + inObjectTypeLiteral = true; + writePunctuation(writer, 15 /* OpenBraceToken */); + writer.writeLine(); + writer.increaseIndent(); + for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + writePunctuation(writer, 23 /* SemicolonToken */); + writer.writeLine(); + } + for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + writeKeyword(writer, 92 /* NewKeyword */); + writeSpace(writer); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + writePunctuation(writer, 23 /* SemicolonToken */); + writer.writeLine(); + } + if (resolved.stringIndexType) { + // [x: string]: + writePunctuation(writer, 19 /* OpenBracketToken */); + writer.writeParameter(getIndexerParameterName(resolved, 0 /* String */, /*fallbackName*/ "x")); + writePunctuation(writer, 54 /* ColonToken */); + writeSpace(writer); + writeKeyword(writer, 130 /* StringKeyword */); + writePunctuation(writer, 20 /* CloseBracketToken */); + writePunctuation(writer, 54 /* ColonToken */); + writeSpace(writer); + writeType(resolved.stringIndexType, 0 /* None */); + writePunctuation(writer, 23 /* SemicolonToken */); + writer.writeLine(); + } + if (resolved.numberIndexType) { + // [x: number]: + writePunctuation(writer, 19 /* OpenBracketToken */); + writer.writeParameter(getIndexerParameterName(resolved, 1 /* Number */, /*fallbackName*/ "x")); + writePunctuation(writer, 54 /* ColonToken */); + writeSpace(writer); + writeKeyword(writer, 128 /* NumberKeyword */); + writePunctuation(writer, 20 /* CloseBracketToken */); + writePunctuation(writer, 54 /* ColonToken */); + writeSpace(writer); + writeType(resolved.numberIndexType, 0 /* None */); + writePunctuation(writer, 23 /* SemicolonToken */); + writer.writeLine(); + } + for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { + var p = _e[_d]; + var t = getTypeOfSymbol(p); + if (p.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(t).length) { + var signatures = getSignaturesOfType(t, 0 /* Call */); + for (var _f = 0; _f < signatures.length; _f++) { + var signature = signatures[_f]; + buildSymbolDisplay(p, writer); + if (p.flags & 536870912 /* Optional */) { + writePunctuation(writer, 53 /* QuestionToken */); + } + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + writePunctuation(writer, 23 /* SemicolonToken */); + writer.writeLine(); + } + } + else { + buildSymbolDisplay(p, writer); + if (p.flags & 536870912 /* Optional */) { + writePunctuation(writer, 53 /* QuestionToken */); + } + writePunctuation(writer, 54 /* ColonToken */); + writeSpace(writer); + writeType(t, 0 /* None */); + writePunctuation(writer, 23 /* SemicolonToken */); + writer.writeLine(); + } + } + writer.decreaseIndent(); + writePunctuation(writer, 16 /* CloseBraceToken */); + inObjectTypeLiteral = saveInObjectTypeLiteral; + } + } + function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaraiton, flags) { + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & 32 /* Class */ || targetSymbol.flags & 64 /* Interface */ || targetSymbol.flags & 524288 /* TypeAlias */) { + buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaraiton, flags); + } + } + function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { + appendSymbolNameOnly(tp.symbol, writer); + var constraint = getConstraintOfTypeParameter(tp); + if (constraint) { + writeSpace(writer); + writeKeyword(writer, 83 /* ExtendsKeyword */); + writeSpace(writer); + buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); + } + } + function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { + var parameterNode = p.valueDeclaration; + if (ts.isRestParameter(parameterNode)) { + writePunctuation(writer, 22 /* DotDotDotToken */); + } + appendSymbolNameOnly(p, writer); + if (isOptionalParameter(parameterNode)) { + writePunctuation(writer, 53 /* QuestionToken */); + } + writePunctuation(writer, 54 /* ColonToken */); + writeSpace(writer); + buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack); + } + function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { + if (typeParameters && typeParameters.length) { + writePunctuation(writer, 25 /* LessThanToken */); + for (var i = 0; i < typeParameters.length; i++) { + if (i > 0) { + writePunctuation(writer, 24 /* CommaToken */); + writeSpace(writer); + } + buildTypeParameterDisplay(typeParameters[i], writer, enclosingDeclaration, flags, symbolStack); + } + writePunctuation(writer, 27 /* GreaterThanToken */); + } + } + function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration, flags, symbolStack) { + if (typeParameters && typeParameters.length) { + writePunctuation(writer, 25 /* LessThanToken */); + for (var i = 0; i < typeParameters.length; i++) { + if (i > 0) { + writePunctuation(writer, 24 /* CommaToken */); + writeSpace(writer); + } + buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, 0 /* None */); + } + writePunctuation(writer, 27 /* GreaterThanToken */); + } + } + function buildDisplayForParametersAndDelimiters(parameters, writer, enclosingDeclaration, flags, symbolStack) { + writePunctuation(writer, 17 /* OpenParenToken */); + for (var i = 0; i < parameters.length; i++) { + if (i > 0) { + writePunctuation(writer, 24 /* CommaToken */); + writeSpace(writer); + } + buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); + } + writePunctuation(writer, 18 /* CloseParenToken */); + } + function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { + if (flags & 8 /* WriteArrowStyleSignature */) { + writeSpace(writer); + writePunctuation(writer, 34 /* EqualsGreaterThanToken */); + } + else { + writePunctuation(writer, 54 /* ColonToken */); + } + writeSpace(writer); + var returnType; + if (signature.typePredicate) { + writer.writeParameter(signature.typePredicate.parameterName); + writeSpace(writer); + writeKeyword(writer, 124 /* IsKeyword */); + writeSpace(writer); + returnType = signature.typePredicate.type; + } + else { + returnType = getReturnTypeOfSignature(signature); + } + buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); + } + function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { + if (signature.target && (flags & 32 /* WriteTypeArgumentsOfSignature */)) { + // Instantiated signature, write type arguments instead + // This is achieved by passing in the mapper separately + buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); + } + else { + buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); + } + buildDisplayForParametersAndDelimiters(signature.parameters, writer, enclosingDeclaration, flags, symbolStack); + buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); + } + return _displayBuilder || (_displayBuilder = { + buildSymbolDisplay: buildSymbolDisplay, + buildTypeDisplay: buildTypeDisplay, + buildTypeParameterDisplay: buildTypeParameterDisplay, + buildParameterDisplay: buildParameterDisplay, + buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, + buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, + buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, + buildSignatureDisplay: buildSignatureDisplay, + buildReturnTypeDisplay: buildReturnTypeDisplay + }); + } + function isDeclarationVisible(node) { + function getContainingExternalModule(node) { + for (; node; node = node.parent) { + if (node.kind === 218 /* ModuleDeclaration */) { + if (node.name.kind === 9 /* StringLiteral */) { + return node; + } + } + else if (node.kind === 248 /* SourceFile */) { + return ts.isExternalModule(node) ? node : undefined; + } + } + ts.Debug.fail("getContainingModule cant reach here"); + } + function isUsedInExportAssignment(node) { + // Get source File and see if it is external module and has export assigned symbol + var externalModule = getContainingExternalModule(node); + var exportAssignmentSymbol; + var resolvedExportSymbol; + if (externalModule) { + // This is export assigned symbol node + var externalModuleSymbol = getSymbolOfNode(externalModule); + exportAssignmentSymbol = getExportAssignmentSymbol(externalModuleSymbol); + var symbolOfNode = getSymbolOfNode(node); + if (isSymbolUsedInExportAssignment(symbolOfNode)) { + return true; + } + // if symbolOfNode is alias declaration, resolve the symbol declaration and check + if (symbolOfNode.flags & 8388608 /* Alias */) { + return isSymbolUsedInExportAssignment(resolveAlias(symbolOfNode)); + } + } + // Check if the symbol is used in export assignment + function isSymbolUsedInExportAssignment(symbol) { + if (exportAssignmentSymbol === symbol) { + return true; + } + if (exportAssignmentSymbol && !!(exportAssignmentSymbol.flags & 8388608 /* Alias */)) { + // if export assigned symbol is alias declaration, resolve the alias + resolvedExportSymbol = resolvedExportSymbol || resolveAlias(exportAssignmentSymbol); + if (resolvedExportSymbol === symbol) { + return true; + } + // Container of resolvedExportSymbol is visible + return ts.forEach(resolvedExportSymbol.declarations, function (current) { + while (current) { + if (current === node) { + return true; + } + current = current.parent; + } + }); + } + } + } + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 163 /* BindingElement */: + return isDeclarationVisible(node.parent.parent); + case 211 /* VariableDeclaration */: + if (ts.isBindingPattern(node.name) && + !node.name.elements.length) { + // If the binding pattern is empty, this variable declaration is not visible + return false; + } + // Otherwise fall through + case 218 /* ModuleDeclaration */: + case 214 /* ClassDeclaration */: + case 215 /* InterfaceDeclaration */: + case 216 /* TypeAliasDeclaration */: + case 213 /* FunctionDeclaration */: + case 217 /* EnumDeclaration */: + case 221 /* ImportEqualsDeclaration */: + var parent_4 = getDeclarationContainer(node); + // If the node is not exported or it is not ambient module element (except import declaration) + if (!(ts.getCombinedNodeFlags(node) & 1 /* Export */) && + !(node.kind !== 221 /* ImportEqualsDeclaration */ && parent_4.kind !== 248 /* SourceFile */ && ts.isInAmbientContext(parent_4))) { + return isGlobalSourceFile(parent_4); + } + // Exported members/ambient module elements (exception import declaration) are visible if parent is visible + return isDeclarationVisible(parent_4); + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + if (node.flags & (32 /* Private */ | 64 /* Protected */)) { + // Private/protected properties/methods are not visible + return false; + } + // Public properties/methods are visible if its parents are visible, so let it fall into next case statement + case 144 /* Constructor */: + case 148 /* ConstructSignature */: + case 147 /* CallSignature */: + case 149 /* IndexSignature */: + case 138 /* Parameter */: + case 219 /* ModuleBlock */: + case 152 /* FunctionType */: + case 153 /* ConstructorType */: + case 155 /* TypeLiteral */: + case 151 /* TypeReference */: + case 156 /* ArrayType */: + case 157 /* TupleType */: + case 158 /* UnionType */: + case 159 /* IntersectionType */: + case 160 /* ParenthesizedType */: + return isDeclarationVisible(node.parent); + // Default binding, import specifier and namespace import is visible + // only on demand so by default it is not visible + case 223 /* ImportClause */: + case 224 /* NamespaceImport */: + case 226 /* ImportSpecifier */: + return false; + // Type parameters are always visible + case 137 /* TypeParameter */: + // Source file is always visible + case 248 /* SourceFile */: + return true; + // Export assignements do not create name bindings outside the module + case 227 /* ExportAssignment */: + return false; + default: + ts.Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + node.kind); + } + } + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); + } + return links.isVisible; + } + } + function collectLinkedAliases(node) { + var exportSymbol; + if (node.parent && node.parent.kind === 227 /* ExportAssignment */) { + exportSymbol = resolveName(node.parent, node.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); + } + else if (node.parent.kind === 230 /* ExportSpecifier */) { + var exportSpecifier = node.parent; + exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? + getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : + resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); + } + var result = []; + if (exportSymbol) { + buildVisibleNodeList(exportSymbol.declarations); + } + return result; + function buildVisibleNodeList(declarations) { + ts.forEach(declarations, function (declaration) { + getNodeLinks(declaration).isVisible = true; + var resultNode = getAnyImportSyntax(declaration) || declaration; + if (!ts.contains(result, resultNode)) { + result.push(resultNode); + } + if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { + // Add the referenced top container visible + var internalModuleReference = declaration.moduleReference; + var firstIdentifier = getFirstIdentifier(internalModuleReference); + var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */, ts.Diagnostics.Cannot_find_name_0, firstIdentifier); + buildVisibleNodeList(importSymbol.declarations); + } + }); + } + } + /** + * Push an entry on the type resolution stack. If an entry with the given target and the given property name + * is already on the stack, and no entries in between already have a type, then a circularity has occurred. + * In this case, the result values of the existing entry and all entries pushed after it are changed to false, + * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned. + * In order to see if the same query has already been done before, the target object and the propertyName both + * must match the one passed in. + * + * @param target The symbol, type, or signature whose type is being queried + * @param propertyName The property name that should be used to query the target for its type + */ + function pushTypeResolution(target, propertyName) { + var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); + if (resolutionCycleStartIndex >= 0) { + // A cycle was found + var length_2 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_2; i++) { + resolutionResults[i] = false; + } + return false; + } + resolutionTargets.push(target); + resolutionResults.push(true); + resolutionPropertyNames.push(propertyName); + return true; + } + function findResolutionCycleStartIndex(target, propertyName) { + for (var i = resolutionTargets.length - 1; i >= 0; i--) { + if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { + return -1; + } + if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { + return i; + } + } + return -1; + } + function hasType(target, propertyName) { + if (propertyName === 0 /* Type */) { + return getSymbolLinks(target).type; + } + if (propertyName === 2 /* DeclaredType */) { + return getSymbolLinks(target).declaredType; + } + if (propertyName === 1 /* ResolvedBaseConstructorType */) { + ts.Debug.assert(!!(target.flags & 1024 /* Class */)); + return target.resolvedBaseConstructorType; + } + if (propertyName === 3 /* ResolvedReturnType */) { + return target.resolvedReturnType; + } + ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + } + // Pop an entry from the type resolution stack and return its associated result value. The result value will + // be true if no circularities were detected, or false if a circularity was found. + function popTypeResolution() { + resolutionTargets.pop(); + resolutionPropertyNames.pop(); + return resolutionResults.pop(); + } + function getDeclarationContainer(node) { + node = ts.getRootDeclaration(node); + // Parent chain: + // VaribleDeclaration -> VariableDeclarationList -> VariableStatement -> 'Declaration Container' + return node.kind === 211 /* VariableDeclaration */ ? node.parent.parent.parent : node.parent; + } + function getTypeOfPrototypeProperty(prototype) { + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', + // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. + // It is an error to explicitly declare a static property member with the name 'prototype'. + var classType = getDeclaredTypeOfSymbol(prototype.parent); + return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; + } + // Return the type of the given property in the given type, or undefined if no such property exists + function getTypeOfPropertyOfType(type, name) { + var prop = getPropertyOfType(type, name); + return prop ? getTypeOfSymbol(prop) : undefined; + } + function isTypeAny(type) { + return type && (type.flags & 1 /* Any */) !== 0; + } + // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been + // assigned by contextual typing. + function getTypeForBindingElementParent(node) { + var symbol = getSymbolOfNode(node); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node); + } + // Return the inferred type for a binding element + function getTypeForBindingElement(declaration) { + var pattern = declaration.parent; + var parentType = getTypeForBindingElementParent(pattern.parent); + // If parent has the unknown (error) type, then so does this binding element + if (parentType === unknownType) { + return unknownType; + } + // If no type was specified or inferred for parent, or if the specified or inferred type is any, + // infer from the initializer of the binding element if one is present. Otherwise, go with the + // undefined or any type of the parent. + if (!parentType || isTypeAny(parentType)) { + if (declaration.initializer) { + return checkExpressionCached(declaration.initializer); + } + return parentType; + } + var type; + if (pattern.kind === 161 /* ObjectBindingPattern */) { + // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) + var name_10 = declaration.propertyName || declaration.name; + // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, + // or otherwise the type of the string index signature. + type = getTypeOfPropertyOfType(parentType, name_10.text) || + isNumericLiteralName(name_10.text) && getIndexTypeOfType(parentType, 1 /* Number */) || + getIndexTypeOfType(parentType, 0 /* String */); + if (!type) { + error(name_10, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_10)); + return unknownType; + } + } + else { + // This elementType will be used if the specific property corresponding to this index is not + // present (aka the tuple element property). This call also checks that the parentType is in + // fact an iterable or array (depending on target language). + var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false); + if (!declaration.dotDotDotToken) { + // Use specific property type when parent is a tuple or numeric index type when parent is an array + var propName = "" + ts.indexOf(pattern.elements, declaration); + type = isTupleLikeType(parentType) + ? getTypeOfPropertyOfType(parentType, propName) + : elementType; + if (!type) { + if (isTupleType(parentType)) { + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), parentType.elementTypes.length, pattern.elements.length); + } + else { + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); + } + return unknownType; + } + } + else { + // Rest element has an array type with the same element type as the parent type + type = createArrayType(elementType); + } + } + return type; + } + // Return the inferred type for a variable, parameter, or property declaration + function getTypeForVariableLikeDeclaration(declaration) { + // A variable declared in a for..in statement is always of type any + if (declaration.parent.parent.kind === 200 /* ForInStatement */) { + return anyType; + } + if (declaration.parent.parent.kind === 201 /* ForOfStatement */) { + // checkRightHandSideOfForOf will return undefined if the for-of expression type was + // missing properties/signatures required to get its iteratedType (like + // [Symbol.iterator] or next). This may be because we accessed properties from anyType, + // or it may have led to an error inside getElementTypeOfIterable. + return checkRightHandSideOfForOf(declaration.parent.parent.expression) || anyType; + } + if (ts.isBindingPattern(declaration.parent)) { + return getTypeForBindingElement(declaration); + } + // Use type from type annotation if one is present + if (declaration.type) { + return getTypeFromTypeNode(declaration.type); + } + if (declaration.kind === 138 /* Parameter */) { + var func = declaration.parent; + // For a parameter of a set accessor, use the type of the get accessor if one is present + if (func.kind === 146 /* SetAccessor */ && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 145 /* GetAccessor */); + if (getter) { + return getReturnTypeOfSignature(getSignatureFromDeclaration(getter)); + } + } + // Use contextual parameter type if one is available + var type = getContextuallyTypedParameterType(declaration); + if (type) { + return type; + } + } + // Use the type of the initializer expression if one is present + if (declaration.initializer) { + return checkExpressionCached(declaration.initializer); + } + // If it is a short-hand property assignment, use the type of the identifier + if (declaration.kind === 246 /* ShorthandPropertyAssignment */) { + return checkIdentifier(declaration.name); + } + // If the declaration specifies a binding pattern, use the type implied by the binding pattern + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false); + } + // No type specified and nothing can be inferred + return undefined; + } + // Return the type implied by a binding pattern element. This is the type of the initializer of the element if + // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding + // pattern. Otherwise, it is the type any. + function getTypeFromBindingElement(element, includePatternInType) { + if (element.initializer) { + return getWidenedType(checkExpressionCached(element.initializer)); + } + if (ts.isBindingPattern(element.name)) { + return getTypeFromBindingPattern(element.name, includePatternInType); + } + return anyType; + } + // Return the type implied by an object binding pattern + function getTypeFromObjectBindingPattern(pattern, includePatternInType) { + var members = {}; + ts.forEach(pattern.elements, function (e) { + var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0); + var name = e.propertyName || e.name; + var symbol = createSymbol(flags, name.text); + symbol.type = getTypeFromBindingElement(e, includePatternInType); + symbol.bindingElement = e; + members[symbol.name] = symbol; + }); + var result = createAnonymousType(undefined, members, emptyArray, emptyArray, undefined, undefined); + if (includePatternInType) { + result.pattern = pattern; + } + return result; + } + // Return the type implied by an array binding pattern + function getTypeFromArrayBindingPattern(pattern, includePatternInType) { + var elements = pattern.elements; + if (elements.length === 0 || elements[elements.length - 1].dotDotDotToken) { + return languageVersion >= 2 /* ES6 */ ? createIterableType(anyType) : anyArrayType; + } + // If the pattern has at least one element, and no rest element, then it should imply a tuple type. + var elementTypes = ts.map(elements, function (e) { return e.kind === 187 /* OmittedExpression */ ? anyType : getTypeFromBindingElement(e, includePatternInType); }); + if (includePatternInType) { + var result = createNewTupleType(elementTypes); + result.pattern = pattern; + return result; + } + return createTupleType(elementTypes); + } + // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself + // and without regard to its context (i.e. without regard any type annotation or initializer associated with the + // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any] + // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is + // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring + // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of + // the parameter. + function getTypeFromBindingPattern(pattern, includePatternInType) { + return pattern.kind === 161 /* ObjectBindingPattern */ + ? getTypeFromObjectBindingPattern(pattern, includePatternInType) + : getTypeFromArrayBindingPattern(pattern, includePatternInType); + } + // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type + // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it + // is a bit more involved. For example: + // + // var [x, s = ""] = [1, "one"]; + // + // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the + // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the + // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. + function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { + var type = getTypeForVariableLikeDeclaration(declaration); + if (type) { + if (reportErrors) { + reportErrorsFromWidening(declaration, type); + } + // During a normal type check we'll never get to here with a property assignment (the check of the containing + // object literal uses a different path). We exclude widening only so that language services and type verification + // tools see the actual type. + return declaration.kind !== 245 /* PropertyAssignment */ ? getWidenedType(type) : type; + } + // Rest parameters default to type any[], other parameters default to type any + type = declaration.dotDotDotToken ? anyArrayType : anyType; + // Report implicit any errors unless this is a private property within an ambient declaration + if (reportErrors && compilerOptions.noImplicitAny) { + var root = ts.getRootDeclaration(declaration); + if (!isPrivateWithinAmbient(root) && !(root.kind === 138 /* Parameter */ && isPrivateWithinAmbient(root.parent))) { + reportImplicitAnyError(declaration, type); + } + } + return type; + } + function getTypeOfVariableOrParameterOrProperty(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + // Handle prototype property + if (symbol.flags & 134217728 /* Prototype */) { + return links.type = getTypeOfPrototypeProperty(symbol); + } + // Handle catch clause variables + var declaration = symbol.valueDeclaration; + if (declaration.parent.kind === 244 /* CatchClause */) { + return links.type = anyType; + } + // Handle export default expressions + if (declaration.kind === 227 /* ExportAssignment */) { + return links.type = checkExpression(declaration.expression); + } + // Handle variable, parameter or property + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return unknownType; + } + var type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); + if (!popTypeResolution()) { + if (symbol.valueDeclaration.type) { + // Variable has type annotation that circularly references the variable itself + type = unknownType; + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + } + else { + // Variable has initializer that circularly references the variable itself + type = anyType; + if (compilerOptions.noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + } + } + links.type = type; + } + return links.type; + } + function getAnnotatedAccessorType(accessor) { + if (accessor) { + if (accessor.kind === 145 /* GetAccessor */) { + return accessor.type && getTypeFromTypeNode(accessor.type); + } + else { + var setterTypeAnnotation = ts.getSetAccessorTypeAnnotationNode(accessor); + return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); + } + } + return undefined; + } + function getTypeOfAccessors(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return unknownType; + } + var getter = ts.getDeclarationOfKind(symbol, 145 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 146 /* SetAccessor */); + var type; + // First try to see if the user specified a return type on the get-accessor. + var getterReturnType = getAnnotatedAccessorType(getter); + if (getterReturnType) { + type = getterReturnType; + } + else { + // If the user didn't specify a return type, try to use the set-accessor's parameter type. + var setterParameterType = getAnnotatedAccessorType(setter); + if (setterParameterType) { + type = setterParameterType; + } + else { + // If there are no specified types, try to infer it from the body of the get accessor if it exists. + if (getter && getter.body) { + type = getReturnTypeFromBody(getter); + } + else { + if (compilerOptions.noImplicitAny) { + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation, symbolToString(symbol)); + } + type = anyType; + } + } + } + if (!popTypeResolution()) { + type = anyType; + if (compilerOptions.noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 145 /* GetAccessor */); + error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + } + } + links.type = type; + } + return links.type; + } + function getTypeOfFuncClassEnumModule(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = createObjectType(65536 /* Anonymous */, symbol); + } + return links.type; + } + function getTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); + } + return links.type; + } + function getTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + var targetSymbol = resolveAlias(symbol); + // It only makes sense to get the type of a value symbol. If the result of resolving + // the alias is not a value, then it has no type. To get the type associated with a + // type symbol, call getDeclaredTypeOfSymbol. + // This check is important because without it, a call to getTypeOfSymbol could end + // up recursively calling getTypeOfAlias, causing a stack overflow. + links.type = targetSymbol.flags & 107455 /* Value */ + ? getTypeOfSymbol(targetSymbol) + : unknownType; + } + return links.type; + } + function getTypeOfInstantiatedSymbol(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + } + return links.type; + } + function getTypeOfSymbol(symbol) { + if (symbol.flags & 16777216 /* Instantiated */) { + return getTypeOfInstantiatedSymbol(symbol); + } + if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { + return getTypeOfVariableOrParameterOrProperty(symbol); + } + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + if (symbol.flags & 8 /* EnumMember */) { + return getTypeOfEnumMember(symbol); + } + if (symbol.flags & 98304 /* Accessor */) { + return getTypeOfAccessors(symbol); + } + if (symbol.flags & 8388608 /* Alias */) { + return getTypeOfAlias(symbol); + } + return unknownType; + } + function getTargetType(type) { + return type.flags & 4096 /* Reference */ ? type.target : type; + } + function hasBaseType(type, checkBase) { + return check(type); + function check(type) { + var target = getTargetType(type); + return target === checkBase || ts.forEach(getBaseTypes(target), check); + } + } + // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set. + // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set + // in-place and returns the same array. + function appendTypeParameters(typeParameters, declarations) { + for (var _i = 0; _i < declarations.length; _i++) { + var declaration = declarations[_i]; + var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); + if (!typeParameters) { + typeParameters = [tp]; + } + else if (!ts.contains(typeParameters, tp)) { + typeParameters.push(tp); + } + } + return typeParameters; + } + // Appends the outer type parameters of a node to a set of type parameters and returns the resulting set. The function + // allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set in-place and + // returns the same array. + function appendOuterTypeParameters(typeParameters, node) { + while (true) { + node = node.parent; + if (!node) { + return typeParameters; + } + if (node.kind === 214 /* ClassDeclaration */ || node.kind === 186 /* ClassExpression */ || + node.kind === 213 /* FunctionDeclaration */ || node.kind === 173 /* FunctionExpression */ || + node.kind === 143 /* MethodDeclaration */ || node.kind === 174 /* ArrowFunction */) { + var declarations = node.typeParameters; + if (declarations) { + return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); + } + } + } + } + // The outer type parameters are those defined by enclosing generic classes, methods, or functions. + function getOuterTypeParametersOfClassOrInterface(symbol) { + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 215 /* InterfaceDeclaration */); + return appendOuterTypeParameters(undefined, declaration); + } + // The local type parameters are the combined set of type parameters from all declarations of the class, + // interface, or type alias. + function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + var result; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + if (node.kind === 215 /* InterfaceDeclaration */ || node.kind === 214 /* ClassDeclaration */ || + node.kind === 186 /* ClassExpression */ || node.kind === 216 /* TypeAliasDeclaration */) { + var declaration = node; + if (declaration.typeParameters) { + result = appendTypeParameters(result, declaration.typeParameters); + } + } + } + return result; + } + // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus + // its locally declared type parameters. + function getTypeParametersOfClassOrInterface(symbol) { + return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); + } + function isConstructorType(type) { + return type.flags & 80896 /* ObjectType */ && getSignaturesOfType(type, 1 /* Construct */).length > 0; + } + function getBaseTypeNodeOfClass(type) { + return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); + } + function getConstructorsForTypeArguments(type, typeArgumentNodes) { + var typeArgCount = typeArgumentNodes ? typeArgumentNodes.length : 0; + return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (sig.typeParameters ? sig.typeParameters.length : 0) === typeArgCount; }); + } + function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes) { + var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); + if (typeArgumentNodes) { + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments); }); + } + return signatures; + } + // The base constructor of a class can resolve to + // undefinedType if the class has no extends clause, + // unknownType if an error occurred during resolution of the extends expression, + // nullType if the extends expression is the null value, or + // an object type with at least one construct signature. + function getBaseConstructorTypeOfClass(type) { + if (!type.resolvedBaseConstructorType) { + var baseTypeNode = getBaseTypeNodeOfClass(type); + if (!baseTypeNode) { + return type.resolvedBaseConstructorType = undefinedType; + } + if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) { + return unknownType; + } + var baseConstructorType = checkExpression(baseTypeNode.expression); + if (baseConstructorType.flags & 80896 /* ObjectType */) { + // Resolving the members of a class requires us to resolve the base class of that class. + // We force resolution here such that we catch circularities now. + resolveStructuredTypeMembers(baseConstructorType); + } + if (!popTypeResolution()) { + error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); + return type.resolvedBaseConstructorType = unknownType; + } + if (baseConstructorType !== unknownType && baseConstructorType !== nullType && !isConstructorType(baseConstructorType)) { + error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + return type.resolvedBaseConstructorType = unknownType; + } + type.resolvedBaseConstructorType = baseConstructorType; + } + return type.resolvedBaseConstructorType; + } + function hasClassBaseType(type) { + return !!ts.forEach(getBaseTypes(type), function (t) { return !!(t.symbol.flags & 32 /* Class */); }); + } + function getBaseTypes(type) { + var isClass = type.symbol.flags & 32 /* Class */; + var isInterface = type.symbol.flags & 64 /* Interface */; + if (!type.resolvedBaseTypes) { + if (!isClass && !isInterface) { + ts.Debug.fail("type must be class or interface"); + } + if (isClass) { + resolveBaseTypesOfClass(type); + } + if (isInterface) { + resolveBaseTypesOfInterface(type); + } + } + return type.resolvedBaseTypes; + } + function resolveBaseTypesOfClass(type) { + type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; + var baseContructorType = getBaseConstructorTypeOfClass(type); + if (!(baseContructorType.flags & 80896 /* ObjectType */)) { + return; + } + var baseTypeNode = getBaseTypeNodeOfClass(type); + var baseType; + if (baseContructorType.symbol && baseContructorType.symbol.flags & 32 /* Class */) { + // When base constructor type is a class we know that the constructors all have the same type parameters as the + // class and all return the instance type of the class. There is no need for further checks and we can apply the + // type arguments in the same manner as a type reference to get the same error reporting experience. + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseContructorType.symbol); + } + else { + // The class derives from a "class-like" constructor function, check that we have at least one construct signature + // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere + // we check that all instantiated signatures return the same type. + var constructors = getInstantiatedConstructorsForTypeArguments(baseContructorType, baseTypeNode.typeArguments); + if (!constructors.length) { + error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); + return; + } + baseType = getReturnTypeOfSignature(constructors[0]); + } + if (baseType === unknownType) { + return; + } + if (!(getTargetType(baseType).flags & (1024 /* Class */ | 2048 /* Interface */))) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); + return; + } + if (type === baseType || hasBaseType(baseType, type)) { + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); + return; + } + if (type.resolvedBaseTypes === emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } + } + function resolveBaseTypesOfInterface(type) { + type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 215 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { + var node = _c[_b]; + var baseType = getTypeFromTypeNode(node); + if (baseType !== unknownType) { + if (getTargetType(baseType).flags & (1024 /* Class */ | 2048 /* Interface */)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } + } + else { + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); + } + } + else { + error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface); + } + } + } + } + } + } + // Returns true if the interface given by the symbol is free of "this" references. Specifically, the result is + // true if the interface itself contains no references to "this" in its body, if all base types are interfaces, + // and if none of the base interfaces have a "this" type. + function isIndependentInterface(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 215 /* InterfaceDeclaration */) { + if (declaration.flags & 524288 /* ContainsThis */) { + return false; + } + var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); + if (baseTypeNodes) { + for (var _b = 0; _b < baseTypeNodes.length; _b++) { + var node = baseTypeNodes[_b]; + if (ts.isSupportedExpressionWithTypeArguments(node)) { + var baseSymbol = resolveEntityName(node.expression, 793056 /* Type */, /*ignoreErrors*/ true); + if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { + return false; + } + } + } + } + } + } + return true; + } + function getDeclaredTypeOfClassOrInterface(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var kind = symbol.flags & 32 /* Class */ ? 1024 /* Class */ : 2048 /* Interface */; + var type = links.declaredType = createObjectType(kind, symbol); + var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type + // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular, + // property types inferred from initializers and method return types inferred from return statements are very hard + // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of + // "this" references. + if (outerTypeParameters || localTypeParameters || kind === 1024 /* Class */ || !isIndependentInterface(symbol)) { + type.flags |= 4096 /* Reference */; + type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); + type.outerTypeParameters = outerTypeParameters; + type.localTypeParameters = localTypeParameters; + type.instantiations = {}; + type.instantiations[getTypeListId(type.typeParameters)] = type; + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(512 /* TypeParameter */ | 33554432 /* ThisType */); + type.thisType.symbol = symbol; + type.thisType.constraint = getTypeWithThisArgument(type); + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + // Note that we use the links object as the target here because the symbol object is used as the unique + // identity for resolution of the 'type' property in SymbolLinks. + if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { + return unknownType; + } + var declaration = ts.getDeclarationOfKind(symbol, 216 /* TypeAliasDeclaration */); + var type = getTypeFromTypeNode(declaration.type); + if (popTypeResolution()) { + links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (links.typeParameters) { + // Initialize the instantiation cache for generic type aliases. The declared type corresponds to + // an instantiation of the type alias with the type parameters supplied as type arguments. + links.instantiations = {}; + links.instantiations[getTypeListId(links.typeParameters)] = type; + } + } + else { + type = unknownType; + error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + } + links.declaredType = type; + } + return links.declaredType; + } + function getDeclaredTypeOfEnum(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var type = createType(128 /* Enum */); + type.symbol = symbol; + links.declaredType = type; + } + return links.declaredType; + } + function getDeclaredTypeOfTypeParameter(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var type = createType(512 /* TypeParameter */); + type.symbol = symbol; + if (!ts.getDeclarationOfKind(symbol, 137 /* TypeParameter */).constraint) { + type.constraint = noConstraintType; + } + links.declaredType = type; + } + return links.declaredType; + } + function getDeclaredTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); + } + return links.declaredType; + } + function getDeclaredTypeOfSymbol(symbol) { + ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0); + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + return getDeclaredTypeOfClassOrInterface(symbol); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getDeclaredTypeOfTypeAlias(symbol); + } + if (symbol.flags & 384 /* Enum */) { + return getDeclaredTypeOfEnum(symbol); + } + if (symbol.flags & 262144 /* TypeParameter */) { + return getDeclaredTypeOfTypeParameter(symbol); + } + if (symbol.flags & 8388608 /* Alias */) { + return getDeclaredTypeOfAlias(symbol); + } + return unknownType; + } + // A type reference is considered independent if each type argument is considered independent. + function isIndependentTypeReference(node) { + if (node.typeArguments) { + for (var _i = 0, _a = node.typeArguments; _i < _a.length; _i++) { + var typeNode = _a[_i]; + if (!isIndependentType(typeNode)) { + return false; + } + } + } + return true; + } + // A type is considered independent if it the any, string, number, boolean, symbol, or void keyword, a string + // literal type, an array with an element type that is considered independent, or a type reference that is + // considered independent. + function isIndependentType(node) { + switch (node.kind) { + case 117 /* AnyKeyword */: + case 130 /* StringKeyword */: + case 128 /* NumberKeyword */: + case 120 /* BooleanKeyword */: + case 131 /* SymbolKeyword */: + case 103 /* VoidKeyword */: + case 9 /* StringLiteral */: + return true; + case 156 /* ArrayType */: + return isIndependentType(node.elementType); + case 151 /* TypeReference */: + return isIndependentTypeReference(node); + } + return false; + } + // A variable-like declaration is considered independent (free of this references) if it has a type annotation + // that specifies an independent type, or if it has no type annotation and no initializer (and thus of type any). + function isIndependentVariableLikeDeclaration(node) { + return node.type && isIndependentType(node.type) || !node.type && !node.initializer; + } + // A function-like declaration is considered independent (free of this references) if it has a return type + // annotation that is considered independent and if each parameter is considered independent. + function isIndependentFunctionLikeDeclaration(node) { + if (node.kind !== 144 /* Constructor */ && (!node.type || !isIndependentType(node.type))) { + return false; + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + if (!isIndependentVariableLikeDeclaration(parameter)) { + return false; + } + } + return true; + } + // Returns true if the class or interface member given by the symbol is free of "this" references. The + // function may return false for symbols that are actually free of "this" references because it is not + // feasible to perform a complete analysis in all cases. In particular, property members with types + // inferred from their initializers and function members with inferred return types are convervatively + // assumed not to be free of "this" references. + function isIndependentMember(symbol) { + if (symbol.declarations && symbol.declarations.length === 1) { + var declaration = symbol.declarations[0]; + if (declaration) { + switch (declaration.kind) { + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + return isIndependentVariableLikeDeclaration(declaration); + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 144 /* Constructor */: + return isIndependentFunctionLikeDeclaration(declaration); + } + } + } + return false; + } + function createSymbolTable(symbols) { + var result = {}; + for (var _i = 0; _i < symbols.length; _i++) { + var symbol = symbols[_i]; + result[symbol.name] = symbol; + } + return result; + } + // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true, + // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. + function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { + var result = {}; + for (var _i = 0; _i < symbols.length; _i++) { + var symbol = symbols[_i]; + result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper); + } + return result; + } + function addInheritedMembers(symbols, baseSymbols) { + for (var _i = 0; _i < baseSymbols.length; _i++) { + var s = baseSymbols[_i]; + if (!ts.hasProperty(symbols, s.name)) { + symbols[s.name] = s; + } + } + } + function addInheritedSignatures(signatures, baseSignatures) { + if (baseSignatures) { + for (var _i = 0; _i < baseSignatures.length; _i++) { + var signature = baseSignatures[_i]; + signatures.push(signature); + } + } + } + function resolveDeclaredMembers(type) { + if (!type.declaredProperties) { + var symbol = type.symbol; + type.declaredProperties = getNamedMembers(symbol.members); + type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members["__call"]); + type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members["__new"]); + type.declaredStringIndexType = getIndexTypeOfSymbol(symbol, 0 /* String */); + type.declaredNumberIndexType = getIndexTypeOfSymbol(symbol, 1 /* Number */); + } + return type; + } + function getTypeWithThisArgument(type, thisArgument) { + if (type.flags & 4096 /* Reference */) { + return createTypeReference(type.target, ts.concatenate(type.typeArguments, [thisArgument || type.target.thisType])); + } + return type; + } + function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { + var mapper = identityMapper; + var members = source.symbol.members; + var callSignatures = source.declaredCallSignatures; + var constructSignatures = source.declaredConstructSignatures; + var stringIndexType = source.declaredStringIndexType; + var numberIndexType = source.declaredNumberIndexType; + if (!ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + mapper = createTypeMapper(typeParameters, typeArguments); + members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); + callSignatures = instantiateList(source.declaredCallSignatures, mapper, instantiateSignature); + constructSignatures = instantiateList(source.declaredConstructSignatures, mapper, instantiateSignature); + stringIndexType = instantiateType(source.declaredStringIndexType, mapper); + numberIndexType = instantiateType(source.declaredNumberIndexType, mapper); + } + var baseTypes = getBaseTypes(source); + if (baseTypes.length) { + if (members === source.symbol.members) { + members = createSymbolTable(source.declaredProperties); + } + var thisArgument = ts.lastOrUndefined(typeArguments); + for (var _i = 0; _i < baseTypes.length; _i++) { + var baseType = baseTypes[_i]; + var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; + addInheritedMembers(members, getPropertiesOfObjectType(instantiatedBaseType)); + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); + constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */)); + stringIndexType = stringIndexType || getIndexTypeOfType(instantiatedBaseType, 0 /* String */); + numberIndexType = numberIndexType || getIndexTypeOfType(instantiatedBaseType, 1 /* Number */); + } + } + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); + } + function resolveClassOrInterfaceMembers(type) { + resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray); + } + function resolveTypeReferenceMembers(type) { + var source = resolveDeclaredMembers(type.target); + var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]); + var typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? + type.typeArguments : ts.concatenate(type.typeArguments, [type]); + resolveObjectTypeMembers(type, source, typeParameters, typeArguments); + } + function createSignature(declaration, typeParameters, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasStringLiterals) { + var sig = new Signature(checker); + sig.declaration = declaration; + sig.typeParameters = typeParameters; + sig.parameters = parameters; + sig.resolvedReturnType = resolvedReturnType; + sig.typePredicate = typePredicate; + sig.minArgumentCount = minArgumentCount; + sig.hasRestParameter = hasRestParameter; + sig.hasStringLiterals = hasStringLiterals; + return sig; + } + function cloneSignature(sig) { + return createSignature(sig.declaration, sig.typeParameters, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); + } + function getDefaultConstructSignatures(classType) { + if (!hasClassBaseType(classType)) { + return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)]; + } + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); + var baseTypeNode = getBaseTypeNodeOfClass(classType); + var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); + var typeArgCount = typeArguments ? typeArguments.length : 0; + var result = []; + for (var _i = 0; _i < baseSignatures.length; _i++) { + var baseSig = baseSignatures[_i]; + var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; + if (typeParamCount === typeArgCount) { + var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); + sig.typeParameters = classType.localTypeParameters; + sig.resolvedReturnType = classType; + result.push(sig); + } + } + return result; + } + function createTupleTypeMemberSymbols(memberTypes) { + var members = {}; + for (var i = 0; i < memberTypes.length; i++) { + var symbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "" + i); + symbol.type = memberTypes[i]; + members[i] = symbol; + } + return members; + } + function resolveTupleTypeMembers(type) { + var arrayElementType = getUnionType(type.elementTypes, /*noSubtypeReduction*/ true); + // Make the tuple type itself the 'this' type by including an extra type argument + var arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); + var members = createTupleTypeMemberSymbols(type.elementTypes); + addInheritedMembers(members, arrayType.properties); + setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexType, arrayType.numberIndexType); + } + function findMatchingSignature(signatureList, signature, partialMatch, ignoreReturnTypes) { + for (var _i = 0; _i < signatureList.length; _i++) { + var s = signatureList[_i]; + if (compareSignatures(s, signature, partialMatch, ignoreReturnTypes, compareTypes)) { + return s; + } + } + } + function findMatchingSignatures(signatureLists, signature, listIndex) { + if (signature.typeParameters) { + // We require an exact match for generic signatures, so we only return signatures from the first + // signature list and only if they have exact matches in the other signature lists. + if (listIndex > 0) { + return undefined; + } + for (var i = 1; i < signatureLists.length; i++) { + if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ false)) { + return undefined; + } + } + return [signature]; + } + var result = undefined; + for (var i = 0; i < signatureLists.length; i++) { + // Allow matching non-generic signatures to have excess parameters and different return types + var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreReturnTypes*/ true); + if (!match) { + return undefined; + } + if (!ts.contains(result, match)) { + (result || (result = [])).push(match); + } + } + return result; + } + // The signatures of a union type are those signatures that are present in each of the constituent types. + // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional + // parameters and may differ in return types. When signatures differ in return types, the resulting return + // type is the union of the constituent return types. + function getUnionSignatures(types, kind) { + var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); + var result = undefined; + for (var i = 0; i < signatureLists.length; i++) { + for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { + var signature = _a[_i]; + // Only process signatures with parameter lists that aren't already in the result list + if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true)) { + var unionSignatures = findMatchingSignatures(signatureLists, signature, i); + if (unionSignatures) { + var s = signature; + // Union the result types when more than one signature matches + if (unionSignatures.length > 1) { + s = cloneSignature(signature); + // Clear resolved return type we possibly got from cloneSignature + s.resolvedReturnType = undefined; + s.unionSignatures = unionSignatures; + } + (result || (result = [])).push(s); + } + } + } + } + return result || emptyArray; + } + function getUnionIndexType(types, kind) { + var indexTypes = []; + for (var _i = 0; _i < types.length; _i++) { + var type = types[_i]; + var indexType = getIndexTypeOfType(type, kind); + if (!indexType) { + return undefined; + } + indexTypes.push(indexType); + } + return getUnionType(indexTypes); + } + function resolveUnionTypeMembers(type) { + // The members and properties collections are empty for union types. To get all properties of a union + // type use getPropertiesOfType (only the language service uses this). + var callSignatures = getUnionSignatures(type.types, 0 /* Call */); + var constructSignatures = getUnionSignatures(type.types, 1 /* Construct */); + var stringIndexType = getUnionIndexType(type.types, 0 /* String */); + var numberIndexType = getUnionIndexType(type.types, 1 /* Number */); + setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexType, numberIndexType); + } + function intersectTypes(type1, type2) { + return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); + } + function resolveIntersectionTypeMembers(type) { + // The members and properties collections are empty for intersection types. To get all properties of an + // intersection type use getPropertiesOfType (only the language service uses this). + var callSignatures = emptyArray; + var constructSignatures = emptyArray; + var stringIndexType = undefined; + var numberIndexType = undefined; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0 /* Call */)); + constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(t, 1 /* Construct */)); + stringIndexType = intersectTypes(stringIndexType, getIndexTypeOfType(t, 0 /* String */)); + numberIndexType = intersectTypes(numberIndexType, getIndexTypeOfType(t, 1 /* Number */)); + } + setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexType, numberIndexType); + } + function resolveAnonymousTypeMembers(type) { + var symbol = type.symbol; + var members; + var callSignatures; + var constructSignatures; + var stringIndexType; + var numberIndexType; + if (type.target) { + members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); + callSignatures = instantiateList(getSignaturesOfType(type.target, 0 /* Call */), type.mapper, instantiateSignature); + constructSignatures = instantiateList(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper, instantiateSignature); + stringIndexType = instantiateType(getIndexTypeOfType(type.target, 0 /* String */), type.mapper); + numberIndexType = instantiateType(getIndexTypeOfType(type.target, 1 /* Number */), type.mapper); + } + else if (symbol.flags & 2048 /* TypeLiteral */) { + members = symbol.members; + callSignatures = getSignaturesOfSymbol(members["__call"]); + constructSignatures = getSignaturesOfSymbol(members["__new"]); + stringIndexType = getIndexTypeOfSymbol(symbol, 0 /* String */); + numberIndexType = getIndexTypeOfSymbol(symbol, 1 /* Number */); + } + else { + // Combinations of function, class, enum and module + members = emptySymbols; + callSignatures = emptyArray; + constructSignatures = emptyArray; + if (symbol.flags & 1952 /* HasExports */) { + members = getExportsOfSymbol(symbol); + } + if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { + callSignatures = getSignaturesOfSymbol(symbol); + } + if (symbol.flags & 32 /* Class */) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + constructSignatures = getSignaturesOfSymbol(symbol.members["__constructor"]); + if (!constructSignatures.length) { + constructSignatures = getDefaultConstructSignatures(classType); + } + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + if (baseConstructorType.flags & 80896 /* ObjectType */) { + members = createSymbolTable(getNamedMembers(members)); + addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); + } + } + stringIndexType = undefined; + numberIndexType = (symbol.flags & 384 /* Enum */) ? stringType : undefined; + } + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); + } + function resolveStructuredTypeMembers(type) { + if (!type.members) { + if (type.flags & 4096 /* Reference */) { + resolveTypeReferenceMembers(type); + } + else if (type.flags & (1024 /* Class */ | 2048 /* Interface */)) { + resolveClassOrInterfaceMembers(type); + } + else if (type.flags & 65536 /* Anonymous */) { + resolveAnonymousTypeMembers(type); + } + else if (type.flags & 8192 /* Tuple */) { + resolveTupleTypeMembers(type); + } + else if (type.flags & 16384 /* Union */) { + resolveUnionTypeMembers(type); + } + else if (type.flags & 32768 /* Intersection */) { + resolveIntersectionTypeMembers(type); + } + } + return type; + } + // Return properties of an object type or an empty array for other types + function getPropertiesOfObjectType(type) { + if (type.flags & 80896 /* ObjectType */) { + return resolveStructuredTypeMembers(type).properties; + } + return emptyArray; + } + // If the given type is an object type and that type has a property by the given name, + // return the symbol for that property.Otherwise return undefined. + function getPropertyOfObjectType(type, name) { + if (type.flags & 80896 /* ObjectType */) { + var resolved = resolveStructuredTypeMembers(type); + if (ts.hasProperty(resolved.members, name)) { + var symbol = resolved.members[name]; + if (symbolIsValue(symbol)) { + return symbol; + } + } + } + } + function getPropertiesOfUnionOrIntersectionType(type) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var current = _a[_i]; + for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { + var prop = _c[_b]; + getPropertyOfUnionOrIntersectionType(type, prop.name); + } + // The properties of a union type are those that are present in all constituent types, so + // we only need to check the properties of the first type + if (type.flags & 16384 /* Union */) { + break; + } + } + return type.resolvedProperties ? symbolsToArray(type.resolvedProperties) : emptyArray; + } + function getPropertiesOfType(type) { + type = getApparentType(type); + return type.flags & 49152 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); + } + /** + * For a type parameter, return the base constraint of the type parameter. For the string, number, + * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the + * type itself. Note that the apparent type of a union type is the union type itself. + */ + function getApparentType(type) { + if (type.flags & 512 /* TypeParameter */) { + do { + type = getConstraintOfTypeParameter(type); + } while (type && type.flags & 512 /* TypeParameter */); + if (!type) { + type = emptyObjectType; + } + } + if (type.flags & 258 /* StringLike */) { + type = globalStringType; + } + else if (type.flags & 132 /* NumberLike */) { + type = globalNumberType; + } + else if (type.flags & 8 /* Boolean */) { + type = globalBooleanType; + } + else if (type.flags & 16777216 /* ESSymbol */) { + type = globalESSymbolType; + } + return type; + } + function createUnionOrIntersectionProperty(containingType, name) { + var types = containingType.types; + var props; + for (var _i = 0; _i < types.length; _i++) { + var current = types[_i]; + var type = getApparentType(current); + if (type !== unknownType) { + var prop = getPropertyOfType(type, name); + if (prop && !(getDeclarationFlagsFromSymbol(prop) & (32 /* Private */ | 64 /* Protected */))) { + if (!props) { + props = [prop]; + } + else if (!ts.contains(props, prop)) { + props.push(prop); + } + } + else if (containingType.flags & 16384 /* Union */) { + // A union type requires the property to be present in all constituent types + return undefined; + } + } + } + if (!props) { + return undefined; + } + if (props.length === 1) { + return props[0]; + } + var propTypes = []; + var declarations = []; + for (var _a = 0; _a < props.length; _a++) { + var prop = props[_a]; + if (prop.declarations) { + ts.addRange(declarations, prop.declarations); + } + propTypes.push(getTypeOfSymbol(prop)); + } + var result = createSymbol(4 /* Property */ | 67108864 /* Transient */ | 268435456 /* SyntheticProperty */, name); + result.containingType = containingType; + result.declarations = declarations; + result.type = containingType.flags & 16384 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); + return result; + } + function getPropertyOfUnionOrIntersectionType(type, name) { + var properties = type.resolvedProperties || (type.resolvedProperties = {}); + if (ts.hasProperty(properties, name)) { + return properties[name]; + } + var property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties[name] = property; + } + return property; + } + // Return the symbol for the property with the given name in the given type. Creates synthetic union properties when + // necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from + // Object and Function as appropriate. + function getPropertyOfType(type, name) { + type = getApparentType(type); + if (type.flags & 80896 /* ObjectType */) { + var resolved = resolveStructuredTypeMembers(type); + if (ts.hasProperty(resolved.members, name)) { + var symbol = resolved.members[name]; + if (symbolIsValue(symbol)) { + return symbol; + } + } + if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { + var symbol = getPropertyOfObjectType(globalFunctionType, name); + if (symbol) { + return symbol; + } + } + return getPropertyOfObjectType(globalObjectType, name); + } + if (type.flags & 49152 /* UnionOrIntersection */) { + return getPropertyOfUnionOrIntersectionType(type, name); + } + return undefined; + } + function getSignaturesOfStructuredType(type, kind) { + if (type.flags & 130048 /* StructuredType */) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; + } + return emptyArray; + } + /** + * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and + * maps primitive types and type parameters are to their apparent types. + */ + function getSignaturesOfType(type, kind) { + return getSignaturesOfStructuredType(getApparentType(type), kind); + } + function typeHasConstructSignatures(type) { + var apparentType = getApparentType(type); + if (apparentType.flags & (80896 /* ObjectType */ | 16384 /* Union */)) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.constructSignatures.length > 0; + } + return false; + } + function typeHasCallOrConstructSignatures(type) { + var apparentType = getApparentType(type); + if (apparentType.flags & 130048 /* StructuredType */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length > 0 || resolved.constructSignatures.length > 0; + } + return false; + } + function getIndexTypeOfStructuredType(type, kind) { + if (type.flags & 130048 /* StructuredType */) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 /* String */ ? resolved.stringIndexType : resolved.numberIndexType; + } + } + // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. + function getIndexTypeOfType(type, kind) { + return getIndexTypeOfStructuredType(getApparentType(type), kind); + } + // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual + // type checking functions). + function getTypeParametersFromDeclaration(typeParameterDeclarations) { + var result = []; + ts.forEach(typeParameterDeclarations, function (node) { + var tp = getDeclaredTypeOfTypeParameter(node.symbol); + if (!ts.contains(result, tp)) { + result.push(tp); + } + }); + return result; + } + function symbolsToArray(symbols) { + var result = []; + for (var id in symbols) { + if (!isReservedMemberName(id)) { + result.push(symbols[id]); + } + } + return result; + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node)) { + return true; + } + if (node.initializer) { + var signatureDeclaration = node.parent; + var signature = getSignatureFromDeclaration(signatureDeclaration); + var parameterIndex = signatureDeclaration.parameters.indexOf(node); + ts.Debug.assert(parameterIndex >= 0); + return parameterIndex >= signature.minArgumentCount; + } + return false; + } + function getSignatureFromDeclaration(declaration) { + var links = getNodeLinks(declaration); + if (!links.resolvedSignature) { + var classType = declaration.kind === 144 /* Constructor */ ? + getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) + : undefined; + var typeParameters = classType ? classType.localTypeParameters : + declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : undefined; + var parameters = []; + var hasStringLiterals = false; + var minArgumentCount = -1; + for (var i = 0, n = declaration.parameters.length; i < n; i++) { + var param = declaration.parameters[i]; + parameters.push(param.symbol); + if (param.type && param.type.kind === 9 /* StringLiteral */) { + hasStringLiterals = true; + } + if (param.initializer || param.questionToken || param.dotDotDotToken) { + if (minArgumentCount < 0) { + minArgumentCount = i; + } + } + else { + // If we see any required parameters, it means the prior ones were not in fact optional. + minArgumentCount = -1; + } + } + if (minArgumentCount < 0) { + minArgumentCount = declaration.parameters.length; + } + var returnType; + var typePredicate; + if (classType) { + returnType = classType; + } + else if (declaration.type) { + returnType = getTypeFromTypeNode(declaration.type); + if (declaration.type.kind === 150 /* TypePredicate */) { + var typePredicateNode = declaration.type; + typePredicate = { + parameterName: typePredicateNode.parameterName ? typePredicateNode.parameterName.text : undefined, + parameterIndex: typePredicateNode.parameterName ? getTypePredicateParameterIndex(declaration.parameters, typePredicateNode.parameterName) : undefined, + type: getTypeFromTypeNode(typePredicateNode.type) + }; + } + } + else { + // TypeScript 1.0 spec (April 2014): + // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. + if (declaration.kind === 145 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 146 /* SetAccessor */); + returnType = getAnnotatedAccessorType(setter); + } + if (!returnType && ts.nodeIsMissing(declaration.body)) { + returnType = anyType; + } + } + links.resolvedSignature = createSignature(declaration, typeParameters, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasStringLiterals); + } + return links.resolvedSignature; + } + function getSignaturesOfSymbol(symbol) { + if (!symbol) + return emptyArray; + var result = []; + for (var i = 0, len = symbol.declarations.length; i < len; i++) { + var node = symbol.declarations[i]; + switch (node.kind) { + case 152 /* FunctionType */: + case 153 /* ConstructorType */: + case 213 /* FunctionDeclaration */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 144 /* Constructor */: + case 147 /* CallSignature */: + case 148 /* ConstructSignature */: + case 149 /* IndexSignature */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 173 /* FunctionExpression */: + case 174 /* ArrowFunction */: + // Don't include signature if node is the implementation of an overloaded function. A node is considered + // an implementation node if it has a body and the previous node is of the same kind and immediately + // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). + if (i > 0 && node.body) { + var previous = symbol.declarations[i - 1]; + if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { + break; + } + } + result.push(getSignatureFromDeclaration(node)); + } + } + return result; + } + function getReturnTypeOfSignature(signature) { + if (!signature.resolvedReturnType) { + if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { + return unknownType; + } + var type; + if (signature.target) { + type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); + } + else if (signature.unionSignatures) { + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature)); + } + else { + type = getReturnTypeFromBody(signature.declaration); + } + if (!popTypeResolution()) { + type = anyType; + if (compilerOptions.noImplicitAny) { + var declaration = signature.declaration; + if (declaration.name) { + error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + } + else { + error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + } + } + } + signature.resolvedReturnType = type; + } + return signature.resolvedReturnType; + } + function getRestTypeOfSignature(signature) { + if (signature.hasRestParameter) { + var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); + if (type.flags & 4096 /* Reference */ && type.target === globalArrayType) { + return type.typeArguments[0]; + } + } + return anyType; + } + function getSignatureInstantiation(signature, typeArguments) { + return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); + } + function getErasedSignature(signature) { + if (!signature.typeParameters) + return signature; + if (!signature.erasedSignatureCache) { + if (signature.target) { + signature.erasedSignatureCache = instantiateSignature(getErasedSignature(signature.target), signature.mapper); + } + else { + signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); + } + } + return signature.erasedSignatureCache; + } + function getOrCreateTypeFromSignature(signature) { + // There are two ways to declare a construct signature, one is by declaring a class constructor + // using the constructor keyword, and the other is declaring a bare construct signature in an + // object type literal or interface (using the new keyword). Each way of declaring a constructor + // will result in a different declaration kind. + if (!signature.isolatedSignatureType) { + var isConstructor = signature.declaration.kind === 144 /* Constructor */ || signature.declaration.kind === 148 /* ConstructSignature */; + var type = createObjectType(65536 /* Anonymous */ | 262144 /* FromSignature */); + type.members = emptySymbols; + type.properties = emptyArray; + type.callSignatures = !isConstructor ? [signature] : emptyArray; + type.constructSignatures = isConstructor ? [signature] : emptyArray; + signature.isolatedSignatureType = type; + } + return signature.isolatedSignatureType; + } + function getIndexSymbol(symbol) { + return symbol.members["__index"]; + } + function getIndexDeclarationOfSymbol(symbol, kind) { + var syntaxKind = kind === 1 /* Number */ ? 128 /* NumberKeyword */ : 130 /* StringKeyword */; + var indexSymbol = getIndexSymbol(symbol); + if (indexSymbol) { + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var node = decl; + if (node.parameters.length === 1) { + var parameter = node.parameters[0]; + if (parameter && parameter.type && parameter.type.kind === syntaxKind) { + return node; + } + } + } + } + return undefined; + } + function getIndexTypeOfSymbol(symbol, kind) { + var declaration = getIndexDeclarationOfSymbol(symbol, kind); + return declaration + ? declaration.type ? getTypeFromTypeNode(declaration.type) : anyType + : undefined; + } + function getConstraintOfTypeParameter(type) { + if (!type.constraint) { + if (type.target) { + var targetConstraint = getConstraintOfTypeParameter(type.target); + type.constraint = targetConstraint ? instantiateType(targetConstraint, type.mapper) : noConstraintType; + } + else { + type.constraint = getTypeFromTypeNode(ts.getDeclarationOfKind(type.symbol, 137 /* TypeParameter */).constraint); + } + } + return type.constraint === noConstraintType ? undefined : type.constraint; + } + function getParentSymbolOfTypeParameter(typeParameter) { + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 137 /* TypeParameter */).parent); + } + function getTypeListId(types) { + if (types) { + switch (types.length) { + case 1: + return "" + types[0].id; + case 2: + return types[0].id + "," + types[1].id; + default: + var result = ""; + for (var i = 0; i < types.length; i++) { + if (i > 0) { + result += ","; + } + result += types[i].id; + } + return result; + } + } + return ""; + } + // This function is used to propagate certain flags when creating new object type references and union types. + // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type + // of an object literal or the anyFunctionType. This is because there are operations in the type checker + // that care about the presence of such types at arbitrary depth in a containing type. + function getPropagatingFlagsOfTypes(types) { + var result = 0; + for (var _i = 0; _i < types.length; _i++) { + var type = types[_i]; + result |= type.flags; + } + return result & 14680064 /* PropagatingFlags */; + } + function createTypeReference(target, typeArguments) { + var id = getTypeListId(typeArguments); + var type = target.instantiations[id]; + if (!type) { + var flags = 4096 /* Reference */ | (typeArguments ? getPropagatingFlagsOfTypes(typeArguments) : 0); + type = target.instantiations[id] = createObjectType(flags, target.symbol); + type.target = target; + type.typeArguments = typeArguments; + } + return type; + } + function isTypeParameterReferenceIllegalInConstraint(typeReferenceNode, typeParameterSymbol) { + var links = getNodeLinks(typeReferenceNode); + if (links.isIllegalTypeReferenceInConstraint !== undefined) { + return links.isIllegalTypeReferenceInConstraint; + } + // bubble up to the declaration + var currentNode = typeReferenceNode; + // forEach === exists + while (!ts.forEach(typeParameterSymbol.declarations, function (d) { return d.parent === currentNode.parent; })) { + currentNode = currentNode.parent; + } + // if last step was made from the type parameter this means that path has started somewhere in constraint which is illegal + links.isIllegalTypeReferenceInConstraint = currentNode.kind === 137 /* TypeParameter */; + return links.isIllegalTypeReferenceInConstraint; + } + function checkTypeParameterHasIllegalReferencesInConstraint(typeParameter) { + var typeParameterSymbol; + function check(n) { + if (n.kind === 151 /* TypeReference */ && n.typeName.kind === 69 /* Identifier */) { + var links = getNodeLinks(n); + if (links.isIllegalTypeReferenceInConstraint === undefined) { + var symbol = resolveName(typeParameter, n.typeName.text, 793056 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (symbol && (symbol.flags & 262144 /* TypeParameter */)) { + // TypeScript 1.0 spec (April 2014): 3.4.1 + // Type parameters declared in a particular type parameter list + // may not be referenced in constraints in that type parameter list + // symbol.declaration.parent === typeParameter.parent + // -> typeParameter and symbol.declaration originate from the same type parameter list + // -> illegal for all declarations in symbol + // forEach === exists + links.isIllegalTypeReferenceInConstraint = ts.forEach(symbol.declarations, function (d) { return d.parent === typeParameter.parent; }); + } + } + if (links.isIllegalTypeReferenceInConstraint) { + error(typeParameter, ts.Diagnostics.Constraint_of_a_type_parameter_cannot_reference_any_type_parameter_from_the_same_type_parameter_list); + } + } + ts.forEachChild(n, check); + } + if (typeParameter.constraint) { + typeParameterSymbol = getSymbolOfNode(typeParameter); + check(typeParameter.constraint); + } + } + // Get type from reference to class or interface + function getTypeFromClassOrInterfaceReference(node, symbol) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeParameters = type.localTypeParameters; + if (typeParameters) { + if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { + error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */), typeParameters.length); + return unknownType; + } + // In a type reference, the outer type parameters of the referenced class or interface are automatically + // supplied as type arguments and the type reference only specifies arguments for the local type parameters + // of the class or interface. + return createTypeReference(type, ts.concatenate(type.outerTypeParameters, ts.map(node.typeArguments, getTypeFromTypeNode))); + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + return unknownType; + } + return type; + } + // Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include + // references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the + // declared type. Instantiations are cached using the type identities of the type arguments as the key. + function getTypeFromTypeAliasReference(node, symbol) { + var type = getDeclaredTypeOfSymbol(symbol); + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + if (typeParameters) { + if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { + error(node, ts.Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); + return unknownType; + } + var typeArguments = ts.map(node.typeArguments, getTypeFromTypeNode); + var id = getTypeListId(typeArguments); + return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments))); + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return type; + } + // Get type from reference to named type that cannot be generic (enum or type parameter) + function getTypeFromNonGenericTypeReference(node, symbol) { + if (symbol.flags & 262144 /* TypeParameter */ && isTypeParameterReferenceIllegalInConstraint(node, symbol)) { + // TypeScript 1.0 spec (April 2014): 3.4.1 + // Type parameters declared in a particular type parameter list + // may not be referenced in constraints in that type parameter list + // Implementation: such type references are resolved to 'unknown' type that usually denotes error + return unknownType; + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return getDeclaredTypeOfSymbol(symbol); + } + function getTypeFromTypeReference(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + // We only support expressions that are simple qualified names. For other expressions this produces undefined. + var typeNameOrExpression = node.kind === 151 /* TypeReference */ ? node.typeName : + ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : + undefined; + var symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056 /* Type */) || unknownSymbol; + var type = symbol === unknownSymbol ? unknownType : + symbol.flags & (32 /* Class */ | 64 /* Interface */) ? getTypeFromClassOrInterfaceReference(node, symbol) : + symbol.flags & 524288 /* TypeAlias */ ? getTypeFromTypeAliasReference(node, symbol) : + getTypeFromNonGenericTypeReference(node, symbol); + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // type reference in checkTypeReferenceOrExpressionWithTypeArguments. + links.resolvedSymbol = symbol; + links.resolvedType = type; + } + return links.resolvedType; + } + function getTypeFromTypeQueryNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + // TypeScript 1.0 spec (April 2014): 3.6.3 + // The expression is processed as an identifier expression (section 4.3) + // or property access expression(section 4.10), + // the widened type(section 3.9) of which becomes the result. + links.resolvedType = getWidenedType(checkExpression(node.exprName)); + } + return links.resolvedType; + } + function getTypeOfGlobalSymbol(symbol, arity) { + function getTypeDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0; _i < declarations.length; _i++) { + var declaration = declarations[_i]; + switch (declaration.kind) { + case 214 /* ClassDeclaration */: + case 215 /* InterfaceDeclaration */: + case 217 /* EnumDeclaration */: + return declaration; + } + } + } + if (!symbol) { + return arity ? emptyGenericType : emptyObjectType; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!(type.flags & 80896 /* ObjectType */)) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); + return arity ? emptyGenericType : emptyObjectType; + } + if ((type.typeParameters ? type.typeParameters.length : 0) !== arity) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbol.name, arity); + return arity ? emptyGenericType : emptyObjectType; + } + return type; + } + function getGlobalValueSymbol(name) { + return getGlobalSymbol(name, 107455 /* Value */, ts.Diagnostics.Cannot_find_global_value_0); + } + function getGlobalTypeSymbol(name) { + return getGlobalSymbol(name, 793056 /* Type */, ts.Diagnostics.Cannot_find_global_type_0); + } + function getGlobalSymbol(name, meaning, diagnostic) { + return resolveName(undefined, name, meaning, diagnostic, name); + } + function getGlobalType(name, arity) { + if (arity === void 0) { arity = 0; } + return getTypeOfGlobalSymbol(getGlobalTypeSymbol(name), arity); + } + function tryGetGlobalType(name, arity) { + if (arity === void 0) { arity = 0; } + return getTypeOfGlobalSymbol(getGlobalSymbol(name, 793056 /* Type */, /*diagnostic*/ undefined), arity); + } + /** + * Returns a type that is inside a namespace at the global scope, e.g. + * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type + */ + function getExportedTypeFromNamespace(namespace, name) { + var namespaceSymbol = getGlobalSymbol(namespace, 1536 /* Namespace */, /*diagnosticMessage*/ undefined); + var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793056 /* Type */); + return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); + } + function getGlobalESSymbolConstructorSymbol() { + return globalESSymbolConstructorSymbol || (globalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol")); + } + /** + * Creates a TypeReference for a generic `TypedPropertyDescriptor`. + */ + function createTypedPropertyDescriptorType(propertyType) { + var globalTypedPropertyDescriptorType = getGlobalTypedPropertyDescriptorType(); + return globalTypedPropertyDescriptorType !== emptyGenericType + ? createTypeReference(globalTypedPropertyDescriptorType, [propertyType]) + : emptyObjectType; + } + /** + * Instantiates a global type that is generic with some element type, and returns that instantiation. + */ + function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { + return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; + } + function createIterableType(elementType) { + return createTypeFromGenericGlobalType(globalIterableType, [elementType]); + } + function createIterableIteratorType(elementType) { + return createTypeFromGenericGlobalType(globalIterableIteratorType, [elementType]); + } + function createArrayType(elementType) { + return createTypeFromGenericGlobalType(globalArrayType, [elementType]); + } + function getTypeFromArrayTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); + } + return links.resolvedType; + } + function createTupleType(elementTypes) { + var id = getTypeListId(elementTypes); + return tupleTypes[id] || (tupleTypes[id] = createNewTupleType(elementTypes)); + } + function createNewTupleType(elementTypes) { + var type = createObjectType(8192 /* Tuple */ | getPropagatingFlagsOfTypes(elementTypes)); + type.elementTypes = elementTypes; + return type; + } + function getTypeFromTupleTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); + } + return links.resolvedType; + } + function addTypeToSet(typeSet, type, typeSetKind) { + if (type.flags & typeSetKind) { + addTypesToSet(typeSet, type.types, typeSetKind); + } + else if (!ts.contains(typeSet, type)) { + typeSet.push(type); + } + } + // Add the given types to the given type set. Order is preserved, duplicates are removed, + // and nested types of the given kind are flattened into the set. + function addTypesToSet(typeSet, types, typeSetKind) { + for (var _i = 0; _i < types.length; _i++) { + var type = types[_i]; + addTypeToSet(typeSet, type, typeSetKind); + } + } + function isSubtypeOfAny(candidate, types) { + for (var i = 0, len = types.length; i < len; i++) { + if (candidate !== types[i] && isTypeSubtypeOf(candidate, types[i])) { + return true; + } + } + return false; + } + function removeSubtypes(types) { + var i = types.length; + while (i > 0) { + i--; + if (isSubtypeOfAny(types[i], types)) { + types.splice(i, 1); + } + } + } + function containsTypeAny(types) { + for (var _i = 0; _i < types.length; _i++) { + var type = types[_i]; + if (isTypeAny(type)) { + return true; + } + } + return false; + } + function removeAllButLast(types, typeToRemove) { + var i = types.length; + while (i > 0 && types.length > 1) { + i--; + if (types[i] === typeToRemove) { + types.splice(i, 1); + } + } + } + // We reduce the constituent type set to only include types that aren't subtypes of other types, unless + // the noSubtypeReduction flag is specified, in which case we perform a simple deduplication based on + // object identity. Subtype reduction is possible only when union types are known not to circularly + // reference themselves (as is the case with union types created by expression constructs such as array + // literals and the || and ?: operators). Named types can circularly reference themselves and therefore + // cannot be deduplicated during their declaration. For example, "type Item = string | (() => Item" is + // a named type that circularly references itself. + function getUnionType(types, noSubtypeReduction) { + if (types.length === 0) { + return emptyObjectType; + } + var typeSet = []; + addTypesToSet(typeSet, types, 16384 /* Union */); + if (containsTypeAny(typeSet)) { + return anyType; + } + if (noSubtypeReduction) { + removeAllButLast(typeSet, undefinedType); + removeAllButLast(typeSet, nullType); + } + else { + removeSubtypes(typeSet); + } + if (typeSet.length === 1) { + return typeSet[0]; + } + var id = getTypeListId(typeSet); + var type = unionTypes[id]; + if (!type) { + type = unionTypes[id] = createObjectType(16384 /* Union */ | getPropagatingFlagsOfTypes(typeSet)); + type.types = typeSet; + } + return type; + } + function getTypeFromUnionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), /*noSubtypeReduction*/ true); + } + return links.resolvedType; + } + // We do not perform structural deduplication on intersection types. Intersection types are created only by the & + // type operator and we can't reduce those because we want to support recursive intersection types. For example, + // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. + // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution + // for intersections of types with signatures can be deterministic. + function getIntersectionType(types) { + if (types.length === 0) { + return emptyObjectType; + } + var typeSet = []; + addTypesToSet(typeSet, types, 32768 /* Intersection */); + if (containsTypeAny(typeSet)) { + return anyType; + } + if (typeSet.length === 1) { + return typeSet[0]; + } + var id = getTypeListId(typeSet); + var type = intersectionTypes[id]; + if (!type) { + type = intersectionTypes[id] = createObjectType(32768 /* Intersection */ | getPropagatingFlagsOfTypes(typeSet)); + type.types = typeSet; + } + return type; + } + function getTypeFromIntersectionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode)); + } + return links.resolvedType; + } + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + // Deferred resolution of members is handled by resolveObjectTypeMembers + links.resolvedType = createObjectType(65536 /* Anonymous */, node.symbol); + } + return links.resolvedType; + } + function getStringLiteralType(node) { + if (ts.hasProperty(stringLiteralTypes, node.text)) { + return stringLiteralTypes[node.text]; + } + var type = stringLiteralTypes[node.text] = createType(256 /* StringLiteral */); + type.text = ts.getTextOfNode(node); + return type; + } + function getTypeFromStringLiteral(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getStringLiteralType(node); + } + return links.resolvedType; + } + function getThisType(node) { + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + var parent = container && container.parent; + if (parent && (ts.isClassLike(parent) || parent.kind === 215 /* InterfaceDeclaration */)) { + if (!(container.flags & 128 /* Static */) && + (container.kind !== 144 /* Constructor */ || ts.isNodeDescendentOf(node, container.body))) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; + } + } + error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); + return unknownType; + } + function getTypeFromThisTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getThisType(node); + } + return links.resolvedType; + } + function getTypeFromTypeNode(node) { + switch (node.kind) { + case 117 /* AnyKeyword */: + return anyType; + case 130 /* StringKeyword */: + return stringType; + case 128 /* NumberKeyword */: + return numberType; + case 120 /* BooleanKeyword */: + return booleanType; + case 131 /* SymbolKeyword */: + return esSymbolType; + case 103 /* VoidKeyword */: + return voidType; + case 97 /* ThisKeyword */: + return getTypeFromThisTypeNode(node); + case 9 /* StringLiteral */: + return getTypeFromStringLiteral(node); + case 151 /* TypeReference */: + return getTypeFromTypeReference(node); + case 150 /* TypePredicate */: + return booleanType; + case 188 /* ExpressionWithTypeArguments */: + return getTypeFromTypeReference(node); + case 154 /* TypeQuery */: + return getTypeFromTypeQueryNode(node); + case 156 /* ArrayType */: + return getTypeFromArrayTypeNode(node); + case 157 /* TupleType */: + return getTypeFromTupleTypeNode(node); + case 158 /* UnionType */: + return getTypeFromUnionTypeNode(node); + case 159 /* IntersectionType */: + return getTypeFromIntersectionTypeNode(node); + case 160 /* ParenthesizedType */: + return getTypeFromTypeNode(node.type); + case 152 /* FunctionType */: + case 153 /* ConstructorType */: + case 155 /* TypeLiteral */: + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + // This function assumes that an identifier or qualified name is a type expression + // Callers should first ensure this by calling isTypeNode + case 69 /* Identifier */: + case 135 /* QualifiedName */: + var symbol = getSymbolAtLocation(node); + return symbol && getDeclaredTypeOfSymbol(symbol); + default: + return unknownType; + } + } + function instantiateList(items, mapper, instantiator) { + if (items && items.length) { + var result = []; + for (var _i = 0; _i < items.length; _i++) { + var v = items[_i]; + result.push(instantiator(v, mapper)); + } + return result; + } + return items; + } + function createUnaryTypeMapper(source, target) { + return function (t) { return t === source ? target : t; }; + } + function createBinaryTypeMapper(source1, target1, source2, target2) { + return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; }; + } + function createTypeMapper(sources, targets) { + switch (sources.length) { + case 1: return createUnaryTypeMapper(sources[0], targets[0]); + case 2: return createBinaryTypeMapper(sources[0], targets[0], sources[1], targets[1]); + } + return function (t) { + for (var i = 0; i < sources.length; i++) { + if (t === sources[i]) { + return targets[i]; + } + } + return t; + }; + } + function createUnaryTypeEraser(source) { + return function (t) { return t === source ? anyType : t; }; + } + function createBinaryTypeEraser(source1, source2) { + return function (t) { return t === source1 || t === source2 ? anyType : t; }; + } + function createTypeEraser(sources) { + switch (sources.length) { + case 1: return createUnaryTypeEraser(sources[0]); + case 2: return createBinaryTypeEraser(sources[0], sources[1]); + } + return function (t) { + for (var _i = 0; _i < sources.length; _i++) { + var source = sources[_i]; + if (t === source) { + return anyType; + } + } + return t; + }; + } + function createInferenceMapper(context) { + var mapper = function (t) { + for (var i = 0; i < context.typeParameters.length; i++) { + if (t === context.typeParameters[i]) { + context.inferences[i].isFixed = true; + return getInferredType(context, i); + } + } + return t; + }; + mapper.context = context; + return mapper; + } + function identityMapper(type) { + return type; + } + function combineTypeMappers(mapper1, mapper2) { + return function (t) { return instantiateType(mapper1(t), mapper2); }; + } + function instantiateTypeParameter(typeParameter, mapper) { + var result = createType(512 /* TypeParameter */); + result.symbol = typeParameter.symbol; + if (typeParameter.constraint) { + result.constraint = instantiateType(typeParameter.constraint, mapper); + } + else { + result.target = typeParameter; + result.mapper = mapper; + } + return result; + } + function instantiateSignature(signature, mapper, eraseTypeParameters) { + var freshTypeParameters; + var freshTypePredicate; + if (signature.typeParameters && !eraseTypeParameters) { + freshTypeParameters = instantiateList(signature.typeParameters, mapper, instantiateTypeParameter); + mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + } + if (signature.typePredicate) { + freshTypePredicate = { + parameterName: signature.typePredicate.parameterName, + parameterIndex: signature.typePredicate.parameterIndex, + type: instantiateType(signature.typePredicate.type, mapper) + }; + } + var result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasStringLiterals); + result.target = signature; + result.mapper = mapper; + return result; + } + function instantiateSymbol(symbol, mapper) { + if (symbol.flags & 16777216 /* Instantiated */) { + var links = getSymbolLinks(symbol); + // If symbol being instantiated is itself a instantiation, fetch the original target and combine the + // type mappers. This ensures that original type identities are properly preserved and that aliases + // always reference a non-aliases. + symbol = links.target; + mapper = combineTypeMappers(links.mapper, mapper); + } + // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and + // also transient so that we can just store data on it directly. + var result = createSymbol(16777216 /* Instantiated */ | 67108864 /* Transient */ | symbol.flags, symbol.name); + result.declarations = symbol.declarations; + result.parent = symbol.parent; + result.target = symbol; + result.mapper = mapper; + if (symbol.valueDeclaration) { + result.valueDeclaration = symbol.valueDeclaration; + } + return result; + } + function instantiateAnonymousType(type, mapper) { + if (mapper.instantiations) { + var cachedType = mapper.instantiations[type.id]; + if (cachedType) { + return cachedType; + } + } + else { + mapper.instantiations = []; + } + // Mark the anonymous type as instantiated such that our infinite instantiation detection logic can recognize it + var result = createObjectType(65536 /* Anonymous */ | 131072 /* Instantiated */, type.symbol); + result.target = type; + result.mapper = mapper; + mapper.instantiations[type.id] = result; + return result; + } + function instantiateType(type, mapper) { + if (type && mapper !== identityMapper) { + if (type.flags & 512 /* TypeParameter */) { + return mapper(type); + } + if (type.flags & 65536 /* Anonymous */) { + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) ? + instantiateAnonymousType(type, mapper) : type; + } + if (type.flags & 4096 /* Reference */) { + return createTypeReference(type.target, instantiateList(type.typeArguments, mapper, instantiateType)); + } + if (type.flags & 8192 /* Tuple */) { + return createTupleType(instantiateList(type.elementTypes, mapper, instantiateType)); + } + if (type.flags & 16384 /* Union */) { + return getUnionType(instantiateList(type.types, mapper, instantiateType), /*noSubtypeReduction*/ true); + } + if (type.flags & 32768 /* Intersection */) { + return getIntersectionType(instantiateList(type.types, mapper, instantiateType)); + } + } + return type; + } + // Returns true if the given expression contains (at any level of nesting) a function or arrow expression + // that is subject to contextual typing. + function isContextSensitive(node) { + ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + switch (node.kind) { + case 173 /* FunctionExpression */: + case 174 /* ArrowFunction */: + return isContextSensitiveFunctionLikeDeclaration(node); + case 165 /* ObjectLiteralExpression */: + return ts.forEach(node.properties, isContextSensitive); + case 164 /* ArrayLiteralExpression */: + return ts.forEach(node.elements, isContextSensitive); + case 182 /* ConditionalExpression */: + return isContextSensitive(node.whenTrue) || + isContextSensitive(node.whenFalse); + case 181 /* BinaryExpression */: + return node.operatorToken.kind === 52 /* BarBarToken */ && + (isContextSensitive(node.left) || isContextSensitive(node.right)); + case 245 /* PropertyAssignment */: + return isContextSensitive(node.initializer); + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + return isContextSensitiveFunctionLikeDeclaration(node); + case 172 /* ParenthesizedExpression */: + return isContextSensitive(node.expression); + } + return false; + } + function isContextSensitiveFunctionLikeDeclaration(node) { + return !node.typeParameters && node.parameters.length && !ts.forEach(node.parameters, function (p) { return p.type; }); + } + function getTypeWithoutSignatures(type) { + if (type.flags & 80896 /* ObjectType */) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.constructSignatures.length) { + var result = createObjectType(65536 /* Anonymous */, type.symbol); + result.members = resolved.members; + result.properties = resolved.properties; + result.callSignatures = emptyArray; + result.constructSignatures = emptyArray; + type = result; + } + } + return type; + } + // TYPE CHECKING + function isTypeIdenticalTo(source, target) { + return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined); + } + function compareTypes(source, target) { + return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined) ? -1 /* True */ : 0 /* False */; + } + function isTypeSubtypeOf(source, target) { + return checkTypeSubtypeOf(source, target, /*errorNode*/ undefined); + } + function isTypeAssignableTo(source, target) { + return checkTypeAssignableTo(source, target, /*errorNode*/ undefined); + } + function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); + } + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + } + function isSignatureAssignableTo(source, target) { + var sourceType = getOrCreateTypeFromSignature(source); + var targetType = getOrCreateTypeFromSignature(target); + return checkTypeRelatedTo(sourceType, targetType, assignableRelation, /*errorNode*/ undefined); + } + /** + * Checks if 'source' is related to 'target' (e.g.: is a assignable to). + * @param source The left-hand-side of the relation. + * @param target The right-hand-side of the relation. + * @param relation The relation considered. One of 'identityRelation', 'assignableRelation', or 'subTypeRelation'. + * Used as both to determine which checks are performed and as a cache of previously computed results. + * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used. + * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used. + * @param containingMessageChain A chain of errors to prepend any new errors found. + */ + function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { + var errorInfo; + var sourceStack; + var targetStack; + var maybeStack; + var expandingFlags; + var depth = 0; + var overflow = false; + var elaborateErrors = false; + ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); + var result = isRelatedTo(source, target, errorNode !== undefined, headMessage); + if (overflow) { + error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + } + else if (errorInfo) { + // If we already computed this relation, but in a context where we didn't want to report errors (e.g. overload resolution), + // then we'll only have a top-level error (e.g. 'Class X does not implement interface Y') without any details. If this happened, + // request a recompuation to get a complete error message. This will be skipped if we've already done this computation in a context + // where errors were being reported. + if (errorInfo.next === undefined) { + errorInfo = undefined; + elaborateErrors = true; + isRelatedTo(source, target, errorNode !== undefined, headMessage); + } + if (containingMessageChain) { + errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + } + return result !== 0 /* False */; + function reportError(message, arg0, arg1, arg2) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); + } + function reportRelationError(message, source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if (sourceType === targetType) { + sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */); + targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */); + } + reportError(message || ts.Diagnostics.Type_0_is_not_assignable_to_type_1, sourceType, targetType); + } + // Compare two types and return + // Ternary.True if they are related with no assumptions, + // Ternary.Maybe if they are related with assumptions of other relationships, or + // Ternary.False if they are not related. + function isRelatedTo(source, target, reportErrors, headMessage) { + var result; + // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases + if (source === target) + return -1 /* True */; + if (relation === identityRelation) { + return isIdenticalTo(source, target); + } + if (isTypeAny(target)) + return -1 /* True */; + if (source === undefinedType) + return -1 /* True */; + if (source === nullType && target !== undefinedType) + return -1 /* True */; + if (source.flags & 128 /* Enum */ && target === numberType) + return -1 /* True */; + if (source.flags & 256 /* StringLiteral */ && target === stringType) + return -1 /* True */; + if (relation === assignableRelation) { + if (isTypeAny(source)) + return -1 /* True */; + if (source === numberType && target.flags & 128 /* Enum */) + return -1 /* True */; + } + if (source.flags & 1048576 /* FreshObjectLiteral */) { + if (hasExcessProperties(source, target, reportErrors)) { + if (reportErrors) { + reportRelationError(headMessage, source, target); + } + return 0 /* False */; + } + // Above we check for excess properties with respect to the entire target type. When union + // and intersection types are further deconstructed on the target side, we don't want to + // make the check again (as it might fail for a partial target type). Therefore we obtain + // the regular source type and proceed with that. + if (target.flags & 49152 /* UnionOrIntersection */) { + source = getRegularTypeOfObjectLiteral(source); + } + } + var saveErrorInfo = errorInfo; + // Note that the "each" checks must precede the "some" checks to produce the correct results + if (source.flags & 16384 /* Union */) { + if (result = eachTypeRelatedToType(source, target, reportErrors)) { + return result; + } + } + else if (target.flags & 32768 /* Intersection */) { + if (result = typeRelatedToEachType(source, target, reportErrors)) { + return result; + } + } + else { + // It is necessary to try "some" checks on both sides because there may be nested "each" checks + // on either side that need to be prioritized. For example, A | B = (A | B) & (C | D) or + // A & B = (A & B) | (C & D). + if (source.flags & 32768 /* Intersection */) { + // If target is a union type the following check will report errors so we suppress them here + if (result = someTypeRelatedToType(source, target, reportErrors && !(target.flags & 16384 /* Union */))) { + return result; + } + } + if (target.flags & 16384 /* Union */) { + if (result = typeRelatedToSomeType(source, target, reportErrors)) { + return result; + } + } + } + if (source.flags & 512 /* TypeParameter */) { + var constraint = getConstraintOfTypeParameter(source); + if (!constraint || constraint.flags & 1 /* Any */) { + constraint = emptyObjectType; + } + // Report constraint errors only if the constraint is not the empty object type + var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; + if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else { + if (source.flags & 4096 /* Reference */ && target.flags & 4096 /* Reference */ && source.target === target.target) { + // We have type references to same target type, see if relationship holds for all type arguments + if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { + return result; + } + } + // Even if relationship doesn't hold for unions, intersections, or generic type references, + // it may hold in a structural comparison. + var apparentType = getApparentType(source); + // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates + // to X. Failing both of those we want to check if the aggregation of A and B's members structurally + // relates to X. Thus, we include intersection types on the source side here. + if (apparentType.flags & (80896 /* ObjectType */ | 32768 /* Intersection */) && target.flags & 80896 /* ObjectType */) { + // Report structural errors only if we haven't reported any errors yet + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo; + if (result = objectTypeRelatedTo(apparentType, target, reportStructuralErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + if (reportErrors) { + reportRelationError(headMessage, source, target); + } + return 0 /* False */; + } + function isIdenticalTo(source, target) { + var result; + if (source.flags & 80896 /* ObjectType */ && target.flags & 80896 /* ObjectType */) { + if (source.flags & 4096 /* Reference */ && target.flags & 4096 /* Reference */ && source.target === target.target) { + // We have type references to same target type, see if all type arguments are identical + if (result = typeArgumentsRelatedTo(source, target, /*reportErrors*/ false)) { + return result; + } + } + return objectTypeRelatedTo(source, target, /*reportErrors*/ false); + } + if (source.flags & 512 /* TypeParameter */ && target.flags & 512 /* TypeParameter */) { + return typeParameterIdenticalTo(source, target); + } + if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || + source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { + if (result = eachTypeRelatedToSomeType(source, target)) { + if (result &= eachTypeRelatedToSomeType(target, source)) { + return result; + } + } + } + return 0 /* False */; + } + // Check if a property with the given name is known anywhere in the given type. In an object type, a property + // is considered known if the object type is empty and the check is for assignability, if the object type has + // index signatures, or if the property is actually declared in the object type. In a union or intersection + // type, a property is considered known if it is known in any constituent type. + function isKnownProperty(type, name) { + if (type.flags & 80896 /* ObjectType */) { + var resolved = resolveStructuredTypeMembers(type); + if (relation === assignableRelation && (type === globalObjectType || resolved.properties.length === 0) || + resolved.stringIndexType || resolved.numberIndexType || getPropertyOfType(type, name)) { + return true; + } + return false; + } + if (type.flags & 49152 /* UnionOrIntersection */) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name)) { + return true; + } + } + return false; + } + return true; + } + function hasExcessProperties(source, target, reportErrors) { + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!isKnownProperty(target, prop.name)) { + if (reportErrors) { + // We know *exactly* where things went wrong when comparing the types. + // Use this property as the error node as this will be more helpful in + // reasoning about what went wrong. + errorNode = prop.valueDeclaration; + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); + } + return true; + } + } + } + function eachTypeRelatedToSomeType(source, target) { + var result = -1 /* True */; + var sourceTypes = source.types; + for (var _i = 0; _i < sourceTypes.length; _i++) { + var sourceType = sourceTypes[_i]; + var related = typeRelatedToSomeType(sourceType, target, false); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function typeRelatedToSomeType(source, target, reportErrors) { + var targetTypes = target.types; + for (var i = 0, len = targetTypes.length; i < len; i++) { + var related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); + if (related) { + return related; + } + } + return 0 /* False */; + } + function typeRelatedToEachType(source, target, reportErrors) { + var result = -1 /* True */; + var targetTypes = target.types; + for (var _i = 0; _i < targetTypes.length; _i++) { + var targetType = targetTypes[_i]; + var related = isRelatedTo(source, targetType, reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function someTypeRelatedToType(source, target, reportErrors) { + var sourceTypes = source.types; + for (var i = 0, len = sourceTypes.length; i < len; i++) { + var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); + if (related) { + return related; + } + } + return 0 /* False */; + } + function eachTypeRelatedToType(source, target, reportErrors) { + var result = -1 /* True */; + var sourceTypes = source.types; + for (var _i = 0; _i < sourceTypes.length; _i++) { + var sourceType = sourceTypes[_i]; + var related = isRelatedTo(sourceType, target, reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function typeArgumentsRelatedTo(source, target, reportErrors) { + var sources = source.typeArguments || emptyArray; + var targets = target.typeArguments || emptyArray; + if (sources.length !== targets.length && relation === identityRelation) { + return 0 /* False */; + } + var result = -1 /* True */; + for (var i = 0; i < targets.length; i++) { + var related = isRelatedTo(sources[i], targets[i], reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function typeParameterIdenticalTo(source, target) { + if (source.symbol.name !== target.symbol.name) { + return 0 /* False */; + } + // covers case when both type parameters does not have constraint (both equal to noConstraintType) + if (source.constraint === target.constraint) { + return -1 /* True */; + } + if (source.constraint === noConstraintType || target.constraint === noConstraintType) { + return 0 /* False */; + } + return isIdenticalTo(source.constraint, target.constraint); + } + // Determine if two object types are related by structure. First, check if the result is already available in the global cache. + // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true. + // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are + // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion + // and issue an error. Otherwise, actually compare the structure of the two types. + function objectTypeRelatedTo(source, target, reportErrors) { + if (overflow) { + return 0 /* False */; + } + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var related = relation[id]; + if (related !== undefined) { + // If we computed this relation already and it was failed and reported, or if we're not being asked to elaborate + // errors, we can use the cached value. Otherwise, recompute the relation + if (!elaborateErrors || (related === 3 /* FailedAndReported */)) { + return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; + } + } + if (depth > 0) { + for (var i = 0; i < depth; i++) { + // If source and target are already being compared, consider them related with assumptions + if (maybeStack[i][id]) { + return 1 /* Maybe */; + } + } + if (depth === 100) { + overflow = true; + return 0 /* False */; + } + } + else { + sourceStack = []; + targetStack = []; + maybeStack = []; + expandingFlags = 0; + } + sourceStack[depth] = source; + targetStack[depth] = target; + maybeStack[depth] = {}; + maybeStack[depth][id] = 1 /* Succeeded */; + depth++; + var saveExpandingFlags = expandingFlags; + if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack, depth)) + expandingFlags |= 1; + if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth)) + expandingFlags |= 2; + var result; + if (expandingFlags === 3) { + result = 1 /* Maybe */; + } + else { + result = propertiesRelatedTo(source, target, reportErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportErrors); + if (result) { + result &= stringIndexTypesRelatedTo(source, target, reportErrors); + if (result) { + result &= numberIndexTypesRelatedTo(source, target, reportErrors); + } + } + } + } + } + expandingFlags = saveExpandingFlags; + depth--; + if (result) { + var maybeCache = maybeStack[depth]; + // If result is definitely true, copy assumptions to global cache, else copy to next level up + var destinationCache = (result === -1 /* True */ || depth === 0) ? relation : maybeStack[depth - 1]; + ts.copyMap(maybeCache, destinationCache); + } + else { + // A false result goes straight into global cache (when something is false under assumptions it + // will also be false without assumptions) + relation[id] = reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */; + } + return result; + } + function propertiesRelatedTo(source, target, reportErrors) { + if (relation === identityRelation) { + return propertiesIdenticalTo(source, target); + } + var result = -1 /* True */; + var properties = getPropertiesOfObjectType(target); + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288 /* ObjectLiteral */); + for (var _i = 0; _i < properties.length; _i++) { + var targetProp = properties[_i]; + var sourceProp = getPropertyOfType(source, targetProp.name); + if (sourceProp !== targetProp) { + if (!sourceProp) { + if (!(targetProp.flags & 536870912 /* Optional */) || requireOptionalProperties) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); + } + return 0 /* False */; + } + } + else if (!(targetProp.flags & 134217728 /* Prototype */)) { + var sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); + var targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); + if (sourcePropFlags & 32 /* Private */ || targetPropFlags & 32 /* Private */) { + if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { + if (reportErrors) { + if (sourcePropFlags & 32 /* Private */ && targetPropFlags & 32 /* Private */) { + reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); + } + else { + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 32 /* Private */ ? source : target), typeToString(sourcePropFlags & 32 /* Private */ ? target : source)); + } + } + return 0 /* False */; + } + } + else if (targetPropFlags & 64 /* Protected */) { + var sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & 32 /* Class */; + var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(sourceProp.parent) : undefined; + var targetClass = getDeclaredTypeOfSymbol(targetProp.parent); + if (!sourceClass || !hasBaseType(sourceClass, targetClass)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(sourceClass || source), typeToString(targetClass)); + } + return 0 /* False */; + } + } + else if (sourcePropFlags & 64 /* Protected */) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); + } + return 0 /* False */; + } + result &= related; + if (sourceProp.flags & 536870912 /* Optional */ && !(targetProp.flags & 536870912 /* Optional */)) { + // TypeScript 1.0 spec (April 2014): 3.8.3 + // S is a subtype of a type T, and T is a supertype of S if ... + // S' and T are object types and, for each member M in T.. + // M is a property and S' contains a property N where + // if M is a required property, N is also a required property + // (M - property in T) + // (N - property in S) + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + } + } + } + return result; + } + function propertiesIdenticalTo(source, target) { + if (!(source.flags & 80896 /* ObjectType */ && target.flags & 80896 /* ObjectType */)) { + return 0 /* False */; + } + var sourceProperties = getPropertiesOfObjectType(source); + var targetProperties = getPropertiesOfObjectType(target); + if (sourceProperties.length !== targetProperties.length) { + return 0 /* False */; + } + var result = -1 /* True */; + for (var _i = 0; _i < sourceProperties.length; _i++) { + var sourceProp = sourceProperties[_i]; + var targetProp = getPropertyOfObjectType(target, sourceProp.name); + if (!targetProp) { + return 0 /* False */; + } + var related = compareProperties(sourceProp, targetProp, isRelatedTo); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function signaturesRelatedTo(source, target, kind, reportErrors) { + if (relation === identityRelation) { + return signaturesIdenticalTo(source, target, kind); + } + if (target === anyFunctionType || source === anyFunctionType) { + return -1 /* True */; + } + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + var result = -1 /* True */; + var saveErrorInfo = errorInfo; + if (kind === 1 /* Construct */) { + // Only want to compare the construct signatures for abstractness guarantees. + // Because the "abstractness" of a class is the same across all construct signatures + // (internally we are checking the corresponding declaration), it is enough to perform + // the check and report an error once over all pairs of source and target construct signatures. + // + // sourceSig and targetSig are (possibly) undefined. + // + // Note that in an extends-clause, targetSignatures is stripped, so the check never proceeds. + var sourceSig = sourceSignatures[0]; + var targetSig = targetSignatures[0]; + result &= abstractSignatureRelatedTo(source, sourceSig, target, targetSig); + if (result !== -1 /* True */) { + return result; + } + } + outer: for (var _i = 0; _i < targetSignatures.length; _i++) { + var t = targetSignatures[_i]; + if (!t.hasStringLiterals || target.flags & 262144 /* FromSignature */) { + var localErrors = reportErrors; + var checkedAbstractAssignability = false; + for (var _a = 0; _a < sourceSignatures.length; _a++) { + var s = sourceSignatures[_a]; + if (!s.hasStringLiterals || source.flags & 262144 /* FromSignature */) { + var related = signatureRelatedTo(s, t, localErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + // Only report errors from the first failure + localErrors = false; + } + } + return 0 /* False */; + } + } + return result; + function abstractSignatureRelatedTo(source, sourceSig, target, targetSig) { + if (sourceSig && targetSig) { + var sourceDecl = source.symbol && getClassLikeDeclarationOfSymbol(source.symbol); + var targetDecl = target.symbol && getClassLikeDeclarationOfSymbol(target.symbol); + if (!sourceDecl) { + // If the source object isn't itself a class declaration, it can be freely assigned, regardless + // of whether the constructed object is abstract or not. + return -1 /* True */; + } + var sourceErasedSignature = getErasedSignature(sourceSig); + var targetErasedSignature = getErasedSignature(targetSig); + var sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature); + var targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); + var sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getClassLikeDeclarationOfSymbol(sourceReturnType.symbol); + var targetReturnDecl = targetReturnType && targetReturnType.symbol && getClassLikeDeclarationOfSymbol(targetReturnType.symbol); + var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 256 /* Abstract */; + var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 256 /* Abstract */; + if (sourceIsAbstract && !(targetIsAbstract && targetDecl)) { + // if target isn't a class-declaration type, then it can be new'd, so we forbid the assignment. + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0 /* False */; + } + } + return -1 /* True */; + } + } + function signatureRelatedTo(source, target, reportErrors) { + if (source === target) { + return -1 /* True */; + } + if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + return 0 /* False */; + } + var sourceMax = source.parameters.length; + var targetMax = target.parameters.length; + var checkCount; + if (source.hasRestParameter && target.hasRestParameter) { + checkCount = sourceMax > targetMax ? sourceMax : targetMax; + sourceMax--; + targetMax--; + } + else if (source.hasRestParameter) { + sourceMax--; + checkCount = targetMax; + } + else if (target.hasRestParameter) { + targetMax--; + checkCount = sourceMax; + } + else { + checkCount = sourceMax < targetMax ? sourceMax : targetMax; + } + // Spec 1.0 Section 3.8.3 & 3.8.4: + // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N + source = getErasedSignature(source); + target = getErasedSignature(target); + var result = -1 /* True */; + for (var i = 0; i < checkCount; i++) { + var s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); + var t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); + var saveErrorInfo = errorInfo; + var related = isRelatedTo(s, t, reportErrors); + if (!related) { + related = isRelatedTo(t, s, false); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, source.parameters[i < sourceMax ? i : sourceMax].name, target.parameters[i < targetMax ? i : targetMax].name); + } + return 0 /* False */; + } + errorInfo = saveErrorInfo; + } + result &= related; + } + if (source.typePredicate && target.typePredicate) { + var hasDifferentParameterIndex = source.typePredicate.parameterIndex !== target.typePredicate.parameterIndex; + var hasDifferentTypes; + if (hasDifferentParameterIndex || + (hasDifferentTypes = !isTypeIdenticalTo(source.typePredicate.type, target.typePredicate.type))) { + if (reportErrors) { + var sourceParamText = source.typePredicate.parameterName; + var targetParamText = target.typePredicate.parameterName; + var sourceTypeText = typeToString(source.typePredicate.type); + var targetTypeText = typeToString(target.typePredicate.type); + if (hasDifferentParameterIndex) { + reportError(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceParamText, targetParamText); + } + else if (hasDifferentTypes) { + reportError(ts.Diagnostics.Type_0_is_not_assignable_to_type_1, sourceTypeText, targetTypeText); + } + reportError(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, sourceParamText + " is " + sourceTypeText, targetParamText + " is " + targetTypeText); + } + return 0 /* False */; + } + } + else if (!source.typePredicate && target.typePredicate) { + if (reportErrors) { + reportError(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); + } + return 0 /* False */; + } + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) + return result; + var sourceReturnType = getReturnTypeOfSignature(source); + return result & isRelatedTo(sourceReturnType, targetReturnType, reportErrors); + } + function signaturesIdenticalTo(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + if (sourceSignatures.length !== targetSignatures.length) { + return 0 /* False */; + } + var result = -1 /* True */; + for (var i = 0, len = sourceSignatures.length; i < len; ++i) { + var related = compareSignatures(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function stringIndexTypesRelatedTo(source, target, reportErrors) { + if (relation === identityRelation) { + return indexTypesIdenticalTo(0 /* String */, source, target); + } + var targetType = getIndexTypeOfType(target, 0 /* String */); + if (targetType && !(targetType.flags & 1 /* Any */)) { + var sourceType = getIndexTypeOfType(source, 0 /* String */); + if (!sourceType) { + if (reportErrors) { + reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + } + return 0 /* False */; + } + var related = isRelatedTo(sourceType, targetType, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Index_signatures_are_incompatible); + } + return 0 /* False */; + } + return related; + } + return -1 /* True */; + } + function numberIndexTypesRelatedTo(source, target, reportErrors) { + if (relation === identityRelation) { + return indexTypesIdenticalTo(1 /* Number */, source, target); + } + var targetType = getIndexTypeOfType(target, 1 /* Number */); + if (targetType && !(targetType.flags & 1 /* Any */)) { + var sourceStringType = getIndexTypeOfType(source, 0 /* String */); + var sourceNumberType = getIndexTypeOfType(source, 1 /* Number */); + if (!(sourceStringType || sourceNumberType)) { + if (reportErrors) { + reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + } + return 0 /* False */; + } + var related; + if (sourceStringType && sourceNumberType) { + // If we know for sure we're testing both string and numeric index types then only report errors from the second one + related = isRelatedTo(sourceStringType, targetType, false) || isRelatedTo(sourceNumberType, targetType, reportErrors); + } + else { + related = isRelatedTo(sourceStringType || sourceNumberType, targetType, reportErrors); + } + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Index_signatures_are_incompatible); + } + return 0 /* False */; + } + return related; + } + return -1 /* True */; + } + function indexTypesIdenticalTo(indexKind, source, target) { + var targetType = getIndexTypeOfType(target, indexKind); + var sourceType = getIndexTypeOfType(source, indexKind); + if (!sourceType && !targetType) { + return -1 /* True */; + } + if (sourceType && targetType) { + return isRelatedTo(sourceType, targetType); + } + return 0 /* False */; + } + } + // Return true if the given type is part of a deeply nested chain of generic instantiations. We consider this to be the case + // when structural type comparisons have been started for 10 or more instantiations of the same generic type. It is possible, + // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely expanding. + // Effectively, we will generate a false positive when two types are structurally equal to at least 10 levels, but unequal at + // some level beyond that. + function isDeeplyNestedGeneric(type, stack, depth) { + // We track type references (created by createTypeReference) and instantiated types (created by instantiateType) + if (type.flags & (4096 /* Reference */ | 131072 /* Instantiated */) && depth >= 5) { + var symbol = type.symbol; + var count = 0; + for (var i = 0; i < depth; i++) { + var t = stack[i]; + if (t.flags & (4096 /* Reference */ | 131072 /* Instantiated */) && t.symbol === symbol) { + count++; + if (count >= 5) + return true; + } + } + } + return false; + } + function isPropertyIdenticalTo(sourceProp, targetProp) { + return compareProperties(sourceProp, targetProp, compareTypes) !== 0 /* False */; + } + function compareProperties(sourceProp, targetProp, compareTypes) { + // Two members are considered identical when + // - they are public properties with identical names, optionality, and types, + // - they are private or protected properties originating in the same declaration and having identical types + if (sourceProp === targetProp) { + return -1 /* True */; + } + var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (32 /* Private */ | 64 /* Protected */); + var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (32 /* Private */ | 64 /* Protected */); + if (sourcePropAccessibility !== targetPropAccessibility) { + return 0 /* False */; + } + if (sourcePropAccessibility) { + if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { + return 0 /* False */; + } + } + else { + if ((sourceProp.flags & 536870912 /* Optional */) !== (targetProp.flags & 536870912 /* Optional */)) { + return 0 /* False */; + } + } + return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + function compareSignatures(source, target, partialMatch, ignoreReturnTypes, compareTypes) { + if (source === target) { + return -1 /* True */; + } + if (source.parameters.length !== target.parameters.length || + source.minArgumentCount !== target.minArgumentCount || + source.hasRestParameter !== target.hasRestParameter) { + if (!partialMatch || + source.parameters.length < target.parameters.length && !source.hasRestParameter || + source.minArgumentCount > target.minArgumentCount) { + return 0 /* False */; + } + } + var result = -1 /* True */; + if (source.typeParameters && target.typeParameters) { + if (source.typeParameters.length !== target.typeParameters.length) { + return 0 /* False */; + } + for (var i = 0, len = source.typeParameters.length; i < len; ++i) { + var related = compareTypes(source.typeParameters[i], target.typeParameters[i]); + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + else if (source.typeParameters || target.typeParameters) { + return 0 /* False */; + } + // Spec 1.0 Section 3.8.3 & 3.8.4: + // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N + source = getErasedSignature(source); + target = getErasedSignature(target); + var targetLen = target.parameters.length; + for (var i = 0; i < targetLen; i++) { + var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]); + var t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfSymbol(target.parameters[i]); + var related = compareTypes(s, t); + if (!related) { + return 0 /* False */; + } + result &= related; + } + if (!ignoreReturnTypes) { + result &= compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + return result; + } + function isRestParameterIndex(signature, parameterIndex) { + return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; + } + function isSupertypeOfEach(candidate, types) { + for (var _i = 0; _i < types.length; _i++) { + var type = types[_i]; + if (candidate !== type && !isTypeSubtypeOf(type, candidate)) + return false; + } + return true; + } + function getCommonSupertype(types) { + return ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); + } + function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { + // The downfallType/bestSupertypeDownfallType is the first type that caused a particular candidate + // to not be the common supertype. So if it weren't for this one downfallType (and possibly others), + // the type in question could have been the common supertype. + var bestSupertype; + var bestSupertypeDownfallType; + var bestSupertypeScore = 0; + for (var i = 0; i < types.length; i++) { + var score = 0; + var downfallType = undefined; + for (var j = 0; j < types.length; j++) { + if (isTypeSubtypeOf(types[j], types[i])) { + score++; + } + else if (!downfallType) { + downfallType = types[j]; + } + } + ts.Debug.assert(!!downfallType, "If there is no common supertype, each type should have a downfallType"); + if (score > bestSupertypeScore) { + bestSupertype = types[i]; + bestSupertypeDownfallType = downfallType; + bestSupertypeScore = score; + } + // types.length - 1 is the maximum score, given that getCommonSupertype returned false + if (bestSupertypeScore === types.length - 1) { + break; + } + } + // In the following errors, the {1} slot is before the {0} slot because checkTypeSubtypeOf supplies the + // subtype as the first argument to the error + checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); + } + function isArrayType(type) { + return type.flags & 4096 /* Reference */ && type.target === globalArrayType; + } + function isArrayLikeType(type) { + // A type is array-like if it is not the undefined or null type and if it is assignable to any[] + return !(type.flags & (32 /* Undefined */ | 64 /* Null */)) && isTypeAssignableTo(type, anyArrayType); + } + function isTupleLikeType(type) { + return !!getPropertyOfType(type, "0"); + } + /** + * Check if a Type was written as a tuple type literal. + * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. + */ + function isTupleType(type) { + return !!(type.flags & 8192 /* Tuple */); + } + function getRegularTypeOfObjectLiteral(type) { + if (type.flags & 1048576 /* FreshObjectLiteral */) { + var regularType = type.regularType; + if (!regularType) { + regularType = createType(type.flags & ~1048576 /* FreshObjectLiteral */); + regularType.symbol = type.symbol; + regularType.members = type.members; + regularType.properties = type.properties; + regularType.callSignatures = type.callSignatures; + regularType.constructSignatures = type.constructSignatures; + regularType.stringIndexType = type.stringIndexType; + regularType.numberIndexType = type.numberIndexType; + type.regularType = regularType; + } + return regularType; + } + return type; + } + function getWidenedTypeOfObjectLiteral(type) { + var properties = getPropertiesOfObjectType(type); + var members = {}; + ts.forEach(properties, function (p) { + var propType = getTypeOfSymbol(p); + var widenedType = getWidenedType(propType); + if (propType !== widenedType) { + var symbol = createSymbol(p.flags | 67108864 /* Transient */, p.name); + symbol.declarations = p.declarations; + symbol.parent = p.parent; + symbol.type = widenedType; + symbol.target = p; + if (p.valueDeclaration) + symbol.valueDeclaration = p.valueDeclaration; + p = symbol; + } + members[p.name] = p; + }); + var stringIndexType = getIndexTypeOfType(type, 0 /* String */); + var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); + if (stringIndexType) + stringIndexType = getWidenedType(stringIndexType); + if (numberIndexType) + numberIndexType = getWidenedType(numberIndexType); + return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexType, numberIndexType); + } + function getWidenedType(type) { + if (type.flags & 6291456 /* RequiresWidening */) { + if (type.flags & (32 /* Undefined */ | 64 /* Null */)) { + return anyType; + } + if (type.flags & 524288 /* ObjectLiteral */) { + return getWidenedTypeOfObjectLiteral(type); + } + if (type.flags & 16384 /* Union */) { + return getUnionType(ts.map(type.types, getWidenedType), /*noSubtypeReduction*/ true); + } + if (isArrayType(type)) { + return createArrayType(getWidenedType(type.typeArguments[0])); + } + if (isTupleType(type)) { + return createTupleType(ts.map(type.elementTypes, getWidenedType)); + } + } + return type; + } + /** + * Reports implicit any errors that occur as a result of widening 'null' and 'undefined' + * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to + * getWidenedType. But in some cases getWidenedType is called without reporting errors + * (type argument inference is an example). + * + * The return value indicates whether an error was in fact reported. The particular circumstances + * are on a best effort basis. Currently, if the null or undefined that causes widening is inside + * an object literal property (arbitrarily deeply), this function reports an error. If no error is + * reported, reportImplicitAnyError is a suitable fallback to report a general error. + */ + function reportWideningErrorsInType(type) { + var errorReported = false; + if (type.flags & 16384 /* Union */) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + if (isArrayType(type)) { + return reportWideningErrorsInType(type.typeArguments[0]); + } + if (isTupleType(type)) { + for (var _b = 0, _c = type.elementTypes; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + if (type.flags & 524288 /* ObjectLiteral */) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; + var t = getTypeOfSymbol(p); + if (t.flags & 2097152 /* ContainsUndefinedOrNull */) { + if (!reportWideningErrorsInType(t)) { + error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); + } + errorReported = true; + } + } + } + return errorReported; + } + function reportImplicitAnyError(declaration, type) { + var typeAsString = typeToString(getWidenedType(type)); + var diagnostic; + switch (declaration.kind) { + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; + break; + case 138 /* Parameter */: + diagnostic = declaration.dotDotDotToken ? + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; + break; + case 213 /* FunctionDeclaration */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 173 /* FunctionExpression */: + case 174 /* ArrowFunction */: + if (!declaration.name) { + error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + } + diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; + break; + default: + diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; + } + error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + } + function reportErrorsFromWidening(declaration, type) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 2097152 /* ContainsUndefinedOrNull */) { + // Report implicit any error within type if possible, otherwise report error on declaration + if (!reportWideningErrorsInType(type)) { + reportImplicitAnyError(declaration, type); + } + } + } + function forEachMatchingParameterType(source, target, callback) { + var sourceMax = source.parameters.length; + var targetMax = target.parameters.length; + var count; + if (source.hasRestParameter && target.hasRestParameter) { + count = sourceMax > targetMax ? sourceMax : targetMax; + sourceMax--; + targetMax--; + } + else if (source.hasRestParameter) { + sourceMax--; + count = targetMax; + } + else if (target.hasRestParameter) { + targetMax--; + count = sourceMax; + } + else { + count = sourceMax < targetMax ? sourceMax : targetMax; + } + for (var i = 0; i < count; i++) { + var s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); + var t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); + callback(s, t); + } + } + function createInferenceContext(typeParameters, inferUnionTypes) { + var inferences = []; + for (var _i = 0; _i < typeParameters.length; _i++) { + var unused = typeParameters[_i]; + inferences.push({ + primary: undefined, secondary: undefined, isFixed: false + }); + } + return { + typeParameters: typeParameters, + inferUnionTypes: inferUnionTypes, + inferences: inferences, + inferredTypes: new Array(typeParameters.length) + }; + } + function inferTypes(context, source, target) { + var sourceStack; + var targetStack; + var depth = 0; + var inferiority = 0; + inferFromTypes(source, target); + function isInProcess(source, target) { + for (var i = 0; i < depth; i++) { + if (source === sourceStack[i] && target === targetStack[i]) { + return true; + } + } + return false; + } + function inferFromTypes(source, target) { + if (target.flags & 512 /* TypeParameter */) { + // If target is a type parameter, make an inference, unless the source type contains + // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). + // Because the anyFunctionType is internal, it should not be exposed to the user by adding + // it as an inference candidate. Hopefully, a better candidate will come along that does + // not contain anyFunctionType when we come back to this argument for its second round + // of inference. + if (source.flags & 8388608 /* ContainsAnyFunctionType */) { + return; + } + var typeParameters = context.typeParameters; + for (var i = 0; i < typeParameters.length; i++) { + if (target === typeParameters[i]) { + var inferences = context.inferences[i]; + if (!inferences.isFixed) { + // Any inferences that are made to a type parameter in a union type are inferior + // to inferences made to a flat (non-union) type. This is because if we infer to + // T | string[], we really don't know if we should be inferring to T or not (because + // the correct constituent on the target side could be string[]). Therefore, we put + // such inferior inferences into a secondary bucket, and only use them if the primary + // bucket is empty. + var candidates = inferiority ? + inferences.secondary || (inferences.secondary = []) : + inferences.primary || (inferences.primary = []); + if (!ts.contains(candidates, source)) { + candidates.push(source); + } + } + return; + } + } + } + else if (source.flags & 4096 /* Reference */ && target.flags & 4096 /* Reference */ && source.target === target.target) { + // If source and target are references to the same generic type, infer from type arguments + var sourceTypes = source.typeArguments || emptyArray; + var targetTypes = target.typeArguments || emptyArray; + var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + for (var i = 0; i < count; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + else if (source.flags & 8192 /* Tuple */ && target.flags & 8192 /* Tuple */ && source.elementTypes.length === target.elementTypes.length) { + // If source and target are tuples of the same size, infer from element types + var sourceTypes = source.elementTypes; + var targetTypes = target.elementTypes; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + else if (target.flags & 49152 /* UnionOrIntersection */) { + var targetTypes = target.types; + var typeParameterCount = 0; + var typeParameter; + // First infer to each type in union or intersection that isn't a type parameter + for (var _i = 0; _i < targetTypes.length; _i++) { + var t = targetTypes[_i]; + if (t.flags & 512 /* TypeParameter */ && ts.contains(context.typeParameters, t)) { + typeParameter = t; + typeParameterCount++; + } + else { + inferFromTypes(source, t); + } + } + // Next, if target is a union type containing a single naked type parameter, make a + // secondary inference to that type parameter. We don't do this for intersection types + // because in a target type like Foo & T we don't know how which parts of the source type + // should be matched by Foo and which should be inferred to T. + if (target.flags & 16384 /* Union */ && typeParameterCount === 1) { + inferiority++; + inferFromTypes(source, typeParameter); + inferiority--; + } + } + else if (source.flags & 49152 /* UnionOrIntersection */) { + // Source is a union or intersection type, infer from each consituent type + var sourceTypes = source.types; + for (var _a = 0; _a < sourceTypes.length; _a++) { + var sourceType = sourceTypes[_a]; + inferFromTypes(sourceType, target); + } + } + else { + source = getApparentType(source); + if (source.flags & 80896 /* ObjectType */ && (target.flags & 4096 /* Reference */ && target.typeArguments || + target.flags & 8192 /* Tuple */ || + target.flags & 65536 /* Anonymous */ && target.symbol && target.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */))) { + // If source is an object type, and target is a type reference with type arguments, a tuple type, + // the type of a method, or a type literal, infer from members + if (isInProcess(source, target)) { + return; + } + if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { + return; + } + if (depth === 0) { + sourceStack = []; + targetStack = []; + } + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + inferFromProperties(source, target); + inferFromSignatures(source, target, 0 /* Call */); + inferFromSignatures(source, target, 1 /* Construct */); + inferFromIndexTypes(source, target, 0 /* String */, 0 /* String */); + inferFromIndexTypes(source, target, 1 /* Number */, 1 /* Number */); + inferFromIndexTypes(source, target, 0 /* String */, 1 /* Number */); + depth--; + } + } + } + function inferFromProperties(source, target) { + var properties = getPropertiesOfObjectType(target); + for (var _i = 0; _i < properties.length; _i++) { + var targetProp = properties[_i]; + var sourceProp = getPropertyOfObjectType(source, targetProp.name); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + } + } + function inferFromSignatures(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + var sourceLen = sourceSignatures.length; + var targetLen = targetSignatures.length; + var len = sourceLen < targetLen ? sourceLen : targetLen; + for (var i = 0; i < len; i++) { + inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); + } + } + function inferFromSignature(source, target) { + forEachMatchingParameterType(source, target, inferFromTypes); + if (source.typePredicate && target.typePredicate) { + if (target.typePredicate.parameterIndex === source.typePredicate.parameterIndex) { + // Return types from type predicates are treated as booleans. In order to infer types + // from type predicates we would need to infer using the type within the type predicate + // (i.e. 'Foo' from 'x is Foo'). + inferFromTypes(source.typePredicate.type, target.typePredicate.type); + } + } + else { + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + } + function inferFromIndexTypes(source, target, sourceKind, targetKind) { + var targetIndexType = getIndexTypeOfType(target, targetKind); + if (targetIndexType) { + var sourceIndexType = getIndexTypeOfType(source, sourceKind); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetIndexType); + } + } + } + } + function getInferenceCandidates(context, index) { + var inferences = context.inferences[index]; + return inferences.primary || inferences.secondary || emptyArray; + } + function getInferredType(context, index) { + var inferredType = context.inferredTypes[index]; + var inferenceSucceeded; + if (!inferredType) { + var inferences = getInferenceCandidates(context, index); + if (inferences.length) { + // Infer widened union or supertype, or the unknown type for no common supertype + var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); + inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; + inferenceSucceeded = !!unionOrSuperType; + } + else { + // Infer the empty object type when no inferences were made. It is important to remember that + // in this case, inference still succeeds, meaning there is no error for not having inference + // candidates. An inference error only occurs when there are *conflicting* candidates, i.e. + // candidates with no common supertype. + inferredType = emptyObjectType; + inferenceSucceeded = true; + } + // Only do the constraint check if inference succeeded (to prevent cascading errors) + if (inferenceSucceeded) { + var constraint = getConstraintOfTypeParameter(context.typeParameters[index]); + inferredType = constraint && !isTypeAssignableTo(inferredType, constraint) ? constraint : inferredType; + } + else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { + // If inference failed, it is necessary to record the index of the failed type parameter (the one we are on). + // It might be that inference has already failed on a later type parameter on a previous call to inferTypeArguments. + // So if this failure is on preceding type parameter, this type parameter is the new failure index. + context.failedTypeParameterIndex = index; + } + context.inferredTypes[index] = inferredType; + } + return inferredType; + } + function getInferredTypes(context) { + for (var i = 0; i < context.inferredTypes.length; i++) { + getInferredType(context, i); + } + return context.inferredTypes; + } + function hasAncestor(node, kind) { + return ts.getAncestor(node, kind) !== undefined; + } + // EXPRESSION TYPE CHECKING + function getResolvedSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + links.resolvedSymbol = (!ts.nodeIsMissing(node) && resolveName(node, node.text, 107455 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node)) || unknownSymbol; + } + return links.resolvedSymbol; + } + function isInTypeQuery(node) { + // TypeScript 1.0 spec (April 2014): 3.6.3 + // A type query consists of the keyword typeof followed by an expression. + // The expression is restricted to a single identifier or a sequence of identifiers separated by periods + while (node) { + switch (node.kind) { + case 154 /* TypeQuery */: + return true; + case 69 /* Identifier */: + case 135 /* QualifiedName */: + node = node.parent; + continue; + default: + return false; + } + } + ts.Debug.fail("should not get here"); + } + // For a union type, remove all constituent types that are of the given type kind (when isOfTypeKind is true) + // or not of the given type kind (when isOfTypeKind is false) + function removeTypesFromUnionType(type, typeKind, isOfTypeKind, allowEmptyUnionResult) { + if (type.flags & 16384 /* Union */) { + var types = type.types; + if (ts.forEach(types, function (t) { return !!(t.flags & typeKind) === isOfTypeKind; })) { + // Above we checked if we have anything to remove, now use the opposite test to do the removal + var narrowedType = getUnionType(ts.filter(types, function (t) { return !(t.flags & typeKind) === isOfTypeKind; })); + if (allowEmptyUnionResult || narrowedType !== emptyObjectType) { + return narrowedType; + } + } + } + else if (allowEmptyUnionResult && !!(type.flags & typeKind) === isOfTypeKind) { + // Use getUnionType(emptyArray) instead of emptyObjectType in case the way empty union types + // are represented ever changes. + return getUnionType(emptyArray); + } + return type; + } + function hasInitializer(node) { + return !!(node.initializer || ts.isBindingPattern(node.parent) && hasInitializer(node.parent.parent)); + } + // Check if a given variable is assigned within a given syntax node + function isVariableAssignedWithin(symbol, node) { + var links = getNodeLinks(node); + if (links.assignmentChecks) { + var cachedResult = links.assignmentChecks[symbol.id]; + if (cachedResult !== undefined) { + return cachedResult; + } + } + else { + links.assignmentChecks = {}; + } + return links.assignmentChecks[symbol.id] = isAssignedIn(node); + function isAssignedInBinaryExpression(node) { + if (node.operatorToken.kind >= 56 /* FirstAssignment */ && node.operatorToken.kind <= 68 /* LastAssignment */) { + var n = node.left; + while (n.kind === 172 /* ParenthesizedExpression */) { + n = n.expression; + } + if (n.kind === 69 /* Identifier */ && getResolvedSymbol(n) === symbol) { + return true; + } + } + return ts.forEachChild(node, isAssignedIn); + } + function isAssignedInVariableDeclaration(node) { + if (!ts.isBindingPattern(node.name) && getSymbolOfNode(node) === symbol && hasInitializer(node)) { + return true; + } + return ts.forEachChild(node, isAssignedIn); + } + function isAssignedIn(node) { + switch (node.kind) { + case 181 /* BinaryExpression */: + return isAssignedInBinaryExpression(node); + case 211 /* VariableDeclaration */: + case 163 /* BindingElement */: + return isAssignedInVariableDeclaration(node); + case 161 /* ObjectBindingPattern */: + case 162 /* ArrayBindingPattern */: + case 164 /* ArrayLiteralExpression */: + case 165 /* ObjectLiteralExpression */: + case 166 /* PropertyAccessExpression */: + case 167 /* ElementAccessExpression */: + case 168 /* CallExpression */: + case 169 /* NewExpression */: + case 171 /* TypeAssertionExpression */: + case 189 /* AsExpression */: + case 172 /* ParenthesizedExpression */: + case 179 /* PrefixUnaryExpression */: + case 175 /* DeleteExpression */: + case 178 /* AwaitExpression */: + case 176 /* TypeOfExpression */: + case 177 /* VoidExpression */: + case 180 /* PostfixUnaryExpression */: + case 184 /* YieldExpression */: + case 182 /* ConditionalExpression */: + case 185 /* SpreadElementExpression */: + case 192 /* Block */: + case 193 /* VariableStatement */: + case 195 /* ExpressionStatement */: + case 196 /* IfStatement */: + case 197 /* DoStatement */: + case 198 /* WhileStatement */: + case 199 /* ForStatement */: + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + case 204 /* ReturnStatement */: + case 205 /* WithStatement */: + case 206 /* SwitchStatement */: + case 241 /* CaseClause */: + case 242 /* DefaultClause */: + case 207 /* LabeledStatement */: + case 208 /* ThrowStatement */: + case 209 /* TryStatement */: + case 244 /* CatchClause */: + case 233 /* JsxElement */: + case 234 /* JsxSelfClosingElement */: + case 238 /* JsxAttribute */: + case 239 /* JsxSpreadAttribute */: + case 235 /* JsxOpeningElement */: + case 240 /* JsxExpression */: + return ts.forEachChild(node, isAssignedIn); + } + return false; + } + } + // Get the narrowed type of a given symbol at a given location + function getNarrowedTypeOfSymbol(symbol, node) { + var type = getTypeOfSymbol(symbol); + // Only narrow when symbol is variable of type any or an object, union, or type parameter type + if (node && symbol.flags & 3 /* Variable */) { + if (isTypeAny(type) || type.flags & (80896 /* ObjectType */ | 16384 /* Union */ | 512 /* TypeParameter */)) { + loop: while (node.parent) { + var child = node; + node = node.parent; + var narrowedType = type; + switch (node.kind) { + case 196 /* IfStatement */: + // In a branch of an if statement, narrow based on controlling expression + if (child !== node.expression) { + narrowedType = narrowType(type, node.expression, /*assumeTrue*/ child === node.thenStatement); + } + break; + case 182 /* ConditionalExpression */: + // In a branch of a conditional expression, narrow based on controlling condition + if (child !== node.condition) { + narrowedType = narrowType(type, node.condition, /*assumeTrue*/ child === node.whenTrue); + } + break; + case 181 /* BinaryExpression */: + // In the right operand of an && or ||, narrow based on left operand + if (child === node.right) { + if (node.operatorToken.kind === 51 /* AmpersandAmpersandToken */) { + narrowedType = narrowType(type, node.left, /*assumeTrue*/ true); + } + else if (node.operatorToken.kind === 52 /* BarBarToken */) { + narrowedType = narrowType(type, node.left, /*assumeTrue*/ false); + } + } + break; + case 248 /* SourceFile */: + case 218 /* ModuleDeclaration */: + case 213 /* FunctionDeclaration */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 144 /* Constructor */: + // Stop at the first containing function or module declaration + break loop; + } + // Use narrowed type if construct contains no assignments to variable + if (narrowedType !== type) { + if (isVariableAssignedWithin(symbol, node)) { + break; + } + type = narrowedType; + } + } + } + } + return type; + function narrowTypeByEquality(type, expr, assumeTrue) { + // Check that we have 'typeof ' on the left and string literal on the right + if (expr.left.kind !== 176 /* TypeOfExpression */ || expr.right.kind !== 9 /* StringLiteral */) { + return type; + } + var left = expr.left; + var right = expr.right; + if (left.expression.kind !== 69 /* Identifier */ || getResolvedSymbol(left.expression) !== symbol) { + return type; + } + var typeInfo = primitiveTypeInfo[right.text]; + if (expr.operatorToken.kind === 33 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + if (assumeTrue) { + // Assumed result is true. If check was not for a primitive type, remove all primitive types + if (!typeInfo) { + return removeTypesFromUnionType(type, /*typeKind*/ 258 /* StringLike */ | 132 /* NumberLike */ | 8 /* Boolean */ | 16777216 /* ESSymbol */, + /*isOfTypeKind*/ true, /*allowEmptyUnionResult*/ false); + } + // Check was for a primitive type, return that primitive type if it is a subtype + if (isTypeSubtypeOf(typeInfo.type, type)) { + return typeInfo.type; + } + // Otherwise, remove all types that aren't of the primitive type kind. This can happen when the type is + // union of enum types and other types. + return removeTypesFromUnionType(type, /*typeKind*/ typeInfo.flags, /*isOfTypeKind*/ false, /*allowEmptyUnionResult*/ false); + } + else { + // Assumed result is false. If check was for a primitive type, remove that primitive type + if (typeInfo) { + return removeTypesFromUnionType(type, /*typeKind*/ typeInfo.flags, /*isOfTypeKind*/ true, /*allowEmptyUnionResult*/ false); + } + // Otherwise we don't have enough information to do anything. + return type; + } + } + function narrowTypeByAnd(type, expr, assumeTrue) { + if (assumeTrue) { + // The assumed result is true, therefore we narrow assuming each operand to be true. + return narrowType(narrowType(type, expr.left, /*assumeTrue*/ true), expr.right, /*assumeTrue*/ true); + } + else { + // The assumed result is false. This means either the first operand was false, or the first operand was true + // and the second operand was false. We narrow with those assumptions and union the two resulting types. + return getUnionType([ + narrowType(type, expr.left, /*assumeTrue*/ false), + narrowType(narrowType(type, expr.left, /*assumeTrue*/ true), expr.right, /*assumeTrue*/ false) + ]); + } + } + function narrowTypeByOr(type, expr, assumeTrue) { + if (assumeTrue) { + // The assumed result is true. This means either the first operand was true, or the first operand was false + // and the second operand was true. We narrow with those assumptions and union the two resulting types. + return getUnionType([ + narrowType(type, expr.left, /*assumeTrue*/ true), + narrowType(narrowType(type, expr.left, /*assumeTrue*/ false), expr.right, /*assumeTrue*/ true) + ]); + } + else { + // The assumed result is false, therefore we narrow assuming each operand to be false. + return narrowType(narrowType(type, expr.left, /*assumeTrue*/ false), expr.right, /*assumeTrue*/ false); + } + } + function narrowTypeByInstanceof(type, expr, assumeTrue) { + // Check that type is not any, assumed result is true, and we have variable symbol on the left + if (isTypeAny(type) || !assumeTrue || expr.left.kind !== 69 /* Identifier */ || getResolvedSymbol(expr.left) !== symbol) { + return type; + } + // Check that right operand is a function type with a prototype property + var rightType = checkExpression(expr.right); + if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + return type; + } + var targetType; + var prototypeProperty = getPropertyOfType(rightType, "prototype"); + if (prototypeProperty) { + // Target type is type of the prototype property + var prototypePropertyType = getTypeOfSymbol(prototypeProperty); + if (!isTypeAny(prototypePropertyType)) { + targetType = prototypePropertyType; + } + } + if (!targetType) { + // Target type is type of construct signature + var constructSignatures; + if (rightType.flags & 2048 /* Interface */) { + constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; + } + else if (rightType.flags & 65536 /* Anonymous */) { + constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + } + if (constructSignatures && constructSignatures.length) { + targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); + } + } + if (targetType) { + return getNarrowedType(type, targetType); + } + return type; + } + function getNarrowedType(originalType, narrowedTypeCandidate) { + // If the current type is a union type, remove all constituents that aren't assignable to target. If that produces + // 0 candidates, fall back to the assignability check + if (originalType.flags & 16384 /* Union */) { + var assignableConstituents = ts.filter(originalType.types, function (t) { return isTypeAssignableTo(t, narrowedTypeCandidate); }); + if (assignableConstituents.length) { + return getUnionType(assignableConstituents); + } + } + if (isTypeAssignableTo(narrowedTypeCandidate, originalType)) { + // Narrow to the target type if it's assignable to the current type + return narrowedTypeCandidate; + } + return originalType; + } + function narrowTypeByTypePredicate(type, expr, assumeTrue) { + if (type.flags & 1 /* Any */) { + return type; + } + var signature = getResolvedSignature(expr); + if (signature.typePredicate && + expr.arguments[signature.typePredicate.parameterIndex] && + getSymbolAtLocation(expr.arguments[signature.typePredicate.parameterIndex]) === symbol) { + if (!assumeTrue) { + if (type.flags & 16384 /* Union */) { + return getUnionType(ts.filter(type.types, function (t) { return !isTypeSubtypeOf(t, signature.typePredicate.type); })); + } + return type; + } + return getNarrowedType(type, signature.typePredicate.type); + } + return type; + } + // Narrow the given type based on the given expression having the assumed boolean value. The returned type + // will be a subtype or the same type as the argument. + function narrowType(type, expr, assumeTrue) { + switch (expr.kind) { + case 168 /* CallExpression */: + return narrowTypeByTypePredicate(type, expr, assumeTrue); + case 172 /* ParenthesizedExpression */: + return narrowType(type, expr.expression, assumeTrue); + case 181 /* BinaryExpression */: + var operator = expr.operatorToken.kind; + if (operator === 32 /* EqualsEqualsEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { + return narrowTypeByEquality(type, expr, assumeTrue); + } + else if (operator === 51 /* AmpersandAmpersandToken */) { + return narrowTypeByAnd(type, expr, assumeTrue); + } + else if (operator === 52 /* BarBarToken */) { + return narrowTypeByOr(type, expr, assumeTrue); + } + else if (operator === 91 /* InstanceOfKeyword */) { + return narrowTypeByInstanceof(type, expr, assumeTrue); + } + break; + case 179 /* PrefixUnaryExpression */: + if (expr.operator === 49 /* ExclamationToken */) { + return narrowType(type, expr.operand, !assumeTrue); + } + break; + } + return type; + } + } + function checkIdentifier(node) { + var symbol = getResolvedSymbol(node); + // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. + // Although in down-level emit of arrow function, we emit it using function expression which means that + // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects + // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior. + // To avoid that we will give an error to users if they use arguments objects in arrow function so that they + // can explicitly bound arguments objects + if (symbol === argumentsSymbol) { + var container = ts.getContainingFunction(node); + if (container.kind === 174 /* ArrowFunction */) { + if (languageVersion < 2 /* ES6 */) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); + } + } + if (node.parserContextFlags & 8 /* Await */) { + getNodeLinks(container).flags |= 4096 /* CaptureArguments */; + getNodeLinks(node).flags |= 2048 /* LexicalArguments */; + } + } + if (symbol.flags & 8388608 /* Alias */ && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + markAliasSymbolAsReferenced(symbol); + } + checkCollisionWithCapturedSuperVariable(node, node); + checkCollisionWithCapturedThisVariable(node, node); + checkBlockScopedBindingCapturedInLoop(node, symbol); + return getNarrowedTypeOfSymbol(getExportSymbolOfValueSymbolIfExported(symbol), node); + } + function isInsideFunction(node, threshold) { + var current = node; + while (current && current !== threshold) { + if (ts.isFunctionLike(current)) { + return true; + } + current = current.parent; + } + return false; + } + function checkBlockScopedBindingCapturedInLoop(node, symbol) { + if (languageVersion >= 2 /* ES6 */ || + (symbol.flags & 2 /* BlockScopedVariable */) === 0 || + symbol.valueDeclaration.parent.kind === 244 /* CatchClause */) { + return; + } + // - check if binding is used in some function + // (stop the walk when reaching container of binding declaration) + // - if first check succeeded - check if variable is declared inside the loop + // nesting structure: + // (variable declaration or binding element) -> variable declaration list -> container + var container = symbol.valueDeclaration; + while (container.kind !== 212 /* VariableDeclarationList */) { + container = container.parent; + } + // get the parent of variable declaration list + container = container.parent; + if (container.kind === 193 /* VariableStatement */) { + // if parent is variable statement - get its parent + container = container.parent; + } + var inFunction = isInsideFunction(node.parent, container); + var current = container; + while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { + if (isIterationStatement(current, /*lookInLabeledStatements*/ false)) { + if (inFunction) { + grammarErrorOnFirstToken(current, ts.Diagnostics.Loop_contains_block_scoped_variable_0_referenced_by_a_function_in_the_loop_This_is_only_supported_in_ECMAScript_6_or_higher, ts.declarationNameToString(node)); + } + // mark value declaration so during emit they can have a special handling + getNodeLinks(symbol.valueDeclaration).flags |= 16384 /* BlockScopedBindingInLoop */; + break; + } + current = current.parent; + } + } + function captureLexicalThis(node, container) { + getNodeLinks(node).flags |= 2 /* LexicalThis */; + if (container.kind === 141 /* PropertyDeclaration */ || container.kind === 144 /* Constructor */) { + var classNode = container.parent; + getNodeLinks(classNode).flags |= 4 /* CaptureThis */; + } + else { + getNodeLinks(container).flags |= 4 /* CaptureThis */; + } + } + function checkThisExpression(node) { + // Stop at the first arrow function so that we can + // tell whether 'this' needs to be captured. + var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); + var needToCaptureLexicalThis = false; + // Now skip arrow functions to get the "real" owner of 'this'. + if (container.kind === 174 /* ArrowFunction */) { + container = ts.getThisContainer(container, /* includeArrowFunctions */ false); + // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code + needToCaptureLexicalThis = (languageVersion < 2 /* ES6 */); + } + switch (container.kind) { + case 218 /* ModuleDeclaration */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + break; + case 217 /* EnumDeclaration */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + break; + case 144 /* Constructor */: + if (isInConstructorArgumentInitializer(node, container)) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); + } + break; + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + if (container.flags & 128 /* Static */) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); + } + break; + case 136 /* ComputedPropertyName */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); + break; + } + if (needToCaptureLexicalThis) { + captureLexicalThis(node, container); + } + if (ts.isClassLike(container.parent)) { + var symbol = getSymbolOfNode(container.parent); + return container.flags & 128 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + } + return anyType; + } + function isInConstructorArgumentInitializer(node, constructorDecl) { + for (var n = node; n && n !== constructorDecl; n = n.parent) { + if (n.kind === 138 /* Parameter */) { + return true; + } + } + return false; + } + function checkSuperExpression(node) { + var isCallExpression = node.parent.kind === 168 /* CallExpression */ && node.parent.expression === node; + var classDeclaration = ts.getContainingClass(node); + var classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + var container = ts.getSuperContainer(node, /*includeFunctions*/ true); + var needToCaptureLexicalThis = false; + if (!isCallExpression) { + // adjust the container reference in case if super is used inside arrow functions with arbitrary deep nesting + while (container && container.kind === 174 /* ArrowFunction */) { + container = ts.getSuperContainer(container, /*includeFunctions*/ true); + needToCaptureLexicalThis = languageVersion < 2 /* ES6 */; + } + } + var canUseSuperExpression = isLegalUsageOfSuperExpression(container); + var nodeCheckFlag = 0; + // always set NodeCheckFlags for 'super' expression node + if (canUseSuperExpression) { + if ((container.flags & 128 /* Static */) || isCallExpression) { + nodeCheckFlag = 512 /* SuperStatic */; + } + else { + nodeCheckFlag = 256 /* SuperInstance */; + } + getNodeLinks(node).flags |= nodeCheckFlag; + if (needToCaptureLexicalThis) { + // call expressions are allowed only in constructors so they should always capture correct 'this' + // super property access expressions can also appear in arrow functions - + // in this case they should also use correct lexical this + captureLexicalThis(node.parent, container); + } + } + if (!baseClassType) { + if (!classDeclaration || !ts.getClassExtendsHeritageClauseElement(classDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } + return unknownType; + } + if (!canUseSuperExpression) { + if (container && container.kind === 136 /* ComputedPropertyName */) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); + } + else if (isCallExpression) { + error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); + } + else { + error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); + } + return unknownType; + } + if (container.kind === 144 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) + error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); + return unknownType; + } + return nodeCheckFlag === 512 /* SuperStatic */ + ? getBaseConstructorTypeOfClass(classType) + : baseClassType; + function isLegalUsageOfSuperExpression(container) { + if (!container) { + return false; + } + if (isCallExpression) { + // TS 1.0 SPEC (April 2014): 4.8.1 + // Super calls are only permitted in constructors of derived classes + return container.kind === 144 /* Constructor */; + } + else { + // TS 1.0 SPEC (April 2014) + // 'super' property access is allowed + // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance + // - In a static member function or static member accessor + // topmost container must be something that is directly nested in the class declaration + if (container && ts.isClassLike(container.parent)) { + if (container.flags & 128 /* Static */) { + return container.kind === 143 /* MethodDeclaration */ || + container.kind === 142 /* MethodSignature */ || + container.kind === 145 /* GetAccessor */ || + container.kind === 146 /* SetAccessor */; + } + else { + return container.kind === 143 /* MethodDeclaration */ || + container.kind === 142 /* MethodSignature */ || + container.kind === 145 /* GetAccessor */ || + container.kind === 146 /* SetAccessor */ || + container.kind === 141 /* PropertyDeclaration */ || + container.kind === 140 /* PropertySignature */ || + container.kind === 144 /* Constructor */; + } + } + } + return false; + } + } + // Return contextual type of parameter or undefined if no contextual type is available + function getContextuallyTypedParameterType(parameter) { + var func = parameter.parent; + if (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) { + if (isContextSensitive(func)) { + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var funcHasRestParameters = ts.hasRestParameter(func); + var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); + var indexOfParameter = ts.indexOf(func.parameters, parameter); + if (indexOfParameter < len) { + return getTypeAtPosition(contextualSignature, indexOfParameter); + } + // If last parameter is contextually rest parameter get its type + if (funcHasRestParameters && + indexOfParameter === (func.parameters.length - 1) && + isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { + return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); + } + } + } + } + return undefined; + } + // In a variable, parameter or property declaration with a type annotation, the contextual type of an initializer + // expression is the type of the variable, parameter or property. Otherwise, in a parameter declaration of a + // contextually typed function expression, the contextual type of an initializer expression is the contextual type + // of the parameter. Otherwise, in a variable or parameter declaration with a binding pattern name, the contextual + // type of an initializer expression is the type implied by the binding pattern. + function getContextualTypeForInitializerExpression(node) { + var declaration = node.parent; + if (node === declaration.initializer) { + if (declaration.type) { + return getTypeFromTypeNode(declaration.type); + } + if (declaration.kind === 138 /* Parameter */) { + var type = getContextuallyTypedParameterType(declaration); + if (type) { + return type; + } + } + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true); + } + } + return undefined; + } + function getContextualTypeForReturnExpression(node) { + var func = ts.getContainingFunction(node); + if (func && !func.asteriskToken) { + return getContextualReturnType(func); + } + return undefined; + } + function getContextualTypeForYieldOperand(node) { + var func = ts.getContainingFunction(node); + if (func) { + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + return node.asteriskToken + ? contextualReturnType + : getElementTypeOfIterableIterator(contextualReturnType); + } + } + return undefined; + } + function isInParameterInitializerBeforeContainingFunction(node) { + while (node.parent && !ts.isFunctionLike(node.parent)) { + if (node.parent.kind === 138 /* Parameter */ && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } + function getContextualReturnType(functionDecl) { + // If the containing function has a return type annotation, is a constructor, or is a get accessor whose + // corresponding set accessor has a type annotation, return statements in the function are contextually typed + if (functionDecl.type || + functionDecl.kind === 144 /* Constructor */ || + functionDecl.kind === 145 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 146 /* SetAccessor */))) { + return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); + } + // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature + // and that call signature is non-generic, return statements are contextually typed by the return type of the signature + var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); + if (signature) { + return getReturnTypeOfSignature(signature); + } + return undefined; + } + // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. + function getContextualTypeForArgument(callTarget, arg) { + var args = getEffectiveCallArguments(callTarget); + var argIndex = ts.indexOf(args, arg); + if (argIndex >= 0) { + var signature = getResolvedSignature(callTarget); + return getTypeAtPosition(signature, argIndex); + } + return undefined; + } + function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { + if (template.parent.kind === 170 /* TaggedTemplateExpression */) { + return getContextualTypeForArgument(template.parent, substitutionExpression); + } + return undefined; + } + function getContextualTypeForBinaryOperand(node) { + var binaryExpression = node.parent; + var operator = binaryExpression.operatorToken.kind; + if (operator >= 56 /* FirstAssignment */ && operator <= 68 /* LastAssignment */) { + // In an assignment expression, the right operand is contextually typed by the type of the left operand. + if (node === binaryExpression.right) { + return checkExpression(binaryExpression.left); + } + } + else if (operator === 52 /* BarBarToken */) { + // When an || expression has a contextual type, the operands are contextually typed by that type. When an || + // expression has no contextual type, the right operand is contextually typed by the type of the left operand. + var type = getContextualType(binaryExpression); + if (!type && node === binaryExpression.right) { + type = checkExpression(binaryExpression.left); + } + return type; + } + return undefined; + } + // Apply a mapping function to a contextual type and return the resulting type. If the contextual type + // is a union type, the mapping function is applied to each constituent type and a union of the resulting + // types is returned. + function applyToContextualType(type, mapper) { + if (!(type.flags & 16384 /* Union */)) { + return mapper(type); + } + var types = type.types; + var mappedType; + var mappedTypes; + for (var _i = 0; _i < types.length; _i++) { + var current = types[_i]; + var t = mapper(current); + if (t) { + if (!mappedType) { + mappedType = t; + } + else if (!mappedTypes) { + mappedTypes = [mappedType, t]; + } + else { + mappedTypes.push(t); + } + } + } + return mappedTypes ? getUnionType(mappedTypes) : mappedType; + } + function getTypeOfPropertyOfContextualType(type, name) { + return applyToContextualType(type, function (t) { + var prop = t.flags & 130048 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; + return prop ? getTypeOfSymbol(prop) : undefined; + }); + } + function getIndexTypeOfContextualType(type, kind) { + return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); + } + // Return true if the given contextual type is a tuple-like type + function contextualTypeIsTupleLikeType(type) { + return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + } + // Return true if the given contextual type provides an index signature of the given kind + function contextualTypeHasIndexSignature(type, kind) { + return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, function (t) { return getIndexTypeOfStructuredType(t, kind); }) : getIndexTypeOfStructuredType(type, kind)); + } + // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of + // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one + // exists. Otherwise, it is the type of the string index signature in T, if one exists. + function getContextualTypeForObjectLiteralMethod(node) { + ts.Debug.assert(ts.isObjectLiteralMethod(node)); + if (isInsideWithStatementBody(node)) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + return getContextualTypeForObjectLiteralElement(node); + } + function getContextualTypeForObjectLiteralElement(element) { + var objectLiteral = element.parent; + var type = getContextualType(objectLiteral); + if (type) { + if (!ts.hasDynamicName(element)) { + // For a (non-symbol) computed property, there is no reason to look up the name + // in the type. It will just be "__computed", which does not appear in any + // SymbolTable. + var symbolName = getSymbolOfNode(element).name; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName); + if (propertyType) { + return propertyType; + } + } + return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) || + getIndexTypeOfContextualType(type, 0 /* String */); + } + return undefined; + } + // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is + // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature, + // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated + // type of T. + function getContextualTypeForElementExpression(node) { + var arrayLiteral = node.parent; + var type = getContextualType(arrayLiteral); + if (type) { + var index = ts.indexOf(arrayLiteral.elements, node); + return getTypeOfPropertyOfContextualType(type, "" + index) + || getIndexTypeOfContextualType(type, 1 /* Number */) + || (languageVersion >= 2 /* ES6 */ ? getElementTypeOfIterable(type, /*errorNode*/ undefined) : undefined); + } + return undefined; + } + // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. + function getContextualTypeForConditionalOperand(node) { + var conditional = node.parent; + return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; + } + function getContextualTypeForJsxExpression(expr) { + // Contextual type only applies to JSX expressions that are in attribute assignments (not in 'Children' positions) + if (expr.parent.kind === 238 /* JsxAttribute */) { + var attrib = expr.parent; + var attrsType = getJsxElementAttributesType(attrib.parent); + if (!attrsType || isTypeAny(attrsType)) { + return undefined; + } + else { + return getTypeOfPropertyOfType(attrsType, attrib.name.text); + } + } + if (expr.kind === 239 /* JsxSpreadAttribute */) { + return getJsxElementAttributesType(expr.parent); + } + return undefined; + } + // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily + // be "pushed" onto a node using the contextualType property. + function getContextualType(node) { + var type = getContextualTypeWorker(node); + return type && getApparentType(type); + } + function getContextualTypeWorker(node) { + if (isInsideWithStatementBody(node)) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + if (node.contextualType) { + return node.contextualType; + } + var parent = node.parent; + switch (parent.kind) { + case 211 /* VariableDeclaration */: + case 138 /* Parameter */: + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 163 /* BindingElement */: + return getContextualTypeForInitializerExpression(node); + case 174 /* ArrowFunction */: + case 204 /* ReturnStatement */: + return getContextualTypeForReturnExpression(node); + case 184 /* YieldExpression */: + return getContextualTypeForYieldOperand(parent); + case 168 /* CallExpression */: + case 169 /* NewExpression */: + return getContextualTypeForArgument(parent, node); + case 171 /* TypeAssertionExpression */: + case 189 /* AsExpression */: + return getTypeFromTypeNode(parent.type); + case 181 /* BinaryExpression */: + return getContextualTypeForBinaryOperand(node); + case 245 /* PropertyAssignment */: + return getContextualTypeForObjectLiteralElement(parent); + case 164 /* ArrayLiteralExpression */: + return getContextualTypeForElementExpression(node); + case 182 /* ConditionalExpression */: + return getContextualTypeForConditionalOperand(node); + case 190 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 183 /* TemplateExpression */); + return getContextualTypeForSubstitutionExpression(parent.parent, node); + case 172 /* ParenthesizedExpression */: + return getContextualType(parent); + case 240 /* JsxExpression */: + case 239 /* JsxSpreadAttribute */: + return getContextualTypeForJsxExpression(parent); + } + return undefined; + } + // If the given type is an object or union type, if that type has a single signature, and if + // that signature is non-generic, return the signature. Otherwise return undefined. + function getNonGenericSignature(type) { + var signatures = getSignaturesOfStructuredType(type, 0 /* Call */); + if (signatures.length === 1) { + var signature = signatures[0]; + if (!signature.typeParameters) { + return signature; + } + } + } + function isFunctionExpressionOrArrowFunction(node) { + return node.kind === 173 /* FunctionExpression */ || node.kind === 174 /* ArrowFunction */; + } + function getContextualSignatureForFunctionLikeDeclaration(node) { + // Only function expressions, arrow functions, and object literal methods are contextually typed. + return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) + ? getContextualSignature(node) + : undefined; + } + // Return the contextual signature for a given expression node. A contextual type provides a + // contextual signature if it has a single call signature and if that call signature is non-generic. + // If the contextual type is a union type, get the signature from each type possible and if they are + // all identical ignoring their return type, the result is same signature but with return type as + // union type of return types from these signatures + function getContextualSignature(node) { + ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var type = ts.isObjectLiteralMethod(node) + ? getContextualTypeForObjectLiteralMethod(node) + : getContextualType(node); + if (!type) { + return undefined; + } + if (!(type.flags & 16384 /* Union */)) { + return getNonGenericSignature(type); + } + var signatureList; + var types = type.types; + for (var _i = 0; _i < types.length; _i++) { + var current = types[_i]; + var signature = getNonGenericSignature(current); + if (signature) { + if (!signatureList) { + // This signature will contribute to contextual union signature + signatureList = [signature]; + } + else if (!compareSignatures(signatureList[0], signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true, compareTypes)) { + // Signatures aren't identical, do not use + return undefined; + } + else { + // Use this signature for contextual union signature + signatureList.push(signature); + } + } + } + // Result is union of signatures collected (return type is union of return types of this signature set) + var result; + if (signatureList) { + result = cloneSignature(signatureList[0]); + // Clear resolved return type we possibly got from cloneSignature + result.resolvedReturnType = undefined; + result.unionSignatures = signatureList; + } + return result; + } + /** + * Detect if the mapper implies an inference context. Specifically, there are 4 possible values + * for a mapper. Let's go through each one of them: + * + * 1. undefined - this means we are not doing inferential typing, but we may do contextual typing, + * which could cause us to assign a parameter a type + * 2. identityMapper - means we want to avoid assigning a parameter a type, whether or not we are in + * inferential typing (context is undefined for the identityMapper) + * 3. a mapper created by createInferenceMapper - we are doing inferential typing, we want to assign + * types to parameters and fix type parameters (context is defined) + * 4. an instantiation mapper created by createTypeMapper or createTypeEraser - this should never be + * passed as the contextual mapper when checking an expression (context is undefined for these) + * + * isInferentialContext is detecting if we are in case 3 + */ + function isInferentialContext(mapper) { + return mapper && mapper.context; + } + // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property + // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is + // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ p: a}] = xxx'. + function isAssignmentTarget(node) { + var parent = node.parent; + if (parent.kind === 181 /* BinaryExpression */ && parent.operatorToken.kind === 56 /* EqualsToken */ && parent.left === node) { + return true; + } + if (parent.kind === 245 /* PropertyAssignment */) { + return isAssignmentTarget(parent.parent); + } + if (parent.kind === 164 /* ArrayLiteralExpression */) { + return isAssignmentTarget(parent); + } + return false; + } + function checkSpreadElementExpression(node, contextualMapper) { + // It is usually not safe to call checkExpressionCached if we can be contextually typing. + // You can tell that we are contextually typing because of the contextualMapper parameter. + // While it is true that a spread element can have a contextual type, it does not do anything + // with this type. It is neither affected by it, nor does it propagate it to its operand. + // So the fact that contextualMapper is passed is not important, because the operand of a spread + // element is not contextually typed. + var arrayOrIterableType = checkExpressionCached(node.expression, contextualMapper); + return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false); + } + function hasDefaultValue(node) { + return (node.kind === 163 /* BindingElement */ && !!node.initializer) || + (node.kind === 181 /* BinaryExpression */ && node.operatorToken.kind === 56 /* EqualsToken */); + } + function checkArrayLiteral(node, contextualMapper) { + var elements = node.elements; + var hasSpreadElement = false; + var elementTypes = []; + var inDestructuringPattern = isAssignmentTarget(node); + for (var _i = 0; _i < elements.length; _i++) { + var e = elements[_i]; + if (inDestructuringPattern && e.kind === 185 /* SpreadElementExpression */) { + // Given the following situation: + // var c: {}; + // [...c] = ["", 0]; + // + // c is represented in the tree as a spread element in an array literal. + // But c really functions as a rest element, and its purpose is to provide + // a contextual type for the right hand side of the assignment. Therefore, + // instead of calling checkExpression on "...c", which will give an error + // if c is not iterable/array-like, we need to act as if we are trying to + // get the contextual element type from it. So we do something similar to + // getContextualTypeForElementExpression, which will crucially not error + // if there is no index type / iterated type. + var restArrayType = checkExpression(e.expression, contextualMapper); + var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || + (languageVersion >= 2 /* ES6 */ ? getElementTypeOfIterable(restArrayType, /*errorNode*/ undefined) : undefined); + if (restElementType) { + elementTypes.push(restElementType); + } + } + else { + var type = checkExpression(e, contextualMapper); + elementTypes.push(type); + } + hasSpreadElement = hasSpreadElement || e.kind === 185 /* SpreadElementExpression */; + } + if (!hasSpreadElement) { + // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such + // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + if (inDestructuringPattern && elementTypes.length) { + var type = createNewTupleType(elementTypes); + type.pattern = node; + return type; + } + var contextualType = getContextualType(node); + if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { + var pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (pattern && (pattern.kind === 162 /* ArrayBindingPattern */ || pattern.kind === 164 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementTypes.length; i < patternElements.length; i++) { + var patternElement = patternElements[i]; + if (hasDefaultValue(patternElement)) { + elementTypes.push(contextualType.elementTypes[i]); + } + else { + if (patternElement.kind !== 187 /* OmittedExpression */) { + error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(unknownType); + } + } + } + if (elementTypes.length) { + return createTupleType(elementTypes); + } + } + } + return createArrayType(elementTypes.length ? getUnionType(elementTypes) : undefinedType); + } + function isNumericName(name) { + return name.kind === 136 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text); + } + function isNumericComputedName(name) { + // It seems odd to consider an expression of type Any to result in a numeric name, + // but this behavior is consistent with checkIndexedAccess + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 132 /* NumberLike */); + } + function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { + return isTypeAny(type) || allConstituentTypesHaveKind(type, kind); + } + function isNumericLiteralName(name) { + // The intent of numeric names is that + // - they are names with text in a numeric form, and that + // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit', + // acquired by applying the abstract 'ToNumber' operation on the name's text. + // + // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name. + // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold. + // + // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)' + // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'. + // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names + // because their 'ToString' representation is not equal to their original text. + // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1. + // + // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'. + // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation. + // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number. + // + // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional. + // This is desired behavior, because when indexing with them as numeric entities, you are indexing + // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively. + return (+name).toString() === name; + } + function checkComputedPropertyName(node) { + var links = getNodeLinks(node.expression); + if (!links.resolvedType) { + links.resolvedType = checkExpression(node.expression); + // This will allow types number, string, symbol or any. It will also allow enums, the unknown + // type, and any union of these types (like string | number). + if (!isTypeAnyOrAllConstituentTypesHaveKind(links.resolvedType, 132 /* NumberLike */ | 258 /* StringLike */ | 16777216 /* ESSymbol */)) { + error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); + } + else { + checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true); + } + } + return links.resolvedType; + } + function checkObjectLiteral(node, contextualMapper) { + var inDestructuringPattern = isAssignmentTarget(node); + // Grammar checking + checkGrammarObjectLiteralExpression(node, inDestructuringPattern); + var propertiesTable = {}; + var propertiesArray = []; + var contextualType = getContextualType(node); + var contextualTypeHasPattern = contextualType && contextualType.pattern && + (contextualType.pattern.kind === 161 /* ObjectBindingPattern */ || contextualType.pattern.kind === 165 /* ObjectLiteralExpression */); + var typeFlags = 0; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var memberDecl = _a[_i]; + var member = memberDecl.symbol; + if (memberDecl.kind === 245 /* PropertyAssignment */ || + memberDecl.kind === 246 /* ShorthandPropertyAssignment */ || + ts.isObjectLiteralMethod(memberDecl)) { + var type = void 0; + if (memberDecl.kind === 245 /* PropertyAssignment */) { + type = checkPropertyAssignment(memberDecl, contextualMapper); + } + else if (memberDecl.kind === 143 /* MethodDeclaration */) { + type = checkObjectLiteralMethod(memberDecl, contextualMapper); + } + else { + ts.Debug.assert(memberDecl.kind === 246 /* ShorthandPropertyAssignment */); + type = checkExpression(memberDecl.name, contextualMapper); + } + typeFlags |= type.flags; + var prop = createSymbol(4 /* Property */ | 67108864 /* Transient */ | member.flags, member.name); + if (inDestructuringPattern) { + // If object literal is an assignment pattern and if the assignment pattern specifies a default value + // for the property, make the property optional. + var isOptional = (memberDecl.kind === 245 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 246 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + if (isOptional) { + prop.flags |= 536870912 /* Optional */; + } + } + else if (contextualTypeHasPattern) { + // If object literal is contextually typed by the implied type of a binding pattern, and if the + // binding pattern specifies a default value for the property, make the property optional. + var impliedProp = getPropertyOfType(contextualType, member.name); + if (impliedProp) { + prop.flags |= impliedProp.flags & 536870912 /* Optional */; + } + else if (!compilerOptions.suppressExcessPropertyErrors) { + error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); + } + } + prop.declarations = member.declarations; + prop.parent = member.parent; + if (member.valueDeclaration) { + prop.valueDeclaration = member.valueDeclaration; + } + prop.type = type; + prop.target = member; + member = prop; + } + else { + // TypeScript 1.0 spec (April 2014) + // A get accessor declaration is processed in the same manner as + // an ordinary function declaration(section 6.1) with no parameters. + // A set accessor declaration is processed in the same manner + // as an ordinary function declaration with a single parameter and a Void return type. + ts.Debug.assert(memberDecl.kind === 145 /* GetAccessor */ || memberDecl.kind === 146 /* SetAccessor */); + checkAccessorDeclaration(memberDecl); + } + if (!ts.hasDynamicName(memberDecl)) { + propertiesTable[member.name] = member; + } + propertiesArray.push(member); + } + // If object literal is contextually typed by the implied type of a binding pattern, augment the result + // type with those properties for which the binding pattern specifies a default value. + if (contextualTypeHasPattern) { + for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!ts.hasProperty(propertiesTable, prop.name)) { + if (!(prop.flags & 536870912 /* Optional */)) { + error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + propertiesTable[prop.name] = prop; + propertiesArray.push(prop); + } + } + } + var stringIndexType = getIndexType(0 /* String */); + var numberIndexType = getIndexType(1 /* Number */); + var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshObjectLiteral */; + result.flags |= 524288 /* ObjectLiteral */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */); + if (inDestructuringPattern) { + result.pattern = node; + } + return result; + function getIndexType(kind) { + if (contextualType && contextualTypeHasIndexSignature(contextualType, kind)) { + var propTypes = []; + for (var i = 0; i < propertiesArray.length; i++) { + var propertyDecl = node.properties[i]; + if (kind === 0 /* String */ || isNumericName(propertyDecl.name)) { + // Do not call getSymbolOfNode(propertyDecl), as that will get the + // original symbol for the node. We actually want to get the symbol + // created by checkObjectLiteral, since that will be appropriately + // contextually typed and resolved. + var type = getTypeOfSymbol(propertiesArray[i]); + if (!ts.contains(propTypes, type)) { + propTypes.push(type); + } + } + } + var result_1 = propTypes.length ? getUnionType(propTypes) : undefinedType; + typeFlags |= result_1.flags; + return result_1; + } + return undefined; + } + } + function checkJsxSelfClosingElement(node) { + checkJsxOpeningLikeElement(node); + return jsxElementType || anyType; + } + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 69 /* Identifier */) { + return lhs.text === rhs.text; + } + return lhs.right.text === rhs.right.text && + tagNamesAreEquivalent(lhs.left, rhs.left); + } + function checkJsxElement(node) { + // Check attributes + checkJsxOpeningLikeElement(node.openingElement); + // Check that the closing tag matches + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + error(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNode(node.openingElement.tagName)); + } + else { + // Perform resolution on the closing tag so that rename/go to definition/etc work + getJsxElementTagSymbol(node.closingElement); + } + // Check children + for (var _i = 0, _a = node.children; _i < _a.length; _i++) { + var child = _a[_i]; + switch (child.kind) { + case 240 /* JsxExpression */: + checkJsxExpression(child); + break; + case 233 /* JsxElement */: + checkJsxElement(child); + break; + case 234 /* JsxSelfClosingElement */: + checkJsxSelfClosingElement(child); + break; + default: + // No checks for JSX Text + ts.Debug.assert(child.kind === 236 /* JsxText */); + } + } + return jsxElementType || anyType; + } + /** + * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers + */ + function isUnhyphenatedJsxName(name) { + // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers + return name.indexOf("-") < 0; + } + /** + * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name + */ + function isJsxIntrinsicIdentifier(tagName) { + if (tagName.kind === 135 /* QualifiedName */) { + return false; + } + else { + return ts.isIntrinsicJsxName(tagName.text); + } + } + function checkJsxAttribute(node, elementAttributesType, nameTable) { + var correspondingPropType = undefined; + // Look up the corresponding property for this attribute + if (elementAttributesType === emptyObjectType && isUnhyphenatedJsxName(node.name.text)) { + // If there is no 'props' property, you may not have non-"data-" attributes + error(node.parent, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); + } + else if (elementAttributesType && !isTypeAny(elementAttributesType)) { + var correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); + correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol); + if (isUnhyphenatedJsxName(node.name.text)) { + // Maybe there's a string indexer? + var indexerType = getIndexTypeOfType(elementAttributesType, 0 /* String */); + if (indexerType) { + correspondingPropType = indexerType; + } + else { + // If there's no corresponding property with this name, error + if (!correspondingPropType) { + error(node.name, ts.Diagnostics.Property_0_does_not_exist_on_type_1, node.name.text, typeToString(elementAttributesType)); + return unknownType; + } + } + } + } + var exprType; + if (node.initializer) { + exprType = checkExpression(node.initializer); + } + else { + // is sugar for + exprType = booleanType; + } + if (correspondingPropType) { + checkTypeAssignableTo(exprType, correspondingPropType, node); + } + nameTable[node.name.text] = true; + return exprType; + } + function checkJsxSpreadAttribute(node, elementAttributesType, nameTable) { + var type = checkExpression(node.expression); + var props = getPropertiesOfType(type); + for (var _i = 0; _i < props.length; _i++) { + var prop = props[_i]; + // Is there a corresponding property in the element attributes type? Skip checking of properties + // that have already been assigned to, as these are not actually pushed into the resulting type + if (!nameTable[prop.name]) { + var targetPropSym = getPropertyOfType(elementAttributesType, prop.name); + if (targetPropSym) { + var msg = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property, prop.name); + checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(targetPropSym), node, undefined, msg); + } + nameTable[prop.name] = true; + } + } + return type; + } + /// Returns the type JSX.IntrinsicElements. May return `unknownType` if that type is not present. + function getJsxIntrinsicElementsType() { + if (!jsxIntrinsicElementsType) { + jsxIntrinsicElementsType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.IntrinsicElements) || unknownType; + } + return jsxIntrinsicElementsType; + } + /// Given a JSX opening element or self-closing element, return the symbol of the property that the tag name points to if + /// this is an intrinsic tag. This might be a named + /// property of the IntrinsicElements interface, or its string indexer. + /// If this is a class-based tag (otherwise returns undefined), returns the symbol of the class + /// type or factory function. + /// Otherwise, returns unknownSymbol. + function getJsxElementTagSymbol(node) { + var flags = 8 /* UnknownElement */; + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + links.resolvedSymbol = lookupIntrinsicTag(node); + } + else { + links.resolvedSymbol = lookupClassTag(node); + } + } + return links.resolvedSymbol; + function lookupIntrinsicTag(node) { + var intrinsicElementsType = getJsxIntrinsicElementsType(); + if (intrinsicElementsType !== unknownType) { + // Property case + var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.text); + if (intrinsicProp) { + links.jsxFlags |= 1 /* IntrinsicNamedElement */; + return intrinsicProp; + } + // Intrinsic string indexer case + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + links.jsxFlags |= 2 /* IntrinsicIndexedElement */; + return intrinsicElementsType.symbol; + } + // Wasn't found + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, node.tagName.text, "JSX." + JsxNames.IntrinsicElements); + return unknownSymbol; + } + else { + if (compilerOptions.noImplicitAny) { + error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, JsxNames.IntrinsicElements); + } + } + } + function lookupClassTag(node) { + var valueSymbol = resolveJsxTagName(node); + // Look up the value in the current scope + if (valueSymbol && valueSymbol !== unknownSymbol) { + links.jsxFlags |= 4 /* ClassElement */; + if (valueSymbol.flags & 8388608 /* Alias */) { + markAliasSymbolAsReferenced(valueSymbol); + } + } + return valueSymbol || unknownSymbol; + } + function resolveJsxTagName(node) { + if (node.tagName.kind === 69 /* Identifier */) { + var tag = node.tagName; + var sym = getResolvedSymbol(tag); + return sym.exportSymbol || sym; + } + else { + return checkQualifiedName(node.tagName).symbol; + } + } + } + /** + * Given a JSX element that is a class element, finds the Element Instance Type. If the + * element is not a class element, or the class element type cannot be determined, returns 'undefined'. + * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). + */ + function getJsxElementInstanceType(node) { + // There is no such thing as an instance type for a non-class element. This + // line shouldn't be hit. + ts.Debug.assert(!!(getNodeLinks(node).jsxFlags & 4 /* ClassElement */), "Should not call getJsxElementInstanceType on non-class Element"); + var classSymbol = getJsxElementTagSymbol(node); + if (classSymbol === unknownSymbol) { + // Couldn't find the class instance type. Error has already been issued + return anyType; + } + var valueType = getTypeOfSymbol(classSymbol); + if (isTypeAny(valueType)) { + // Short-circuit if the class tag is using an element type 'any' + return anyType; + } + // Resolve the signatures, preferring constructors + var signatures = getSignaturesOfType(valueType, 1 /* Construct */); + if (signatures.length === 0) { + // No construct signatures, try call signatures + signatures = getSignaturesOfType(valueType, 0 /* Call */); + if (signatures.length === 0) { + // We found no signatures at all, which is an error + error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); + return unknownType; + } + } + var returnType = getUnionType(signatures.map(getReturnTypeOfSignature)); + // Issue an error if this return type isn't assignable to JSX.ElementClass + var elemClassType = getJsxGlobalElementClassType(); + if (elemClassType) { + checkTypeRelatedTo(returnType, elemClassType, assignableRelation, node, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + return returnType; + } + /// e.g. "props" for React.d.ts, + /// or 'undefined' if ElementAttributesPropery doesn't exist (which means all + /// non-intrinsic elements' attributes type is 'any'), + /// or '' if it has 0 properties (which means every + /// non-instrinsic elements' attributes type is the element instance type) + function getJsxElementPropertiesName() { + // JSX + var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1536 /* Namespace */, /*diagnosticMessage*/ undefined); + // JSX.ElementAttributesProperty [symbol] + var attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, 793056 /* Type */); + // JSX.ElementAttributesProperty [type] + var attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); + // The properites of JSX.ElementAttributesProperty + var attribProperties = attribPropType && getPropertiesOfType(attribPropType); + if (attribProperties) { + // Element Attributes has zero properties, so the element attributes type will be the class instance type + if (attribProperties.length === 0) { + return ""; + } + else if (attribProperties.length === 1) { + return attribProperties[0].name; + } + else { + error(attribsPropTypeSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, JsxNames.ElementAttributesPropertyNameContainer); + return undefined; + } + } + else { + // No interface exists, so the element attributes type will be an implicit any + return undefined; + } + } + /** + * Given an opening/self-closing element, get the 'element attributes type', i.e. the type that tells + * us which attributes are valid on a given element. + */ + function getJsxElementAttributesType(node) { + var links = getNodeLinks(node); + if (!links.resolvedJsxType) { + var sym = getJsxElementTagSymbol(node); + if (links.jsxFlags & 4 /* ClassElement */) { + var elemInstanceType = getJsxElementInstanceType(node); + if (isTypeAny(elemInstanceType)) { + return links.resolvedJsxType = elemInstanceType; + } + var propsName = getJsxElementPropertiesName(); + if (propsName === undefined) { + // There is no type ElementAttributesProperty, return 'any' + return links.resolvedJsxType = anyType; + } + else if (propsName === "") { + // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead + return links.resolvedJsxType = elemInstanceType; + } + else { + var attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); + if (!attributesType) { + // There is no property named 'props' on this instance type + return links.resolvedJsxType = emptyObjectType; + } + else if (isTypeAny(attributesType) || (attributesType === unknownType)) { + return links.resolvedJsxType = attributesType; + } + else if (!(attributesType.flags & 80896 /* ObjectType */)) { + error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_must_be_an_object_type, typeToString(attributesType)); + return links.resolvedJsxType = anyType; + } + else { + return links.resolvedJsxType = attributesType; + } + } + } + else if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { + return links.resolvedJsxType = getTypeOfSymbol(sym); + } + else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { + return links.resolvedJsxType = getIndexTypeOfSymbol(sym, 0 /* String */); + } + else { + // Resolution failed, so we don't know + return links.resolvedJsxType = anyType; + } + } + return links.resolvedJsxType; + } + /** + * Given a JSX attribute, returns the symbol for the corresponds property + * of the element attributes type. Will return unknownSymbol for attributes + * that have no matching element attributes type property. + */ + function getJsxAttributePropertySymbol(attrib) { + var attributesType = getJsxElementAttributesType(attrib.parent); + var prop = getPropertyOfType(attributesType, attrib.name.text); + return prop || unknownSymbol; + } + var jsxElementClassType = undefined; + function getJsxGlobalElementClassType() { + if (!jsxElementClassType) { + jsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); + } + return jsxElementClassType; + } + /// Returns all the properties of the Jsx.IntrinsicElements interface + function getJsxIntrinsicTagNames() { + var intrinsics = getJsxIntrinsicElementsType(); + return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; + } + function checkJsxPreconditions(errorNode) { + // Preconditions for using JSX + if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) { + error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); + } + if (jsxElementType === undefined) { + if (compilerOptions.noImplicitAny) { + error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); + } + } + } + function checkJsxOpeningLikeElement(node) { + checkGrammarJsxElement(node); + checkJsxPreconditions(node); + // If we're compiling under --jsx react, the symbol 'React' should + // be marked as 'used' so we don't incorrectly elide its import. And if there + // is no 'React' symbol in scope, we should issue an error. + if (compilerOptions.jsx === 2 /* React */) { + var reactSym = resolveName(node.tagName, "React", 107455 /* Value */, ts.Diagnostics.Cannot_find_name_0, "React"); + if (reactSym) { + getSymbolLinks(reactSym).referenced = true; + } + } + var targetAttributesType = getJsxElementAttributesType(node); + var nameTable = {}; + // Process this array in right-to-left order so we know which + // attributes (mostly from spreads) are being overwritten and + // thus should have their types ignored + var sawSpreadedAny = false; + for (var i = node.attributes.length - 1; i >= 0; i--) { + if (node.attributes[i].kind === 238 /* JsxAttribute */) { + checkJsxAttribute((node.attributes[i]), targetAttributesType, nameTable); + } + else { + ts.Debug.assert(node.attributes[i].kind === 239 /* JsxSpreadAttribute */); + var spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable); + if (isTypeAny(spreadType)) { + sawSpreadedAny = true; + } + } + } + // Check that all required properties have been provided. If an 'any' + // was spreaded in, though, assume that it provided all required properties + if (targetAttributesType && !sawSpreadedAny) { + var targetProperties = getPropertiesOfType(targetAttributesType); + for (var i = 0; i < targetProperties.length; i++) { + if (!(targetProperties[i].flags & 536870912 /* Optional */) && + nameTable[targetProperties[i].name] === undefined) { + error(node, ts.Diagnostics.Property_0_is_missing_in_type_1, targetProperties[i].name, typeToString(targetAttributesType)); + } + } + } + } + function checkJsxExpression(node) { + if (node.expression) { + return checkExpression(node.expression); + } + else { + return unknownType; + } + } + // If a symbol is a synthesized symbol with no value declaration, we assume it is a property. Example of this are the synthesized + // '.prototype' property as well as synthesized tuple index properties. + function getDeclarationKindFromSymbol(s) { + return s.valueDeclaration ? s.valueDeclaration.kind : 141 /* PropertyDeclaration */; + } + function getDeclarationFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 16 /* Public */ | 128 /* Static */ : 0; + } + /** + * Check whether the requested property access is valid. + * Returns true if node is a valid property access, and false otherwise. + * @param node The node to be checked. + * @param left The left hand side of the property access (e.g.: the super in `super.foo`). + * @param type The type of left. + * @param prop The symbol for the right hand side of the property access. + */ + function checkClassPropertyAccess(node, left, type, prop) { + var flags = getDeclarationFlagsFromSymbol(prop); + var declaringClass = getDeclaredTypeOfSymbol(prop.parent); + if (left.kind === 95 /* SuperKeyword */) { + var errorNode = node.kind === 166 /* PropertyAccessExpression */ ? + node.name : + node.right; + // TS 1.0 spec (April 2014): 4.8.2 + // - In a constructor, instance member function, instance member accessor, or + // instance member variable initializer where this references a derived class instance, + // a super property access is permitted and must specify a public instance member function of the base class. + // - In a static member function or static member accessor + // where this references the constructor function object of a derived class, + // a super property access is permitted and must specify a public static member function of the base class. + if (getDeclarationKindFromSymbol(prop) !== 143 /* MethodDeclaration */) { + // `prop` refers to a *property* declared in the super class + // rather than a *method*, so it does not satisfy the above criteria. + error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + return false; + } + if (flags & 256 /* Abstract */) { + // A method cannot be accessed in a super property access if the method is abstract. + // This error could mask a private property access error. But, a member + // cannot simultaneously be private and abstract, so this will trigger an + // additional error elsewhere. + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(declaringClass)); + return false; + } + } + // Public properties are otherwise accessible. + if (!(flags & (32 /* Private */ | 64 /* Protected */))) { + return true; + } + // Property is known to be private or protected at this point + // Get the declaring and enclosing class instance types + var enclosingClassDeclaration = ts.getContainingClass(node); + var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; + // Private property is accessible if declaring and enclosing class are the same + if (flags & 32 /* Private */) { + if (declaringClass !== enclosingClass) { + error(node, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass)); + return false; + } + return true; + } + // Property is known to be protected at this point + // All protected properties of a supertype are accessible in a super access + if (left.kind === 95 /* SuperKeyword */) { + return true; + } + // A protected property is accessible in the declaring class and classes derived from it + if (!enclosingClass || !hasBaseType(enclosingClass, declaringClass)) { + error(node, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(declaringClass)); + return false; + } + // No further restrictions for static properties + if (flags & 128 /* Static */) { + return true; + } + // An instance property must be accessed through an instance of the enclosing class + if (type.flags & 33554432 /* ThisType */) { + // get the original type -- represented as the type constraint of the 'this' type + type = getConstraintOfTypeParameter(type); + } + // TODO: why is the first part of this check here? + if (!(getTargetType(type).flags & (1024 /* Class */ | 2048 /* Interface */) && hasBaseType(type, enclosingClass))) { + error(node, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + return false; + } + return true; + } + function checkPropertyAccessExpression(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + } + function checkQualifiedName(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + } + function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { + var type = checkExpression(left); + if (isTypeAny(type)) { + return type; + } + var apparentType = getApparentType(getWidenedType(type)); + if (apparentType === unknownType) { + // handle cases when type is Type parameter with invalid constraint + return unknownType; + } + var prop = getPropertyOfType(apparentType, right.text); + if (!prop) { + if (right.text) { + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 /* ThisType */ ? apparentType : type)); + } + return unknownType; + } + getNodeLinks(node).resolvedSymbol = prop; + if (prop.parent && prop.parent.flags & 32 /* Class */) { + checkClassPropertyAccess(node, left, apparentType, prop); + } + return getTypeOfSymbol(prop); + } + function isValidPropertyAccess(node, propertyName) { + var left = node.kind === 166 /* PropertyAccessExpression */ + ? node.expression + : node.left; + var type = checkExpression(left); + if (type !== unknownType && !isTypeAny(type)) { + var prop = getPropertyOfType(getWidenedType(type), propertyName); + if (prop && prop.parent && prop.parent.flags & 32 /* Class */) { + return checkClassPropertyAccess(node, left, type, prop); + } + } + return true; + } + function checkIndexedAccess(node) { + // Grammar checking + if (!node.argumentExpression) { + var sourceFile = getSourceFile(node); + if (node.parent.kind === 169 /* NewExpression */ && node.parent.expression === node) { + var start = ts.skipTrivia(sourceFile.text, node.expression.end); + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); + } + else { + var start = node.end - "]".length; + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); + } + } + // Obtain base constraint such that we can bail out if the constraint is an unknown type + var objectType = getApparentType(checkExpression(node.expression)); + var indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; + if (objectType === unknownType) { + return unknownType; + } + var isConstEnum = isConstEnumObjectType(objectType); + if (isConstEnum && + (!node.argumentExpression || node.argumentExpression.kind !== 9 /* StringLiteral */)) { + error(node.argumentExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + return unknownType; + } + // TypeScript 1.0 spec (April 2014): 4.10 Property Access + // - If IndexExpr is a string literal or a numeric literal and ObjExpr's apparent type has a property with the name + // given by that literal(converted to its string representation in the case of a numeric literal), the property access is of the type of that property. + // - Otherwise, if ObjExpr's apparent type has a numeric index signature and IndexExpr is of type Any, the Number primitive type, or an enum type, + // the property access is of the type of that index signature. + // - Otherwise, if ObjExpr's apparent type has a string index signature and IndexExpr is of type Any, the String or Number primitive type, or an enum type, + // the property access is of the type of that index signature. + // - Otherwise, if IndexExpr is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any. + // See if we can index as a property. + if (node.argumentExpression) { + var name_11 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_11 !== undefined) { + var prop = getPropertyOfType(objectType, name_11); + if (prop) { + getNodeLinks(node).resolvedSymbol = prop; + return getTypeOfSymbol(prop); + } + else if (isConstEnum) { + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_11, symbolToString(objectType.symbol)); + return unknownType; + } + } + } + // Check for compatible indexer types. + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 258 /* StringLike */ | 132 /* NumberLike */ | 16777216 /* ESSymbol */)) { + // Try to use a number indexer. + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132 /* NumberLike */)) { + var numberIndexType = getIndexTypeOfType(objectType, 1 /* Number */); + if (numberIndexType) { + return numberIndexType; + } + } + // Try to use string indexing. + var stringIndexType = getIndexTypeOfType(objectType, 0 /* String */); + if (stringIndexType) { + return stringIndexType; + } + // Fall back to any. + if (compilerOptions.noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !isTypeAny(objectType)) { + error(node, ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); + } + return anyType; + } + // REVIEW: Users should know the type that was actually used. + error(node, ts.Diagnostics.An_index_expression_argument_must_be_of_type_string_number_symbol_or_any); + return unknownType; + } + /** + * If indexArgumentExpression is a string literal or number literal, returns its text. + * If indexArgumentExpression is a constant value, returns its string value. + * If indexArgumentExpression is a well known symbol, returns the property name corresponding + * to this symbol, as long as it is a proper symbol reference. + * Otherwise, returns undefined. + */ + function getPropertyNameForIndexedAccess(indexArgumentExpression, indexArgumentType) { + if (indexArgumentExpression.kind === 9 /* StringLiteral */ || indexArgumentExpression.kind === 8 /* NumericLiteral */) { + return indexArgumentExpression.text; + } + if (indexArgumentExpression.kind === 167 /* ElementAccessExpression */ || indexArgumentExpression.kind === 166 /* PropertyAccessExpression */) { + var value = getConstantValue(indexArgumentExpression); + if (value !== undefined) { + return value.toString(); + } + } + if (checkThatExpressionIsProperSymbolReference(indexArgumentExpression, indexArgumentType, /*reportError*/ false)) { + var rightHandSideName = indexArgumentExpression.name.text; + return ts.getPropertyNameForKnownSymbolName(rightHandSideName); + } + return undefined; + } + /** + * A proper symbol reference requires the following: + * 1. The property access denotes a property that exists + * 2. The expression is of the form Symbol. + * 3. The property access is of the primitive type symbol. + * 4. Symbol in this context resolves to the global Symbol object + */ + function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { + if (expressionType === unknownType) { + // There is already an error, so no need to report one. + return false; + } + if (!ts.isWellKnownSymbolSyntactically(expression)) { + return false; + } + // Make sure the property type is the primitive symbol type + if ((expressionType.flags & 16777216 /* ESSymbol */) === 0) { + if (reportError) { + error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); + } + return false; + } + // The name is Symbol., so make sure Symbol actually resolves to the + // global Symbol object + var leftHandSide = expression.expression; + var leftHandSideSymbol = getResolvedSymbol(leftHandSide); + if (!leftHandSideSymbol) { + return false; + } + var globalESSymbol = getGlobalESSymbolConstructorSymbol(); + if (!globalESSymbol) { + // Already errored when we tried to look up the symbol + return false; + } + if (leftHandSideSymbol !== globalESSymbol) { + if (reportError) { + error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); + } + return false; + } + return true; + } + function resolveUntypedCall(node) { + if (node.kind === 170 /* TaggedTemplateExpression */) { + checkExpression(node.template); + } + else if (node.kind !== 139 /* Decorator */) { + ts.forEach(node.arguments, function (argument) { + checkExpression(argument); + }); + } + return anySignature; + } + function resolveErrorCall(node) { + resolveUntypedCall(node); + return unknownSignature; + } + // Re-order candidate signatures into the result array. Assumes the result array to be empty. + // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order + // A nit here is that we reorder only signatures that belong to the same symbol, + // so order how inherited signatures are processed is still preserved. + // interface A { (x: string): void } + // interface B extends A { (x: 'foo'): string } + // let b: B; + // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] + function reorderCandidates(signatures, result) { + var lastParent; + var lastSymbol; + var cutoffIndex = 0; + var index; + var specializedIndex = -1; + var spliceIndex; + ts.Debug.assert(!result.length); + for (var _i = 0; _i < signatures.length; _i++) { + var signature = signatures[_i]; + var symbol = signature.declaration && getSymbolOfNode(signature.declaration); + var parent_5 = signature.declaration && signature.declaration.parent; + if (!lastSymbol || symbol === lastSymbol) { + if (lastParent && parent_5 === lastParent) { + index++; + } + else { + lastParent = parent_5; + index = cutoffIndex; + } + } + else { + // current declaration belongs to a different symbol + // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex + index = cutoffIndex = result.length; + lastParent = parent_5; + } + lastSymbol = symbol; + // specialized signatures always need to be placed before non-specialized signatures regardless + // of the cutoff position; see GH#1133 + if (signature.hasStringLiterals) { + specializedIndex++; + spliceIndex = specializedIndex; + // The cutoff index always needs to be greater than or equal to the specialized signature index + // in order to prevent non-specialized signatures from being added before a specialized + // signature. + cutoffIndex++; + } + else { + spliceIndex = index; + } + result.splice(spliceIndex, 0, signature); + } + } + function getSpreadArgumentIndex(args) { + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + if (arg && arg.kind === 185 /* SpreadElementExpression */) { + return i; + } + } + return -1; + } + function hasCorrectArity(node, args, signature) { + var adjustedArgCount; // Apparent number of arguments we will have in this call + var typeArguments; // Type arguments (undefined if none) + var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments + var isDecorator; + var spreadArgIndex = -1; + if (node.kind === 170 /* TaggedTemplateExpression */) { + var tagExpression = node; + // Even if the call is incomplete, we'll have a missing expression as our last argument, + // so we can say the count is just the arg list length + adjustedArgCount = args.length; + typeArguments = undefined; + if (tagExpression.template.kind === 183 /* TemplateExpression */) { + // If a tagged template expression lacks a tail literal, the call is incomplete. + // Specifically, a template only can end in a TemplateTail or a Missing literal. + var templateExpression = tagExpression.template; + var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); + ts.Debug.assert(lastSpan !== undefined); // we should always have at least one span. + callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; + } + else { + // If the template didn't end in a backtick, or its beginning occurred right prior to EOF, + // then this might actually turn out to be a TemplateHead in the future; + // so we consider the call to be incomplete. + var templateLiteral = tagExpression.template; + ts.Debug.assert(templateLiteral.kind === 11 /* NoSubstitutionTemplateLiteral */); + callIsIncomplete = !!templateLiteral.isUnterminated; + } + } + else if (node.kind === 139 /* Decorator */) { + isDecorator = true; + typeArguments = undefined; + adjustedArgCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + } + else { + var callExpression = node; + if (!callExpression.arguments) { + // This only happens when we have something of the form: 'new C' + ts.Debug.assert(callExpression.kind === 169 /* NewExpression */); + return signature.minArgumentCount === 0; + } + // For IDE scenarios we may have an incomplete call, so a trailing comma is tantamount to adding another argument. + adjustedArgCount = callExpression.arguments.hasTrailingComma ? args.length + 1 : args.length; + // If we are missing the close paren, the call is incomplete. + callIsIncomplete = callExpression.arguments.end === callExpression.end; + typeArguments = callExpression.typeArguments; + spreadArgIndex = getSpreadArgumentIndex(args); + } + // If the user supplied type arguments, but the number of type arguments does not match + // the declared number of type parameters, the call has an incorrect arity. + var hasRightNumberOfTypeArgs = !typeArguments || + (signature.typeParameters && typeArguments.length === signature.typeParameters.length); + if (!hasRightNumberOfTypeArgs) { + return false; + } + // If spread arguments are present, check that they correspond to a rest parameter. If so, no + // further checking is necessary. + if (spreadArgIndex >= 0) { + return isRestParameterIndex(signature, spreadArgIndex); + } + // Too many arguments implies incorrect arity. + if (!signature.hasRestParameter && adjustedArgCount > signature.parameters.length) { + return false; + } + // If the call is incomplete, we should skip the lower bound check. + var hasEnoughArguments = adjustedArgCount >= signature.minArgumentCount; + return callIsIncomplete || hasEnoughArguments; + } + // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. + function getSingleCallSignature(type) { + if (type.flags & 80896 /* ObjectType */) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && + resolved.properties.length === 0 && !resolved.stringIndexType && !resolved.numberIndexType) { + return resolved.callSignatures[0]; + } + } + return undefined; + } + // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) + function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { + var context = createInferenceContext(signature.typeParameters, /*inferUnionTypes*/ true); + forEachMatchingParameterType(contextualSignature, signature, function (source, target) { + // Type parameters from outer context referenced by source type are fixed by instantiation of the source type + inferTypes(context, instantiateType(source, contextualMapper), target); + }); + return getSignatureInstantiation(signature, getInferredTypes(context)); + } + function inferTypeArguments(node, signature, args, excludeArgument, context) { + var typeParameters = signature.typeParameters; + var inferenceMapper = createInferenceMapper(context); + // Clear out all the inference results from the last time inferTypeArguments was called on this context + for (var i = 0; i < typeParameters.length; i++) { + // As an optimization, we don't have to clear (and later recompute) inferred types + // for type parameters that have already been fixed on the previous call to inferTypeArguments. + // It would be just as correct to reset all of them. But then we'd be repeating the same work + // for the type parameters that were fixed, namely the work done by getInferredType. + if (!context.inferences[i].isFixed) { + context.inferredTypes[i] = undefined; + } + } + // On this call to inferTypeArguments, we may get more inferences for certain type parameters that were not + // fixed last time. This means that a type parameter that failed inference last time may succeed this time, + // or vice versa. Therefore, the failedTypeParameterIndex is useless if it points to an unfixed type parameter, + // because it may change. So here we reset it. However, getInferredType will not revisit any type parameters + // that were previously fixed. So if a fixed type parameter failed previously, it will fail again because + // it will contain the exact same set of inferences. So if we reset the index from a fixed type parameter, + // we will lose information that we won't recover this time around. + if (context.failedTypeParameterIndex !== undefined && !context.inferences[context.failedTypeParameterIndex].isFixed) { + context.failedTypeParameterIndex = undefined; + } + // We perform two passes over the arguments. In the first pass we infer from all arguments, but use + // wildcards for all context sensitive function expressions. + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. + if (arg === undefined || arg.kind !== 187 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = getEffectiveArgumentType(node, i, arg); + // If the effective argument type is 'undefined', there is no synthetic type + // for the argument. In that case, we should check the argument. + if (argType === undefined) { + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; + argType = checkExpressionWithContextualType(arg, paramType, mapper); + } + inferTypes(context, argType, paramType); + } + } + // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this + // time treating function expressions normally (which may cause previously inferred type arguments to be fixed + // as we construct types for contextually typed parameters) + // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. + // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. + if (excludeArgument) { + for (var i = 0; i < argCount; i++) { + // No need to check for omitted args and template expressions, their exlusion value is always undefined + if (excludeArgument[i] === false) { + var arg = args[i]; + var paramType = getTypeAtPosition(signature, i); + inferTypes(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); + } + } + } + getInferredTypes(context); + } + function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors, headMessage) { + var typeParameters = signature.typeParameters; + var typeArgumentsAreAssignable = true; + for (var i = 0; i < typeParameters.length; i++) { + var typeArgNode = typeArguments[i]; + var typeArgument = getTypeFromTypeNode(typeArgNode); + // Do not push on this array! It has a preallocated length + typeArgumentResultTypes[i] = typeArgument; + if (typeArgumentsAreAssignable /* so far */) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + var errorInfo = void 0; + var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (reportErrors && headMessage) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); + typeArgumentHeadMessage = headMessage; + } + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, typeArgumentHeadMessage, errorInfo); + } + } + } + return typeArgumentsAreAssignable; + } + function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. + if (arg === undefined || arg.kind !== 187 /* OmittedExpression */) { + // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) + var paramType = getTypeAtPosition(signature, i); + var argType = getEffectiveArgumentType(node, i, arg); + // If the effective argument type is 'undefined', there is no synthetic type + // for the argument. In that case, we should check the argument. + if (argType === undefined) { + argType = arg.kind === 9 /* StringLiteral */ && !reportErrors + ? getStringLiteralType(arg) + : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + } + // Use argument expression as error location when reporting errors + var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { + return false; + } + } + } + return true; + } + /** + * Returns the effective arguments for an expression that works like a function invocation. + * + * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. + * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution + * expressions, where the first element of the list is `undefined`. + * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types + * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. + */ + function getEffectiveCallArguments(node) { + var args; + if (node.kind === 170 /* TaggedTemplateExpression */) { + var template = node.template; + args = [undefined]; + if (template.kind === 183 /* TemplateExpression */) { + ts.forEach(template.templateSpans, function (span) { + args.push(span.expression); + }); + } + } + else if (node.kind === 139 /* Decorator */) { + // For a decorator, we return undefined as we will determine + // the number and types of arguments for a decorator using + // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. + return undefined; + } + else { + args = node.arguments || emptyArray; + } + return args; + } + /** + * Returns the effective argument count for a node that works like a function invocation. + * If 'node' is a Decorator, the number of arguments is derived from the decoration + * target and the signature: + * If 'node.target' is a class declaration or class expression, the effective argument + * count is 1. + * If 'node.target' is a parameter declaration, the effective argument count is 3. + * If 'node.target' is a property declaration, the effective argument count is 2. + * If 'node.target' is a method or accessor declaration, the effective argument count + * is 3, although it can be 2 if the signature only accepts two arguments, allowing + * us to match a property decorator. + * Otherwise, the argument count is the length of the 'args' array. + */ + function getEffectiveArgumentCount(node, args, signature) { + if (node.kind === 139 /* Decorator */) { + switch (node.parent.kind) { + case 214 /* ClassDeclaration */: + case 186 /* ClassExpression */: + // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) + return 1; + case 141 /* PropertyDeclaration */: + // A property declaration decorator will have two arguments (see + // `PropertyDecorator` in core.d.ts) + return 2; + case 143 /* MethodDeclaration */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts) + // If we are emitting decorators for ES3, we will only pass two arguments. + if (languageVersion === 0 /* ES3 */) { + return 2; + } + // If the method decorator signature only accepts a target and a key, we will only + // type check those arguments. + return signature.parameters.length >= 3 ? 3 : 2; + case 138 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts) + return 3; + } + } + else { + return args.length; + } + } + /** + * Returns the effective type of the first argument to a decorator. + * If 'node' is a class declaration or class expression, the effective argument type + * is the type of the static side of the class. + * If 'node' is a parameter declaration, the effective argument type is either the type + * of the static or instance side of the class for the parameter's parent method, + * depending on whether the method is declared static. + * For a constructor, the type is always the type of the static side of the class. + * If 'node' is a property, method, or accessor declaration, the effective argument + * type is the type of the static or instance side of the parent class for class + * element, depending on whether the element is declared static. + */ + function getEffectiveDecoratorFirstArgumentType(node) { + // The first argument to a decorator is its `target`. + if (node.kind === 214 /* ClassDeclaration */) { + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class) + var classSymbol = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol); + } + if (node.kind === 138 /* Parameter */) { + // For a parameter decorator, the `target` is the parent type of the + // parameter's containing method. + node = node.parent; + if (node.kind === 144 /* Constructor */) { + var classSymbol = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol); + } + } + if (node.kind === 141 /* PropertyDeclaration */ || + node.kind === 143 /* MethodDeclaration */ || + node.kind === 145 /* GetAccessor */ || + node.kind === 146 /* SetAccessor */) { + // For a property or method decorator, the `target` is the + // "static"-side type of the parent of the member if the member is + // declared "static"; otherwise, it is the "instance"-side type of the + // parent of the member. + return getParentTypeOfClassElement(node); + } + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + /** + * Returns the effective type for the second argument to a decorator. + * If 'node' is a parameter, its effective argument type is one of the following: + * If 'node.parent' is a constructor, the effective argument type is 'any', as we + * will emit `undefined`. + * If 'node.parent' is a member with an identifier, numeric, or string literal name, + * the effective argument type will be a string literal type for the member name. + * If 'node.parent' is a computed property name, the effective argument type will + * either be a symbol type or the string type. + * If 'node' is a member with an identifier, numeric, or string literal name, the + * effective argument type will be a string literal type for the member name. + * If 'node' is a computed property name, the effective argument type will either + * be a symbol type or the string type. + * A class decorator does not have a second argument type. + */ + function getEffectiveDecoratorSecondArgumentType(node) { + // The second argument to a decorator is its `propertyKey` + if (node.kind === 214 /* ClassDeclaration */) { + ts.Debug.fail("Class decorators should not have a second synthetic argument."); + return unknownType; + } + if (node.kind === 138 /* Parameter */) { + node = node.parent; + if (node.kind === 144 /* Constructor */) { + // For a constructor parameter decorator, the `propertyKey` will be `undefined`. + return anyType; + } + } + if (node.kind === 141 /* PropertyDeclaration */ || + node.kind === 143 /* MethodDeclaration */ || + node.kind === 145 /* GetAccessor */ || + node.kind === 146 /* SetAccessor */) { + // The `propertyKey` for a property or method decorator will be a + // string literal type if the member name is an identifier, number, or string; + // otherwise, if the member name is a computed property name it will + // be either string or symbol. + var element = node; + switch (element.name.kind) { + case 69 /* Identifier */: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return getStringLiteralType(element.name); + case 136 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(element.name); + if (allConstituentTypesHaveKind(nameType, 16777216 /* ESSymbol */)) { + return nameType; + } + else { + return stringType; + } + default: + ts.Debug.fail("Unsupported property name."); + return unknownType; + } + } + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + /** + * Returns the effective argument type for the third argument to a decorator. + * If 'node' is a parameter, the effective argument type is the number type. + * If 'node' is a method or accessor, the effective argument type is a + * `TypedPropertyDescriptor` instantiated with the type of the member. + * Class and property decorators do not have a third effective argument. + */ + function getEffectiveDecoratorThirdArgumentType(node) { + // The third argument to a decorator is either its `descriptor` for a method decorator + // or its `parameterIndex` for a paramter decorator + if (node.kind === 214 /* ClassDeclaration */) { + ts.Debug.fail("Class decorators should not have a third synthetic argument."); + return unknownType; + } + if (node.kind === 138 /* Parameter */) { + // The `parameterIndex` for a parameter decorator is always a number + return numberType; + } + if (node.kind === 141 /* PropertyDeclaration */) { + ts.Debug.fail("Property decorators should not have a third synthetic argument."); + return unknownType; + } + if (node.kind === 143 /* MethodDeclaration */ || + node.kind === 145 /* GetAccessor */ || + node.kind === 146 /* SetAccessor */) { + // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` + // for the type of the member. + var propertyType = getTypeOfNode(node); + return createTypedPropertyDescriptorType(propertyType); + } + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + /** + * Returns the effective argument type for the provided argument to a decorator. + */ + function getEffectiveDecoratorArgumentType(node, argIndex) { + if (argIndex === 0) { + return getEffectiveDecoratorFirstArgumentType(node.parent); + } + else if (argIndex === 1) { + return getEffectiveDecoratorSecondArgumentType(node.parent); + } + else if (argIndex === 2) { + return getEffectiveDecoratorThirdArgumentType(node.parent); + } + ts.Debug.fail("Decorators should not have a fourth synthetic argument."); + return unknownType; + } + /** + * Gets the effective argument type for an argument in a call expression. + */ + function getEffectiveArgumentType(node, argIndex, arg) { + // Decorators provide special arguments, a tagged template expression provides + // a special first argument, and string literals get string literal types + // unless we're reporting errors + if (node.kind === 139 /* Decorator */) { + return getEffectiveDecoratorArgumentType(node, argIndex); + } + else if (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */) { + return globalTemplateStringsArrayType; + } + // This is not a synthetic argument, so we return 'undefined' + // to signal that the caller needs to check the argument. + return undefined; + } + /** + * Gets the effective argument expression for an argument in a call expression. + */ + function getEffectiveArgument(node, args, argIndex) { + // For a decorator or the first argument of a tagged template expression we return undefined. + if (node.kind === 139 /* Decorator */ || + (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */)) { + return undefined; + } + return args[argIndex]; + } + /** + * Gets the error node to use when reporting errors for an effective argument. + */ + function getEffectiveArgumentErrorNode(node, argIndex, arg) { + if (node.kind === 139 /* Decorator */) { + // For a decorator, we use the expression of the decorator for error reporting. + return node.expression; + } + else if (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */) { + // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. + return node.template; + } + else { + return arg; + } + } + function resolveCall(node, signatures, candidatesOutArray, headMessage) { + var isTaggedTemplate = node.kind === 170 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 139 /* Decorator */; + var typeArguments; + if (!isTaggedTemplate && !isDecorator) { + typeArguments = node.typeArguments; + // We already perform checking on the type arguments on the class declaration itself. + if (node.expression.kind !== 95 /* SuperKeyword */) { + ts.forEach(typeArguments, checkSourceElement); + } + } + var candidates = candidatesOutArray || []; + // reorderCandidates fills up the candidates array directly + reorderCandidates(signatures, candidates); + if (!candidates.length) { + reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + return resolveErrorCall(node); + } + var args = getEffectiveCallArguments(node); + // The following applies to any value of 'excludeArgument[i]': + // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. + // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. + // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // + // The idea is that we will perform type argument inference & assignability checking once + // without using the susceptible parameters that are functions, and once more for each of those + // parameters, contextually typing each as we go along. + // + // For a tagged template, then the first argument be 'undefined' if necessary + // because it represents a TemplateStringsArray. + // + // For a decorator, no arguments are susceptible to contextual typing due to the fact + // decorators are applied to a declaration by the emitter, and not to an expression. + var excludeArgument; + if (!isDecorator) { + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + } + // The following variables are captured and modified by calls to chooseOverload. + // If overload resolution or type argument inference fails, we want to report the + // best error possible. The best error is one which says that an argument was not + // assignable to a parameter. This implies that everything else about the overload + // was fine. So if there is any overload that is only incorrect because of an + // argument, we will report an error on that one. + // + // function foo(s: string) {} + // function foo(n: number) {} // Report argument error on this overload + // function foo() {} + // foo(true); + // + // If none of the overloads even made it that far, there are two possibilities. + // There was a problem with type arguments for some overload, in which case + // report an error on that. Or none of the overloads even had correct arity, + // in which case give an arity error. + // + // function foo(x: T, y: T) {} // Report type argument inference error + // function foo() {} + // foo(0, true); + // + var candidateForArgumentError; + var candidateForTypeArgumentError; + var resultOfFailedInference; + var result; + // Section 4.12.1: + // if the candidate list contains one or more signatures for which the type of each argument + // expression is a subtype of each corresponding parameter type, the return type of the first + // of those signatures becomes the return type of the function call. + // Otherwise, the return type of the first signature in the candidate list becomes the return + // type of the function call. + // + // Whether the call is an error is determined by assignability of the arguments. The subtype pass + // is just important for choosing the best signature. So in the case where there is only one + // signature, the subtype pass is useless. So skipping it is an optimization. + if (candidates.length > 1) { + result = chooseOverload(candidates, subtypeRelation); + } + if (!result) { + // Reinitialize these pointers for round two + candidateForArgumentError = undefined; + candidateForTypeArgumentError = undefined; + resultOfFailedInference = undefined; + result = chooseOverload(candidates, assignableRelation); + } + if (result) { + return result; + } + // No signatures were applicable. Now report errors based on the last applicable signature with + // no arguments excluded from assignability checks. + // If candidate is undefined, it means that no candidates had a suitable arity. In that case, + // skip the checkApplicableSignature check. + if (candidateForArgumentError) { + // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] + // The importance of excludeArgument is to prevent us from typing function expression parameters + // in arguments too early. If possible, we'd like to only type them once we know the correct + // overload. However, this matters for the case where the call is correct. When the call is + // an error, we don't need to exclude any arguments, although it would cause no harm to do so. + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); + } + else if (candidateForTypeArgumentError) { + if (!isTaggedTemplate && !isDecorator && typeArguments) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], /*reportErrors*/ true, headMessage); + } + else { + ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); + var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; + var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); + var diagnosticChainHead = ts.chainDiagnosticMessages(/*details*/ undefined, // details will be provided by call to reportNoCommonSupertypeError + ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); + if (headMessage) { + diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, headMessage); + } + reportNoCommonSupertypeError(inferenceCandidates, node.expression || node.tag, diagnosticChainHead); + } + } + else { + reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); + } + // No signature was applicable. We have already reported the errors for the invalid signature. + // If this is a type resolution session, e.g. Language Service, try to get better information that anySignature. + // Pick the first candidate that matches the arity. This way we can get a contextual type for cases like: + // declare function f(a: { xa: number; xb: number; }); + // f({ | + if (!produceDiagnostics) { + for (var _i = 0; _i < candidates.length; _i++) { + var candidate = candidates[_i]; + if (hasCorrectArity(node, args, candidate)) { + if (candidate.typeParameters && typeArguments) { + candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); + } + return candidate; + } + } + } + return resolveErrorCall(node); + function reportError(message, arg0, arg1, arg2) { + var errorInfo; + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); + if (headMessage) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + } + function chooseOverload(candidates, relation) { + for (var _i = 0; _i < candidates.length; _i++) { + var originalCandidate = candidates[_i]; + if (!hasCorrectArity(node, args, originalCandidate)) { + continue; + } + var candidate = void 0; + var typeArgumentsAreValid = void 0; + var inferenceContext = originalCandidate.typeParameters + ? createInferenceContext(originalCandidate.typeParameters, /*inferUnionTypes*/ false) + : undefined; + while (true) { + candidate = originalCandidate; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = new Array(candidate.typeParameters.length); + typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false); + } + else { + inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined; + typeArgumentTypes = inferenceContext.inferredTypes; + } + if (!typeArgumentsAreValid) { + break; + } + candidate = getSignatureInstantiation(candidate, typeArgumentTypes); + } + if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { + break; + } + var index = excludeArgument ? ts.indexOf(excludeArgument, true) : -1; + if (index < 0) { + return candidate; + } + excludeArgument[index] = false; + } + // A post-mortem of this iteration of the loop. The signature was not applicable, + // so we want to track it as a candidate for reporting an error. If the candidate + // had no type parameters, or had no issues related to type arguments, we can + // report an error based on the arguments. If there was an issue with type + // arguments, then we can only report an error based on the type arguments. + if (originalCandidate.typeParameters) { + var instantiatedCandidate = candidate; + if (typeArgumentsAreValid) { + candidateForArgumentError = instantiatedCandidate; + } + else { + candidateForTypeArgumentError = originalCandidate; + if (!typeArguments) { + resultOfFailedInference = inferenceContext; + } + } + } + else { + ts.Debug.assert(originalCandidate === candidate); + candidateForArgumentError = originalCandidate; + } + } + return undefined; + } + } + function resolveCallExpression(node, candidatesOutArray) { + if (node.expression.kind === 95 /* SuperKeyword */) { + var superType = checkSuperExpression(node.expression); + if (superType !== unknownType) { + // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated + // with the type arguments specified in the extends clause. + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); + return resolveCall(node, baseConstructors, candidatesOutArray); + } + return resolveUntypedCall(node); + } + var funcType = checkExpression(node.expression); + var apparentType = getApparentType(funcType); + if (apparentType === unknownType) { + // Another error has already been reported + return resolveErrorCall(node); + } + // Technically, this signatures list may be incomplete. We are taking the apparent type, + // but we are not including call signatures that may have been added to the Object or + // Function interface, since they have none by default. This is a bit of a leap of faith + // that the user will not add any. + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + // TS 1.0 spec: 4.12 + // If FuncExpr is of type Any, or of an object type that has no call or construct signatures + // but is a subtype of the Function interface, the call is an untyped function call. In an + // untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual + // types are provided for the argument expressions, and the result is always of type Any. + // We exclude union types because we may have a union of function types that happen to have + // no common signatures. + if (isTypeAny(funcType) || (!callSignatures.length && !constructSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { + // The unknownType indicates that an error already occured (and was reported). No + // need to report another error in this case. + if (funcType !== unknownType && node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call. + // TypeScript employs overload resolution in typed function calls in order to support functions + // with multiple call signatures. + if (!callSignatures.length) { + if (constructSignatures.length) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + } + else { + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + } + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray); + } + function resolveNewExpression(node, candidatesOutArray) { + if (node.arguments && languageVersion < 1 /* ES5 */) { + var spreadIndex = getSpreadArgumentIndex(node.arguments); + if (spreadIndex >= 0) { + error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); + } + } + var expressionType = checkExpression(node.expression); + // If expressionType's apparent type(section 3.8.1) is an object type with one or + // more construct signatures, the expression is processed in the same manner as a + // function call, but using the construct signatures as the initial set of candidate + // signatures for overload resolution. The result type of the function call becomes + // the result type of the operation. + expressionType = getApparentType(expressionType); + if (expressionType === unknownType) { + // Another error has already been reported + return resolveErrorCall(node); + } + // If the expression is a class of abstract type, then it cannot be instantiated. + // Note, only class declarations can be declared abstract. + // In the case of a merged class-module or class-interface declaration, + // only the class declaration node will have the Abstract flag set. + var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); + if (valueDecl && valueDecl.flags & 256 /* Abstract */) { + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + return resolveErrorCall(node); + } + // TS 1.0 spec: 4.11 + // If expressionType is of type Any, Args can be any argument + // list and the result of the operation is of type Any. + if (isTypeAny(expressionType)) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + // Technically, this signatures list may be incomplete. We are taking the apparent type, + // but we are not including construct signatures that may have been added to the Object or + // Function interface, since they have none by default. This is a bit of a leap of faith + // that the user will not add any. + var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */); + if (constructSignatures.length) { + return resolveCall(node, constructSignatures, candidatesOutArray); + } + // If expressionType's apparent type is an object type with no construct signatures but + // one or more call signatures, the expression is processed as a function call. A compile-time + // error occurs if the result of the function call is not Void. The type of the result of the + // operation is Any. + var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); + if (callSignatures.length) { + var signature = resolveCall(node, callSignatures, candidatesOutArray); + if (getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + return signature; + } + error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); + return resolveErrorCall(node); + } + function resolveTaggedTemplateExpression(node, candidatesOutArray) { + var tagType = checkExpression(node.tag); + var apparentType = getApparentType(tagType); + if (apparentType === unknownType) { + // Another error has already been reported + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & 16384 /* Union */) && isTypeAssignableTo(tagType, globalFunctionType))) { + return resolveUntypedCall(node); + } + if (!callSignatures.length) { + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray); + } + /** + * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. + */ + function getDiagnosticHeadMessageForDecoratorResolution(node) { + switch (node.parent.kind) { + case 214 /* ClassDeclaration */: + case 186 /* ClassExpression */: + return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; + case 138 /* Parameter */: + return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; + case 141 /* PropertyDeclaration */: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; + case 143 /* MethodDeclaration */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + } + } + /** + * Resolves a decorator as if it were a call expression. + */ + function resolveDecorator(node, candidatesOutArray) { + var funcType = checkExpression(node.expression); + var apparentType = getApparentType(funcType); + if (apparentType === unknownType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + if (funcType === anyType || (!callSignatures.length && !(funcType.flags & 16384 /* Union */) && isTypeAssignableTo(funcType, globalFunctionType))) { + return resolveUntypedCall(node); + } + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + if (!callSignatures.length) { + var errorInfo; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, headMessage); + } + // candidatesOutArray is passed by signature help in the language service, and collectCandidates + // must fill it up with the appropriate candidate signatures + function getResolvedSignature(node, candidatesOutArray) { + var links = getNodeLinks(node); + // If getResolvedSignature has already been called, we will have cached the resolvedSignature. + // However, it is possible that either candidatesOutArray was not passed in the first time, + // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work + // to correctly fill the candidatesOutArray. + if (!links.resolvedSignature || candidatesOutArray) { + links.resolvedSignature = anySignature; + if (node.kind === 168 /* CallExpression */) { + links.resolvedSignature = resolveCallExpression(node, candidatesOutArray); + } + else if (node.kind === 169 /* NewExpression */) { + links.resolvedSignature = resolveNewExpression(node, candidatesOutArray); + } + else if (node.kind === 170 /* TaggedTemplateExpression */) { + links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray); + } + else if (node.kind === 139 /* Decorator */) { + links.resolvedSignature = resolveDecorator(node, candidatesOutArray); + } + else { + ts.Debug.fail("Branch in 'getResolvedSignature' should be unreachable."); + } + } + return links.resolvedSignature; + } + /** + * Syntactically and semantically checks a call or new expression. + * @param node The call/new expression to be checked. + * @returns On success, the expression's signature's return type. On failure, anyType. + */ + function checkCallExpression(node) { + // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true + checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); + var signature = getResolvedSignature(node); + if (node.expression.kind === 95 /* SuperKeyword */) { + return voidType; + } + if (node.kind === 169 /* NewExpression */) { + var declaration = signature.declaration; + if (declaration && + declaration.kind !== 144 /* Constructor */ && + declaration.kind !== 148 /* ConstructSignature */ && + declaration.kind !== 153 /* ConstructorType */) { + // When resolved signature is a call signature (and not a construct signature) the result type is any + if (compilerOptions.noImplicitAny) { + error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); + } + return anyType; + } + } + return getReturnTypeOfSignature(signature); + } + function checkTaggedTemplateExpression(node) { + return getReturnTypeOfSignature(getResolvedSignature(node)); + } + function checkAssertion(node) { + var exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); + var targetType = getTypeFromTypeNode(node.type); + if (produceDiagnostics && targetType !== unknownType) { + var widenedType = getWidenedType(exprType); + if (!(isTypeAssignableTo(targetType, widenedType))) { + checkTypeAssignableTo(exprType, targetType, node, ts.Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other); + } + } + return targetType; + } + function getTypeAtPosition(signature, pos) { + return signature.hasRestParameter ? + pos < signature.parameters.length - 1 ? getTypeOfSymbol(signature.parameters[pos]) : getRestTypeOfSignature(signature) : + pos < signature.parameters.length ? getTypeOfSymbol(signature.parameters[pos]) : anyType; + } + function assignContextualParameterTypes(signature, context, mapper) { + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var parameter = signature.parameters[i]; + var contextualParameterType = getTypeAtPosition(context, i); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + } + if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { + var parameter = ts.lastOrUndefined(signature.parameters); + var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + } + } + // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push + // the destructured type into the contained binding elements. + function assignBindingElementTypes(node) { + if (ts.isBindingPattern(node.name)) { + for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.kind !== 187 /* OmittedExpression */) { + if (element.name.kind === 69 /* Identifier */) { + getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); + } + assignBindingElementTypes(element); + } + } + } + } + function assignTypeToParameterAndFixTypeParameters(parameter, contextualType, mapper) { + var links = getSymbolLinks(parameter); + if (!links.type) { + links.type = instantiateType(contextualType, mapper); + assignBindingElementTypes(parameter.valueDeclaration); + } + else if (isInferentialContext(mapper)) { + // Even if the parameter already has a type, it might be because it was given a type while + // processing the function as an argument to a prior signature during overload resolution. + // If this was the case, it may have caused some type parameters to be fixed. So here, + // we need to ensure that type parameters at the same positions get fixed again. This is + // done by calling instantiateType to attach the mapper to the contextualType, and then + // calling inferTypes to force a walk of contextualType so that all the correct fixing + // happens. The choice to pass in links.type may seem kind of arbitrary, but it serves + // to make sure that all the correct positions in contextualType are reached by the walk. + // Here is an example: + // + // interface Base { + // baseProp; + // } + // interface Derived extends Base { + // toBase(): Base; + // } + // + // var derived: Derived; + // + // declare function foo(x: T, func: (p: T) => T): T; + // declare function foo(x: T, func: (p: T) => T): T; + // + // var result = foo(derived, d => d.toBase()); + // + // We are typing d while checking the second overload. But we've already given d + // a type (Derived) from the first overload. However, we still want to fix the + // T in the second overload so that we do not infer Base as a candidate for T + // (inferring Base would make type argument inference inconsistent between the two + // overloads). + inferTypes(mapper.context, links.type, instantiateType(contextualType, mapper)); + } + } + function createPromiseType(promisedType) { + // creates a `Promise` type where `T` is the promisedType argument + var globalPromiseType = getGlobalPromiseType(); + if (globalPromiseType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType); + return createTypeReference(globalPromiseType, [promisedType]); + } + return emptyObjectType; + } + function getReturnTypeFromBody(func, contextualMapper) { + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); + if (!func.body) { + return unknownType; + } + var isAsync = ts.isAsyncFunctionLike(func); + var type; + if (func.body.kind !== 192 /* Block */) { + type = checkExpressionCached(func.body, contextualMapper); + if (isAsync) { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body should be unwrapped to its awaited type, which we will wrap in + // the native Promise type later in this function. + type = checkAwaitedType(type, func, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); + } + } + else { + var types; + var funcIsGenerator = !!func.asteriskToken; + if (funcIsGenerator) { + types = checkAndAggregateYieldOperandTypes(func.body, contextualMapper); + if (types.length === 0) { + var iterableIteratorAny = createIterableIteratorType(anyType); + if (compilerOptions.noImplicitAny) { + error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); + } + return iterableIteratorAny; + } + } + else { + types = checkAndAggregateReturnExpressionTypes(func.body, contextualMapper, isAsync); + if (types.length === 0) { + if (isAsync) { + // For an async function, the return type will not be void, but rather a Promise for void. + var promiseType = createPromiseType(voidType); + if (promiseType === emptyObjectType) { + error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + return unknownType; + } + return promiseType; + } + else { + return voidType; + } + } + } + // When yield/return statements are contextually typed we allow the return type to be a union type. + // Otherwise we require the yield/return expressions to have a best common supertype. + type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); + if (!type) { + if (funcIsGenerator) { + error(func, ts.Diagnostics.No_best_common_type_exists_among_yield_expressions); + return createIterableIteratorType(unknownType); + } + else { + error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); + return unknownType; + } + } + if (funcIsGenerator) { + type = createIterableIteratorType(type); + } + } + if (!contextualSignature) { + reportErrorsFromWidening(func, type); + } + var widenedType = getWidenedType(type); + if (isAsync) { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body is awaited type of the body, wrapped in a native Promise type. + var promiseType = createPromiseType(widenedType); + if (promiseType === emptyObjectType) { + error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + return unknownType; + } + return promiseType; + } + else { + return widenedType; + } + } + function checkAndAggregateYieldOperandTypes(body, contextualMapper) { + var aggregatedTypes = []; + ts.forEachYieldExpression(body, function (yieldExpression) { + var expr = yieldExpression.expression; + if (expr) { + var type = checkExpressionCached(expr, contextualMapper); + if (yieldExpression.asteriskToken) { + // A yield* expression effectively yields everything that its operand yields + type = checkElementTypeOfIterable(type, yieldExpression.expression); + } + if (!ts.contains(aggregatedTypes, type)) { + aggregatedTypes.push(type); + } + } + }); + return aggregatedTypes; + } + function checkAndAggregateReturnExpressionTypes(body, contextualMapper, isAsync) { + var aggregatedTypes = []; + ts.forEachReturnStatement(body, function (returnStatement) { + var expr = returnStatement.expression; + if (expr) { + var type = checkExpressionCached(expr, contextualMapper); + if (isAsync) { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body should be unwrapped to its awaited type, which should be wrapped in + // the native Promise type by the caller. + type = checkAwaitedType(type, body.parent, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); + } + if (!ts.contains(aggregatedTypes, type)) { + aggregatedTypes.push(type); + } + } + }); + return aggregatedTypes; + } + function bodyContainsAReturnStatement(funcBody) { + return ts.forEachReturnStatement(funcBody, function (returnStatement) { + return true; + }); + } + function bodyContainsSingleThrowStatement(body) { + return (body.statements.length === 1) && (body.statements[0].kind === 208 /* ThrowStatement */); + } + // TypeScript Specification 1.0 (6.3) - July 2014 + // An explicitly typed function whose return type isn't the Void or the Any type + // must have at least one return statement somewhere in its body. + // An exception to this rule is if the function implementation consists of a single 'throw' statement. + function checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(func, returnType) { + if (!produceDiagnostics) { + return; + } + // Functions that return 'void' or 'any' don't need any return expressions. + if (returnType === voidType || isTypeAny(returnType)) { + return; + } + // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. + if (ts.nodeIsMissing(func.body) || func.body.kind !== 192 /* Block */) { + return; + } + var bodyBlock = func.body; + // Ensure the body has at least one return expression. + if (bodyContainsAReturnStatement(bodyBlock)) { + return; + } + // If there are no return expressions, then we need to check if + // the function body consists solely of a throw statement; + // this is to make an exception for unimplemented functions. + if (bodyContainsSingleThrowStatement(bodyBlock)) { + return; + } + // This function does not conform to the specification. + error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement); + } + function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { + ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + // Grammar checking + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 173 /* FunctionExpression */) { + checkGrammarForGenerator(node); + } + // The identityMapper object is used to indicate that function expressions are wildcards + if (contextualMapper === identityMapper && isContextSensitive(node)) { + return anyFunctionType; + } + var isAsync = ts.isAsyncFunctionLike(node); + if (isAsync) { + emitAwaiter = true; + } + var links = getNodeLinks(node); + var type = getTypeOfSymbol(node.symbol); + var contextSensitive = isContextSensitive(node); + var mightFixTypeParameters = contextSensitive && isInferentialContext(contextualMapper); + // Check if function expression is contextually typed and assign parameter types if so. + // See the comment in assignTypeToParameterAndFixTypeParameters to understand why we need to + // check mightFixTypeParameters. + if (mightFixTypeParameters || !(links.flags & 1024 /* ContextChecked */)) { + var contextualSignature = getContextualSignature(node); + // If a type check is started at a function expression that is an argument of a function call, obtaining the + // contextual type may recursively get back to here during overload resolution of the call. If so, we will have + // already assigned contextual types. + var contextChecked = !!(links.flags & 1024 /* ContextChecked */); + if (mightFixTypeParameters || !contextChecked) { + links.flags |= 1024 /* ContextChecked */; + if (contextualSignature) { + var signature = getSignaturesOfType(type, 0 /* Call */)[0]; + if (contextSensitive) { + assignContextualParameterTypes(signature, contextualSignature, contextualMapper || identityMapper); + } + if (mightFixTypeParameters || !node.type && !signature.resolvedReturnType) { + var returnType = getReturnTypeFromBody(node, contextualMapper); + if (!signature.resolvedReturnType) { + signature.resolvedReturnType = returnType; + } + } + } + if (!contextChecked) { + checkSignatureDeclaration(node); + } + } + } + if (produceDiagnostics && node.kind !== 143 /* MethodDeclaration */ && node.kind !== 142 /* MethodSignature */) { + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + } + return type; + } + function checkFunctionExpressionOrObjectLiteralMethodBody(node) { + ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var isAsync = ts.isAsyncFunctionLike(node); + if (isAsync) { + emitAwaiter = true; + } + var returnType = node.type && getTypeFromTypeNode(node.type); + var promisedType; + if (returnType && isAsync) { + promisedType = checkAsyncFunctionReturnType(node); + } + if (returnType && !node.asteriskToken) { + checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, isAsync ? promisedType : returnType); + } + if (node.body) { + if (!node.type) { + // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors + // we need. An example is the noImplicitAny errors resulting from widening the return expression + // of a function. Because checking of function expression bodies is deferred, there was never an + // appropriate time to do this during the main walk of the file (see the comment at the top of + // checkFunctionExpressionBodies). So it must be done now. + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + if (node.body.kind === 192 /* Block */) { + checkSourceElement(node.body); + } + else { + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so we + // should not be checking assignability of a promise to the return type. Instead, we need to + // check assignability of the awaited type of the expression body against the promised type of + // its return type annotation. + var exprType = checkExpression(node.body); + if (returnType) { + if (isAsync) { + var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member); + checkTypeAssignableTo(awaitedType, promisedType, node.body); + } + else { + checkTypeAssignableTo(exprType, returnType, node.body); + } + } + checkFunctionAndClassExpressionBodies(node.body); + } + } + } + function checkArithmeticOperandType(operand, type, diagnostic) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 132 /* NumberLike */)) { + error(operand, diagnostic); + return false; + } + return true; + } + function checkReferenceExpression(n, invalidReferenceMessage, constantVariableMessage) { + function findSymbol(n) { + var symbol = getNodeLinks(n).resolvedSymbol; + // Because we got the symbol from the resolvedSymbol property, it might be of kind + // SymbolFlags.ExportValue. In this case it is necessary to get the actual export + // symbol, which will have the correct flags set on it. + return symbol && getExportSymbolOfValueSymbolIfExported(symbol); + } + function isReferenceOrErrorExpression(n) { + // TypeScript 1.0 spec (April 2014): + // Expressions are classified as values or references. + // References are the subset of expressions that are permitted as the target of an assignment. + // Specifically, references are combinations of identifiers(section 4.3), parentheses(section 4.7), + // and property accesses(section 4.10). + // All other expression constructs described in this chapter are classified as values. + switch (n.kind) { + case 69 /* Identifier */: { + var symbol = findSymbol(n); + // TypeScript 1.0 spec (April 2014): 4.3 + // An identifier expression that references a variable or parameter is classified as a reference. + // An identifier expression that references any other kind of entity is classified as a value(and therefore cannot be the target of an assignment). + return !symbol || symbol === unknownSymbol || symbol === argumentsSymbol || (symbol.flags & 3 /* Variable */) !== 0; + } + case 166 /* PropertyAccessExpression */: { + var symbol = findSymbol(n); + // TypeScript 1.0 spec (April 2014): 4.10 + // A property access expression is always classified as a reference. + // NOTE (not in spec): assignment to enum members should not be allowed + return !symbol || symbol === unknownSymbol || (symbol.flags & ~8 /* EnumMember */) !== 0; + } + case 167 /* ElementAccessExpression */: + // old compiler doesn't check indexed access + return true; + case 172 /* ParenthesizedExpression */: + return isReferenceOrErrorExpression(n.expression); + default: + return false; + } + } + function isConstVariableReference(n) { + switch (n.kind) { + case 69 /* Identifier */: + case 166 /* PropertyAccessExpression */: { + var symbol = findSymbol(n); + return symbol && (symbol.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 32768 /* Const */) !== 0; + } + case 167 /* ElementAccessExpression */: { + var index = n.argumentExpression; + var symbol = findSymbol(n.expression); + if (symbol && index && index.kind === 9 /* StringLiteral */) { + var name_12 = index.text; + var prop = getPropertyOfType(getTypeOfSymbol(symbol), name_12); + return prop && (prop.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(prop) & 32768 /* Const */) !== 0; + } + return false; + } + case 172 /* ParenthesizedExpression */: + return isConstVariableReference(n.expression); + default: + return false; + } + } + if (!isReferenceOrErrorExpression(n)) { + error(n, invalidReferenceMessage); + return false; + } + if (isConstVariableReference(n)) { + error(n, constantVariableMessage); + return false; + } + return true; + } + function checkDeleteExpression(node) { + checkExpression(node.expression); + return booleanType; + } + function checkTypeOfExpression(node) { + checkExpression(node.expression); + return stringType; + } + function checkVoidExpression(node) { + checkExpression(node.expression); + return undefinedType; + } + function checkAwaitExpression(node) { + // Grammar checking + if (produceDiagnostics) { + if (!(node.parserContextFlags & 8 /* Await */)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + var operandType = checkExpression(node.expression); + return checkAwaitedType(operandType, node); + } + function checkPrefixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + switch (node.operator) { + case 35 /* PlusToken */: + case 36 /* MinusToken */: + case 50 /* TildeToken */: + if (someConstituentTypeHasKind(operandType, 16777216 /* ESSymbol */)) { + error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); + } + return numberType; + case 49 /* ExclamationToken */: + return booleanType; + case 41 /* PlusPlusToken */: + case 42 /* MinusMinusToken */: + var ok = checkArithmeticOperandType(node.operand, operandType, ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + if (ok) { + // run check only if former checks succeeded to avoid reporting cascading errors + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant); + } + return numberType; + } + return unknownType; + } + function checkPostfixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + var ok = checkArithmeticOperandType(node.operand, operandType, ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + if (ok) { + // run check only if former checks succeeded to avoid reporting cascading errors + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant); + } + return numberType; + } + // Just like isTypeOfKind below, except that it returns true if *any* constituent + // has this kind. + function someConstituentTypeHasKind(type, kind) { + if (type.flags & kind) { + return true; + } + if (type.flags & 49152 /* UnionOrIntersection */) { + var types = type.types; + for (var _i = 0; _i < types.length; _i++) { + var current = types[_i]; + if (current.flags & kind) { + return true; + } + } + return false; + } + return false; + } + // Return true if type has the given flags, or is a union or intersection type composed of types that all have those flags. + function allConstituentTypesHaveKind(type, kind) { + if (type.flags & kind) { + return true; + } + if (type.flags & 49152 /* UnionOrIntersection */) { + var types = type.types; + for (var _i = 0; _i < types.length; _i++) { + var current = types[_i]; + if (!(current.flags & kind)) { + return false; + } + } + return true; + } + return false; + } + function isConstEnumObjectType(type) { + return type.flags & (80896 /* ObjectType */ | 65536 /* Anonymous */) && type.symbol && isConstEnumSymbol(type.symbol); + } + function isConstEnumSymbol(symbol) { + return (symbol.flags & 128 /* ConstEnum */) !== 0; + } + function checkInstanceOfExpression(left, right, leftType, rightType) { + // TypeScript 1.0 spec (April 2014): 4.15.4 + // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, + // and the right operand to be of type Any or a subtype of the 'Function' interface type. + // The result is always of the Boolean primitive type. + // NOTE: do not raise error if leftType is unknown as related error was already reported + if (allConstituentTypesHaveKind(leftType, 16777726 /* Primitive */)) { + error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + // NOTE: do not raise error if right is unknown as related error was already reported + if (!(isTypeAny(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); + } + return booleanType; + } + function checkInExpression(left, right, leftType, rightType) { + // TypeScript 1.0 spec (April 2014): 4.15.5 + // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, + // and the right operand to be of type Any, an object type, or a type parameter type. + // The result is always of the Boolean primitive type. + if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 /* StringLike */ | 132 /* NumberLike */ | 16777216 /* ESSymbol */)) { + error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); + } + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 /* ObjectType */ | 512 /* TypeParameter */)) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + return booleanType; + } + function checkObjectLiteralAssignment(node, sourceType, contextualMapper) { + var properties = node.properties; + for (var _i = 0; _i < properties.length; _i++) { + var p = properties[_i]; + if (p.kind === 245 /* PropertyAssignment */ || p.kind === 246 /* ShorthandPropertyAssignment */) { + // TODO(andersh): Computed property support + var name_13 = p.name; + var type = isTypeAny(sourceType) + ? sourceType + : getTypeOfPropertyOfType(sourceType, name_13.text) || + isNumericLiteralName(name_13.text) && getIndexTypeOfType(sourceType, 1 /* Number */) || + getIndexTypeOfType(sourceType, 0 /* String */); + if (type) { + if (p.kind === 246 /* ShorthandPropertyAssignment */) { + checkDestructuringAssignment(p, type); + } + else { + checkDestructuringAssignment(p.initializer || name_13, type); + } + } + else { + error(name_13, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(sourceType), ts.declarationNameToString(name_13)); + } + } + else { + error(p, ts.Diagnostics.Property_assignment_expected); + } + } + return sourceType; + } + function checkArrayLiteralAssignment(node, sourceType, contextualMapper) { + // This elementType will be used if the specific property corresponding to this index is not + // present (aka the tuple element property). This call also checks that the parentType is in + // fact an iterable or array (depending on target language). + var elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false) || unknownType; + var elements = node.elements; + for (var i = 0; i < elements.length; i++) { + var e = elements[i]; + if (e.kind !== 187 /* OmittedExpression */) { + if (e.kind !== 185 /* SpreadElementExpression */) { + var propName = "" + i; + var type = isTypeAny(sourceType) + ? sourceType + : isTupleLikeType(sourceType) + ? getTypeOfPropertyOfType(sourceType, propName) + : elementType; + if (type) { + checkDestructuringAssignment(e, type, contextualMapper); + } + else { + if (isTupleType(sourceType)) { + error(e, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), sourceType.elementTypes.length, elements.length); + } + else { + error(e, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); + } + } + } + else { + if (i < elements.length - 1) { + error(e, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); + } + else { + var restExpression = e.expression; + if (restExpression.kind === 181 /* BinaryExpression */ && restExpression.operatorToken.kind === 56 /* EqualsToken */) { + error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + else { + checkDestructuringAssignment(restExpression, createArrayType(elementType), contextualMapper); + } + } + } + } + } + return sourceType; + } + function checkDestructuringAssignment(exprOrAssignment, sourceType, contextualMapper) { + var target; + if (exprOrAssignment.kind === 246 /* ShorthandPropertyAssignment */) { + var prop = exprOrAssignment; + if (prop.objectAssignmentInitializer) { + checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); + } + target = exprOrAssignment.name; + } + else { + target = exprOrAssignment; + } + if (target.kind === 181 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { + checkBinaryExpression(target, contextualMapper); + target = target.left; + } + if (target.kind === 165 /* ObjectLiteralExpression */) { + return checkObjectLiteralAssignment(target, sourceType, contextualMapper); + } + if (target.kind === 164 /* ArrayLiteralExpression */) { + return checkArrayLiteralAssignment(target, sourceType, contextualMapper); + } + return checkReferenceAssignment(target, sourceType, contextualMapper); + } + function checkReferenceAssignment(target, sourceType, contextualMapper) { + var targetType = checkExpression(target, contextualMapper); + if (checkReferenceExpression(target, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant)) { + checkTypeAssignableTo(sourceType, targetType, target, /*headMessage*/ undefined); + } + return sourceType; + } + function checkBinaryExpression(node, contextualMapper) { + return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, contextualMapper, node); + } + function checkBinaryLikeExpression(left, operatorToken, right, contextualMapper, errorNode) { + var operator = operatorToken.kind; + if (operator === 56 /* EqualsToken */ && (left.kind === 165 /* ObjectLiteralExpression */ || left.kind === 164 /* ArrayLiteralExpression */)) { + return checkDestructuringAssignment(left, checkExpression(right, contextualMapper), contextualMapper); + } + var leftType = checkExpression(left, contextualMapper); + var rightType = checkExpression(right, contextualMapper); + switch (operator) { + case 37 /* AsteriskToken */: + case 38 /* AsteriskAsteriskToken */: + case 59 /* AsteriskEqualsToken */: + case 60 /* AsteriskAsteriskEqualsToken */: + case 39 /* SlashToken */: + case 61 /* SlashEqualsToken */: + case 40 /* PercentToken */: + case 62 /* PercentEqualsToken */: + case 36 /* MinusToken */: + case 58 /* MinusEqualsToken */: + case 43 /* LessThanLessThanToken */: + case 63 /* LessThanLessThanEqualsToken */: + case 44 /* GreaterThanGreaterThanToken */: + case 64 /* GreaterThanGreaterThanEqualsToken */: + case 45 /* GreaterThanGreaterThanGreaterThanToken */: + case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 47 /* BarToken */: + case 67 /* BarEqualsToken */: + case 48 /* CaretToken */: + case 68 /* CaretEqualsToken */: + case 46 /* AmpersandToken */: + case 66 /* AmpersandEqualsToken */: + // TypeScript 1.0 spec (April 2014): 4.19.1 + // These operators require their operands to be of type Any, the Number primitive type, + // or an enum type. Operands of an enum type are treated + // as having the primitive type Number. If one operand is the null or undefined value, + // it is treated as having the type of the other operand. + // The result is always of the Number primitive type. + if (leftType.flags & (32 /* Undefined */ | 64 /* Null */)) + leftType = rightType; + if (rightType.flags & (32 /* Undefined */ | 64 /* Null */)) + rightType = leftType; + var suggestedOperator; + // if a user tries to apply a bitwise operator to 2 boolean operands + // try and return them a helpful suggestion + if ((leftType.flags & 8 /* Boolean */) && + (rightType.flags & 8 /* Boolean */) && + (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { + error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); + } + else { + // otherwise just check each operand separately and report errors as normal + var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + if (leftOk && rightOk) { + checkAssignmentOperator(numberType); + } + } + return numberType; + case 35 /* PlusToken */: + case 57 /* PlusEqualsToken */: + // TypeScript 1.0 spec (April 2014): 4.19.2 + // The binary + operator requires both operands to be of the Number primitive type or an enum type, + // or at least one of the operands to be of type Any or the String primitive type. + // If one operand is the null or undefined value, it is treated as having the type of the other operand. + if (leftType.flags & (32 /* Undefined */ | 64 /* Null */)) + leftType = rightType; + if (rightType.flags & (32 /* Undefined */ | 64 /* Null */)) + rightType = leftType; + var resultType; + if (allConstituentTypesHaveKind(leftType, 132 /* NumberLike */) && allConstituentTypesHaveKind(rightType, 132 /* NumberLike */)) { + // Operands of an enum type are treated as having the primitive type Number. + // If both operands are of the Number primitive type, the result is of the Number primitive type. + resultType = numberType; + } + else { + if (allConstituentTypesHaveKind(leftType, 258 /* StringLike */) || allConstituentTypesHaveKind(rightType, 258 /* StringLike */)) { + // If one or both operands are of the String primitive type, the result is of the String primitive type. + resultType = stringType; + } + else if (isTypeAny(leftType) || isTypeAny(rightType)) { + // Otherwise, the result is of type Any. + // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we. + resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; + } + // Symbols are not allowed at all in arithmetic expressions + if (resultType && !checkForDisallowedESSymbolOperand(operator)) { + return resultType; + } + } + if (!resultType) { + reportOperatorError(); + return anyType; + } + if (operator === 57 /* PlusEqualsToken */) { + checkAssignmentOperator(resultType); + } + return resultType; + case 25 /* LessThanToken */: + case 27 /* GreaterThanToken */: + case 28 /* LessThanEqualsToken */: + case 29 /* GreaterThanEqualsToken */: + if (!checkForDisallowedESSymbolOperand(operator)) { + return booleanType; + } + // Fall through + case 30 /* EqualsEqualsToken */: + case 31 /* ExclamationEqualsToken */: + case 32 /* EqualsEqualsEqualsToken */: + case 33 /* ExclamationEqualsEqualsToken */: + if (!isTypeAssignableTo(leftType, rightType) && !isTypeAssignableTo(rightType, leftType)) { + reportOperatorError(); + } + return booleanType; + case 91 /* InstanceOfKeyword */: + return checkInstanceOfExpression(left, right, leftType, rightType); + case 90 /* InKeyword */: + return checkInExpression(left, right, leftType, rightType); + case 51 /* AmpersandAmpersandToken */: + return rightType; + case 52 /* BarBarToken */: + return getUnionType([leftType, rightType]); + case 56 /* EqualsToken */: + checkAssignmentOperator(rightType); + return getRegularTypeOfObjectLiteral(rightType); + case 24 /* CommaToken */: + return rightType; + } + // Return true if there was no error, false if there was an error. + function checkForDisallowedESSymbolOperand(operator) { + var offendingSymbolOperand = someConstituentTypeHasKind(leftType, 16777216 /* ESSymbol */) ? left : + someConstituentTypeHasKind(rightType, 16777216 /* ESSymbol */) ? right : + undefined; + if (offendingSymbolOperand) { + error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); + return false; + } + return true; + } + function getSuggestedBooleanOperator(operator) { + switch (operator) { + case 47 /* BarToken */: + case 67 /* BarEqualsToken */: + return 52 /* BarBarToken */; + case 48 /* CaretToken */: + case 68 /* CaretEqualsToken */: + return 33 /* ExclamationEqualsEqualsToken */; + case 46 /* AmpersandToken */: + case 66 /* AmpersandEqualsToken */: + return 51 /* AmpersandAmpersandToken */; + default: + return undefined; + } + } + function checkAssignmentOperator(valueType) { + if (produceDiagnostics && operator >= 56 /* FirstAssignment */ && operator <= 68 /* LastAssignment */) { + // TypeScript 1.0 spec (April 2014): 4.17 + // An assignment of the form + // VarExpr = ValueExpr + // requires VarExpr to be classified as a reference + // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) + // and the type of the non - compound operation to be assignable to the type of VarExpr. + var ok = checkReferenceExpression(left, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); + // Use default messages + if (ok) { + // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported + checkTypeAssignableTo(valueType, leftType, left, /*headMessage*/ undefined); + } + } + } + function reportOperatorError() { + error(errorNode || operatorToken, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), typeToString(leftType), typeToString(rightType)); + } + } + function isYieldExpressionInClass(node) { + var current = node; + var parent = node.parent; + while (parent) { + if (ts.isFunctionLike(parent) && current === parent.body) { + return false; + } + else if (ts.isClassLike(current)) { + return true; + } + current = parent; + parent = parent.parent; + } + return false; + } + function checkYieldExpression(node) { + // Grammar checking + if (produceDiagnostics) { + if (!(node.parserContextFlags & 2 /* Yield */) || isYieldExpressionInClass(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + if (node.expression) { + var func = ts.getContainingFunction(node); + // If the user's code is syntactically correct, the func should always have a star. After all, + // we are in a yield context. + if (func && func.asteriskToken) { + var expressionType = checkExpressionCached(node.expression, /*contextualMapper*/ undefined); + var expressionElementType; + var nodeIsYieldStar = !!node.asteriskToken; + if (nodeIsYieldStar) { + expressionElementType = checkElementTypeOfIterable(expressionType, node.expression); + } + // There is no point in doing an assignability check if the function + // has no explicit return type because the return type is directly computed + // from the yield expressions. + if (func.type) { + var signatureElementType = getElementTypeOfIterableIterator(getTypeFromTypeNode(func.type)) || anyType; + if (nodeIsYieldStar) { + checkTypeAssignableTo(expressionElementType, signatureElementType, node.expression, /*headMessage*/ undefined); + } + else { + checkTypeAssignableTo(expressionType, signatureElementType, node.expression, /*headMessage*/ undefined); + } + } + } + } + // Both yield and yield* expressions have type 'any' + return anyType; + } + function checkConditionalExpression(node, contextualMapper) { + checkExpression(node.condition); + var type1 = checkExpression(node.whenTrue, contextualMapper); + var type2 = checkExpression(node.whenFalse, contextualMapper); + return getUnionType([type1, type2]); + } + function checkTemplateExpression(node) { + // We just want to check each expressions, but we are unconcerned with + // the type of each expression, as any value may be coerced into a string. + // It is worth asking whether this is what we really want though. + // A place where we actually *are* concerned with the expressions' types are + // in tagged templates. + ts.forEach(node.templateSpans, function (templateSpan) { + checkExpression(templateSpan.expression); + }); + return stringType; + } + function checkExpressionWithContextualType(node, contextualType, contextualMapper) { + var saveContextualType = node.contextualType; + node.contextualType = contextualType; + var result = checkExpression(node, contextualMapper); + node.contextualType = saveContextualType; + return result; + } + function checkExpressionCached(node, contextualMapper) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = checkExpression(node, contextualMapper); + } + return links.resolvedType; + } + function checkPropertyAssignment(node, contextualMapper) { + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 136 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + return checkExpression(node.initializer, contextualMapper); + } + function checkObjectLiteralMethod(node, contextualMapper) { + // Grammar checking + checkGrammarMethod(node); + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 136 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); + return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper); + } + function instantiateTypeWithSingleGenericCallSignature(node, type, contextualMapper) { + if (isInferentialContext(contextualMapper)) { + var signature = getSingleCallSignature(type); + if (signature && signature.typeParameters) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualSignature = getSingleCallSignature(contextualType); + if (contextualSignature && !contextualSignature.typeParameters) { + return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper)); + } + } + } + } + return type; + } + // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When + // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the + // expression is being inferentially typed (section 4.12.2 in spec) and provides the type mapper to use in + // conjunction with the generic contextual type. When contextualMapper is equal to the identityMapper function + // object, it serves as an indicator that all contained function and arrow expressions should be considered to + // have the wildcard function type; this form of type check is used during overload resolution to exclude + // contextually typed function and arrow expressions in the initial phase. + function checkExpression(node, contextualMapper) { + var type; + if (node.kind === 135 /* QualifiedName */) { + type = checkQualifiedName(node); + } + else { + var uninstantiatedType = checkExpressionWorker(node, contextualMapper); + type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper); + } + if (isConstEnumObjectType(type)) { + // enum object type for const enums are only permitted in: + // - 'left' in property access + // - 'object' in indexed access + // - target in rhs of import statement + var ok = (node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 167 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); + if (!ok) { + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); + } + } + return type; + } + function checkNumericLiteral(node) { + // Grammar checking + checkGrammarNumericLiteral(node); + return numberType; + } + function checkExpressionWorker(node, contextualMapper) { + switch (node.kind) { + case 69 /* Identifier */: + return checkIdentifier(node); + case 97 /* ThisKeyword */: + return checkThisExpression(node); + case 95 /* SuperKeyword */: + return checkSuperExpression(node); + case 93 /* NullKeyword */: + return nullType; + case 99 /* TrueKeyword */: + case 84 /* FalseKeyword */: + return booleanType; + case 8 /* NumericLiteral */: + return checkNumericLiteral(node); + case 183 /* TemplateExpression */: + return checkTemplateExpression(node); + case 9 /* StringLiteral */: + case 11 /* NoSubstitutionTemplateLiteral */: + return stringType; + case 10 /* RegularExpressionLiteral */: + return globalRegExpType; + case 164 /* ArrayLiteralExpression */: + return checkArrayLiteral(node, contextualMapper); + case 165 /* ObjectLiteralExpression */: + return checkObjectLiteral(node, contextualMapper); + case 166 /* PropertyAccessExpression */: + return checkPropertyAccessExpression(node); + case 167 /* ElementAccessExpression */: + return checkIndexedAccess(node); + case 168 /* CallExpression */: + case 169 /* NewExpression */: + return checkCallExpression(node); + case 170 /* TaggedTemplateExpression */: + return checkTaggedTemplateExpression(node); + case 172 /* ParenthesizedExpression */: + return checkExpression(node.expression, contextualMapper); + case 186 /* ClassExpression */: + return checkClassExpression(node); + case 173 /* FunctionExpression */: + case 174 /* ArrowFunction */: + return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); + case 176 /* TypeOfExpression */: + return checkTypeOfExpression(node); + case 171 /* TypeAssertionExpression */: + case 189 /* AsExpression */: + return checkAssertion(node); + case 175 /* DeleteExpression */: + return checkDeleteExpression(node); + case 177 /* VoidExpression */: + return checkVoidExpression(node); + case 178 /* AwaitExpression */: + return checkAwaitExpression(node); + case 179 /* PrefixUnaryExpression */: + return checkPrefixUnaryExpression(node); + case 180 /* PostfixUnaryExpression */: + return checkPostfixUnaryExpression(node); + case 181 /* BinaryExpression */: + return checkBinaryExpression(node, contextualMapper); + case 182 /* ConditionalExpression */: + return checkConditionalExpression(node, contextualMapper); + case 185 /* SpreadElementExpression */: + return checkSpreadElementExpression(node, contextualMapper); + case 187 /* OmittedExpression */: + return undefinedType; + case 184 /* YieldExpression */: + return checkYieldExpression(node); + case 240 /* JsxExpression */: + return checkJsxExpression(node); + case 233 /* JsxElement */: + return checkJsxElement(node); + case 234 /* JsxSelfClosingElement */: + return checkJsxSelfClosingElement(node); + case 235 /* JsxOpeningElement */: + ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); + } + return unknownType; + } + // DECLARATION AND STATEMENT TYPE CHECKING + function checkTypeParameter(node) { + // Grammar Checking + if (node.expression) { + grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); + } + checkSourceElement(node.constraint); + if (produceDiagnostics) { + checkTypeParameterHasIllegalReferencesInConstraint(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); + } + // TODO: Check multiple declarations are identical + } + function checkParameter(node) { + // Grammar checking + // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the + // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code + // or if its FunctionBody is strict code(11.1.5). + // Grammar checking + checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkVariableLikeDeclaration(node); + var func = ts.getContainingFunction(node); + if (node.flags & 112 /* AccessibilityModifier */) { + func = ts.getContainingFunction(node); + if (!(func.kind === 144 /* Constructor */ && ts.nodeIsPresent(func.body))) { + error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); + } + } + if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); + } + // Only check rest parameter type if it's not a binding pattern. Since binding patterns are + // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isArrayType(getTypeOfSymbol(node.symbol))) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); + } + } + function isSyntacticallyValidGenerator(node) { + if (!node.asteriskToken || !node.body) { + return false; + } + return node.kind === 143 /* MethodDeclaration */ || + node.kind === 213 /* FunctionDeclaration */ || + node.kind === 173 /* FunctionExpression */; + } + function getTypePredicateParameterIndex(parameterList, parameter) { + if (parameterList) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 69 /* Identifier */ && + param.name.text === parameter.text) { + return i; + } + } + } + return -1; + } + function isInLegalTypePredicatePosition(node) { + switch (node.parent.kind) { + case 174 /* ArrowFunction */: + case 147 /* CallSignature */: + case 213 /* FunctionDeclaration */: + case 173 /* FunctionExpression */: + case 152 /* FunctionType */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + return node === node.parent.type; + } + return false; + } + function checkSignatureDeclaration(node) { + // Grammar checking + if (node.kind === 149 /* IndexSignature */) { + checkGrammarIndexSignature(node); + } + else if (node.kind === 152 /* FunctionType */ || node.kind === 213 /* FunctionDeclaration */ || node.kind === 153 /* ConstructorType */ || + node.kind === 147 /* CallSignature */ || node.kind === 144 /* Constructor */ || + node.kind === 148 /* ConstructSignature */) { + checkGrammarFunctionLikeDeclaration(node); + } + checkTypeParameters(node.typeParameters); + ts.forEach(node.parameters, checkParameter); + if (node.type) { + if (node.type.kind === 150 /* TypePredicate */) { + var typePredicate = getSignatureFromDeclaration(node).typePredicate; + var typePredicateNode = node.type; + if (isInLegalTypePredicatePosition(typePredicateNode)) { + if (typePredicate.parameterIndex >= 0) { + if (node.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(typePredicateNode.parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(node.parameters[typePredicate.parameterIndex]), typePredicateNode.type); + } + } + else if (typePredicateNode.parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (hasReportedError) { + break; + } + if (param.name.kind === 161 /* ObjectBindingPattern */ || + param.name.kind === 162 /* ArrayBindingPattern */) { + (function checkBindingPattern(pattern) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.name.kind === 69 /* Identifier */ && + element.name.text === typePredicate.parameterName) { + error(typePredicateNode.parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, typePredicate.parameterName); + hasReportedError = true; + break; + } + else if (element.name.kind === 162 /* ArrayBindingPattern */ || + element.name.kind === 161 /* ObjectBindingPattern */) { + checkBindingPattern(element.name); + } + } + })(param.name); + } + } + if (!hasReportedError) { + error(typePredicateNode.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + else { + error(typePredicateNode, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + } + } + else { + checkSourceElement(node.type); + } + } + if (produceDiagnostics) { + checkCollisionWithArgumentsInGeneratedCode(node); + if (compilerOptions.noImplicitAny && !node.type) { + switch (node.kind) { + case 148 /* ConstructSignature */: + error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + case 147 /* CallSignature */: + error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + } + } + if (node.type) { + if (languageVersion >= 2 /* ES6 */ && isSyntacticallyValidGenerator(node)) { + var returnType = getTypeFromTypeNode(node.type); + if (returnType === voidType) { + error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); + } + else { + var generatorElementType = getElementTypeOfIterableIterator(returnType) || anyType; + var iterableIteratorInstantiation = createIterableIteratorType(generatorElementType); + // Naively, one could check that IterableIterator is assignable to the return type annotation. + // However, that would not catch the error in the following case. + // + // interface BadGenerator extends Iterable, Iterator { } + // function* g(): BadGenerator { } // Iterable and Iterator have different types! + // + checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); + } + } + } + } + checkSpecializedSignatureDeclaration(node); + } + function checkTypeForDuplicateIndexSignatures(node) { + if (node.kind === 215 /* InterfaceDeclaration */) { + var nodeSymbol = getSymbolOfNode(node); + // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration + // to prevent this run check only for the first declaration of a given kind + if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + return; + } + } + // TypeScript 1.0 spec (April 2014) + // 3.7.4: An object type can contain at most one string index signature and one numeric index signature. + // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration + var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); + if (indexSymbol) { + var seenNumericIndexer = false; + var seenStringIndexer = false; + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var declaration = decl; + if (declaration.parameters.length === 1 && declaration.parameters[0].type) { + switch (declaration.parameters[0].type.kind) { + case 130 /* StringKeyword */: + if (!seenStringIndexer) { + seenStringIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_string_index_signature); + } + break; + case 128 /* NumberKeyword */: + if (!seenNumericIndexer) { + seenNumericIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_number_index_signature); + } + break; + } + } + } + } + } + function checkPropertyDeclaration(node) { + // Grammar checking + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarProperty(node) || checkGrammarComputedPropertyName(node.name); + checkVariableLikeDeclaration(node); + } + function checkMethodDeclaration(node) { + // Grammar checking + checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); + // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration + checkFunctionLikeDeclaration(node); + // Abstract methods cannot have an implementation. + // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. + if (node.flags & 256 /* Abstract */ && node.body) { + error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); + } + } + function checkConstructorDeclaration(node) { + // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. + checkSignatureDeclaration(node); + // Grammar check for checking only related to constructoDeclaration + checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); + checkSourceElement(node.body); + var symbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); + // Only type check the symbol once + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(symbol); + } + // exit early in the case of signature - super checks are not relevant to them + if (ts.nodeIsMissing(node.body)) { + return; + } + if (!produceDiagnostics) { + return; + } + function isSuperCallExpression(n) { + return n.kind === 168 /* CallExpression */ && n.expression.kind === 95 /* SuperKeyword */; + } + function containsSuperCallAsComputedPropertyName(n) { + return n.name && containsSuperCall(n.name); + } + function containsSuperCall(n) { + if (isSuperCallExpression(n)) { + return true; + } + else if (ts.isFunctionLike(n)) { + return false; + } + else if (ts.isClassLike(n)) { + return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); + } + return ts.forEachChild(n, containsSuperCall); + } + function markThisReferencesAsErrors(n) { + if (n.kind === 97 /* ThisKeyword */) { + error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + } + else if (n.kind !== 173 /* FunctionExpression */ && n.kind !== 213 /* FunctionDeclaration */) { + ts.forEachChild(n, markThisReferencesAsErrors); + } + } + function isInstancePropertyWithInitializer(n) { + return n.kind === 141 /* PropertyDeclaration */ && + !(n.flags & 128 /* Static */) && + !!n.initializer; + } + // TS 1.0 spec (April 2014): 8.3.2 + // Constructors of classes with no extends clause may not contain super calls, whereas + // constructors of derived classes must contain at least one super call somewhere in their function body. + var containingClassDecl = node.parent; + if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + var containingClassSymbol = getSymbolOfNode(containingClassDecl); + var containingClassInstanceType = getDeclaredTypeOfSymbol(containingClassSymbol); + var baseConstructorType = getBaseConstructorTypeOfClass(containingClassInstanceType); + if (containsSuperCall(node.body)) { + if (baseConstructorType === nullType) { + error(node, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + } + // The first statement in the body of a constructor (excluding prologue directives) must be a super call + // if both of the following are true: + // - The containing class is a derived class. + // - The constructor declares parameter properties + // or the containing class declares instance member variables with initializers. + var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || + ts.forEach(node.parameters, function (p) { return p.flags & (16 /* Public */ | 32 /* Private */ | 64 /* Protected */); }); + // Skip past any prologue directives to find the first statement + // to ensure that it was a super call. + if (superCallShouldBeFirst) { + var statements = node.body.statements; + var superCallStatement; + for (var _i = 0; _i < statements.length; _i++) { + var statement = statements[_i]; + if (statement.kind === 195 /* ExpressionStatement */ && isSuperCallExpression(statement.expression)) { + superCallStatement = statement; + break; + } + if (!ts.isPrologueDirective(statement)) { + break; + } + } + if (!superCallStatement) { + error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); + } + else { + // In such a required super call, it is a compile-time error for argument expressions to reference this. + markThisReferencesAsErrors(superCallStatement.expression); + } + } + } + else if (baseConstructorType !== nullType) { + error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); + } + } + } + function checkAccessorDeclaration(node) { + if (produceDiagnostics) { + // Grammar checking accessors + checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); + if (node.kind === 145 /* GetAccessor */) { + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && !(bodyContainsAReturnStatement(node.body) || bodyContainsSingleThrowStatement(node.body))) { + error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement); + } + } + if (!ts.hasDynamicName(node)) { + // TypeScript 1.0 spec (April 2014): 8.4.3 + // Accessors for the same member name must specify the same accessibility. + var otherKind = node.kind === 145 /* GetAccessor */ ? 146 /* SetAccessor */ : 145 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); + if (otherAccessor) { + if (((node.flags & 112 /* AccessibilityModifier */) !== (otherAccessor.flags & 112 /* AccessibilityModifier */))) { + error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + } + var currentAccessorType = getAnnotatedAccessorType(node); + var otherAccessorType = getAnnotatedAccessorType(otherAccessor); + // TypeScript 1.0 spec (April 2014): 4.5 + // If both accessors include type annotations, the specified types must be identical. + if (currentAccessorType && otherAccessorType) { + if (!isTypeIdenticalTo(currentAccessorType, otherAccessorType)) { + error(node, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); + } + } + } + } + getTypeOfAccessors(getSymbolOfNode(node)); + } + checkFunctionLikeDeclaration(node); + } + function checkMissingDeclaration(node) { + checkDecorators(node); + } + function checkTypeArgumentConstraints(typeParameters, typeArguments) { + var result = true; + for (var i = 0; i < typeParameters.length; i++) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + var typeArgument = typeArguments[i]; + result = result && checkTypeAssignableTo(getTypeFromTypeNode(typeArgument), constraint, typeArgument, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + } + return result; + } + function checkTypeReferenceNode(node) { + checkGrammarTypeArguments(node, node.typeArguments); + var type = getTypeFromTypeReference(node); + if (type !== unknownType && node.typeArguments) { + // Do type argument local checks only if referenced type is successfully resolved + ts.forEach(node.typeArguments, checkSourceElement); + if (produceDiagnostics) { + var symbol = getNodeLinks(node).resolvedSymbol; + var typeParameters = symbol.flags & 524288 /* TypeAlias */ ? getSymbolLinks(symbol).typeParameters : type.target.localTypeParameters; + checkTypeArgumentConstraints(typeParameters, node.typeArguments); + } + } + } + function checkTypeQuery(node) { + getTypeFromTypeQueryNode(node); + } + function checkTypeLiteral(node) { + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + } + } + function checkArrayType(node) { + checkSourceElement(node.elementType); + } + function checkTupleType(node) { + // Grammar checking + var hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); + if (!hasErrorFromDisallowedTrailingComma && node.elementTypes.length === 0) { + grammarErrorOnNode(node, ts.Diagnostics.A_tuple_type_element_list_cannot_be_empty); + } + ts.forEach(node.elementTypes, checkSourceElement); + } + function checkUnionOrIntersectionType(node) { + ts.forEach(node.types, checkSourceElement); + } + function isPrivateWithinAmbient(node) { + return (node.flags & 32 /* Private */) && ts.isInAmbientContext(node); + } + function checkSpecializedSignatureDeclaration(signatureDeclarationNode) { + if (!produceDiagnostics) { + return; + } + var signature = getSignatureFromDeclaration(signatureDeclarationNode); + if (!signature.hasStringLiterals) { + return; + } + // TypeScript 1.0 spec (April 2014): 3.7.2.2 + // Specialized signatures are not permitted in conjunction with a function body + if (ts.nodeIsPresent(signatureDeclarationNode.body)) { + error(signatureDeclarationNode, ts.Diagnostics.A_signature_with_an_implementation_cannot_use_a_string_literal_type); + return; + } + // TypeScript 1.0 spec (April 2014): 3.7.2.4 + // Every specialized call or construct signature in an object type must be assignable + // to at least one non-specialized call or construct signature in the same object type + var signaturesToCheck; + // Unnamed (call\construct) signatures in interfaces are inherited and not shadowed so examining just node symbol won't give complete answer. + // Use declaring type to obtain full list of signatures. + if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 215 /* InterfaceDeclaration */) { + ts.Debug.assert(signatureDeclarationNode.kind === 147 /* CallSignature */ || signatureDeclarationNode.kind === 148 /* ConstructSignature */); + var signatureKind = signatureDeclarationNode.kind === 147 /* CallSignature */ ? 0 /* Call */ : 1 /* Construct */; + var containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); + var containingType = getDeclaredTypeOfSymbol(containingSymbol); + signaturesToCheck = getSignaturesOfType(containingType, signatureKind); + } + else { + signaturesToCheck = getSignaturesOfSymbol(getSymbolOfNode(signatureDeclarationNode)); + } + for (var _i = 0; _i < signaturesToCheck.length; _i++) { + var otherSignature = signaturesToCheck[_i]; + if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature)) { + return; + } + } + error(signatureDeclarationNode, ts.Diagnostics.Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature); + } + function getEffectiveDeclarationFlags(n, flagsToCheck) { + var flags = ts.getCombinedNodeFlags(n); + // children of classes (even ambient classes) should not be marked as ambient or export + // because those flags have no useful semantics there. + if (n.parent.kind !== 215 /* InterfaceDeclaration */ && + n.parent.kind !== 214 /* ClassDeclaration */ && + n.parent.kind !== 186 /* ClassExpression */ && + ts.isInAmbientContext(n)) { + if (!(flags & 2 /* Ambient */)) { + // It is nested in an ambient context, which means it is automatically exported + flags |= 1 /* Export */; + } + flags |= 2 /* Ambient */; + } + return flags & flagsToCheck; + } + function checkFunctionOrConstructorSymbol(symbol) { + if (!produceDiagnostics) { + return; + } + function getCanonicalOverload(overloads, implementation) { + // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration + // Error on all deviations from this canonical set of flags + // The caveat is that if some overloads are defined in lib.d.ts, we don't want to + // report the errors on those. To achieve this, we will say that the implementation is + // the canonical signature only if it is in the same container as the first overload + var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; + return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; + } + function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { + // Error if some overloads have a flag that is not shared by all overloads. To find the + // deviations, we XOR someOverloadFlags with allOverloadFlags + var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; + if (someButNotAllOverloadFlags !== 0) { + var canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); + ts.forEach(overloads, function (o) { + var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; + if (deviation & 1 /* Export */) { + error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_not_exported); + } + else if (deviation & 2 /* Ambient */) { + error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + } + else if (deviation & (32 /* Private */ | 64 /* Protected */)) { + error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + } + else if (deviation & 256 /* Abstract */) { + error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_not_abstract); + } + }); + } + } + function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { + if (someHaveQuestionToken !== allHaveQuestionToken) { + var canonicalHasQuestionToken = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); + ts.forEach(overloads, function (o) { + var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken; + if (deviation) { + error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + } + }); + } + } + var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 32 /* Private */ | 64 /* Protected */ | 256 /* Abstract */; + var someNodeFlags = 0; + var allNodeFlags = flagsToCheck; + var someHaveQuestionToken = false; + var allHaveQuestionToken = true; + var hasOverloads = false; + var bodyDeclaration; + var lastSeenNonAmbientDeclaration; + var previousDeclaration; + var declarations = symbol.declarations; + var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0; + function reportImplementationExpectedError(node) { + if (node.name && ts.nodeIsMissing(node.name)) { + return; + } + var seen = false; + var subsequentNode = ts.forEachChild(node.parent, function (c) { + if (seen) { + return c; + } + else { + seen = c === node; + } + }); + if (subsequentNode) { + if (subsequentNode.kind === node.kind) { + var errorNode_1 = subsequentNode.name || subsequentNode; + // TODO(jfreeman): These are methods, so handle computed name case + if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { + var reportError = (node.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */) && + (node.flags & 128 /* Static */) !== (subsequentNode.flags & 128 /* Static */); + // we can get here in two cases + // 1. mixed static and instance class members + // 2. something with the same name was defined before the set of overloads that prevents them from merging + // here we'll report error only for the first case since for second we should already report error in binder + if (reportError) { + var diagnostic = node.flags & 128 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } + return; + } + else if (ts.nodeIsPresent(subsequentNode.body)) { + error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name)); + return; + } + } + } + var errorNode = node.name || node; + if (isConstructor) { + error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); + } + else { + // Report different errors regarding non-consecutive blocks of declarations depending on whether + // the node in question is abstract. + if (node.flags & 256 /* Abstract */) { + error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); + } + else { + error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); + } + } + } + // when checking exported function declarations across modules check only duplicate implementations + // names and consistency of modifiers are verified when we check local symbol + var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & 1536 /* Module */; + var duplicateFunctionDeclaration = false; + var multipleConstructorImplementation = false; + for (var _i = 0; _i < declarations.length; _i++) { + var current = declarations[_i]; + var node = current; + var inAmbientContext = ts.isInAmbientContext(node); + var inAmbientContextOrInterface = node.parent.kind === 215 /* InterfaceDeclaration */ || node.parent.kind === 155 /* TypeLiteral */ || inAmbientContext; + if (inAmbientContextOrInterface) { + // check if declarations are consecutive only if they are non-ambient + // 1. ambient declarations can be interleaved + // i.e. this is legal + // declare function foo(); + // declare function bar(); + // declare function foo(); + // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one + previousDeclaration = undefined; + } + if (node.kind === 213 /* FunctionDeclaration */ || node.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */ || node.kind === 144 /* Constructor */) { + var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); + if (ts.nodeIsPresent(node.body) && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } + else { + duplicateFunctionDeclaration = true; + } + } + else if (!isExportSymbolInsideModule && previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (ts.nodeIsPresent(node.body)) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } + } + else { + hasOverloads = true; + } + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; + } + } + } + if (multipleConstructorImplementation) { + ts.forEach(declarations, function (declaration) { + error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); + }); + } + if (duplicateFunctionDeclaration) { + ts.forEach(declarations, function (declaration) { + error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + }); + } + // Abstract methods can't have an implementation -- in particular, they don't need one. + if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + !(lastSeenNonAmbientDeclaration.flags & 256 /* Abstract */)) { + reportImplementationExpectedError(lastSeenNonAmbientDeclaration); + } + if (hasOverloads) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + if (bodyDeclaration) { + var signatures = getSignaturesOfSymbol(symbol); + var bodySignature = getSignatureFromDeclaration(bodyDeclaration); + // If the implementation signature has string literals, we will have reported an error in + // checkSpecializedSignatureDeclaration + if (!bodySignature.hasStringLiterals) { + // TypeScript 1.0 spec (April 2014): 6.1 + // If a function declaration includes overloads, the overloads determine the call + // signatures of the type given to the function object + // and the function implementation signature must be assignable to that type + // + // TypeScript 1.0 spec (April 2014): 3.8.4 + // Note that specialized call and construct signatures (section 3.7.2.4) are not significant when determining assignment compatibility + // Consider checking against specialized signatures too. Not doing so creates a type hole: + // + // function g(x: "hi", y: boolean); + // function g(x: string, y: {}); + // function g(x: string, y: string) { } + // + // The implementation is completely unrelated to the specialized signature, yet we do not check this. + for (var _a = 0; _a < signatures.length; _a++) { + var signature = signatures[_a]; + if (!signature.hasStringLiterals && !isSignatureAssignableTo(bodySignature, signature)) { + error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); + break; + } + } + } + } + } + } + function checkExportsOnMergedDeclarations(node) { + if (!produceDiagnostics) { + return; + } + // if localSymbol is defined on node then node itself is exported - check is required + var symbol = node.localSymbol; + if (!symbol) { + // local symbol is undefined => this declaration is non-exported. + // however symbol might contain other declarations that are exported + symbol = getSymbolOfNode(node); + if (!(symbol.flags & 7340032 /* Export */)) { + // this is a pure local symbol (all declarations are non-exported) - no need to check anything + return; + } + } + // run the check only for the first declaration in the list + if (ts.getDeclarationOfKind(symbol, node.kind) !== node) { + return; + } + // we use SymbolFlags.ExportValue, SymbolFlags.ExportType and SymbolFlags.ExportNamespace + // to denote disjoint declarationSpaces (without making new enum type). + var exportedDeclarationSpaces = 0 /* None */; + var nonExportedDeclarationSpaces = 0 /* None */; + var defaultExportedDeclarationSpaces = 0 /* None */; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var d = _a[_i]; + var declarationSpaces = getDeclarationSpaces(d); + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 1024 /* Default */); + if (effectiveDeclarationFlags & 1 /* Export */) { + if (effectiveDeclarationFlags & 1024 /* Default */) { + defaultExportedDeclarationSpaces |= declarationSpaces; + } + else { + exportedDeclarationSpaces |= declarationSpaces; + } + } + else { + nonExportedDeclarationSpaces |= declarationSpaces; + } + } + // Spaces for anyting not declared a 'default export'. + var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; + var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; + var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; + if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { + // declaration spaces for exported and non-exported declarations intersect + for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declarationSpaces = getDeclarationSpaces(d); + // Only error on the declarations that conributed to the intersecting spaces. + if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { + error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + } + else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { + error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + } + } + } + function getDeclarationSpaces(d) { + switch (d.kind) { + case 215 /* InterfaceDeclaration */: + return 2097152 /* ExportType */; + case 218 /* ModuleDeclaration */: + return d.name.kind === 9 /* StringLiteral */ || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ + ? 4194304 /* ExportNamespace */ | 1048576 /* ExportValue */ + : 4194304 /* ExportNamespace */; + case 214 /* ClassDeclaration */: + case 217 /* EnumDeclaration */: + return 2097152 /* ExportType */ | 1048576 /* ExportValue */; + case 221 /* ImportEqualsDeclaration */: + var result = 0; + var target = resolveAlias(getSymbolOfNode(d)); + ts.forEach(target.declarations, function (d) { result |= getDeclarationSpaces(d); }); + return result; + default: + return 1048576 /* ExportValue */; + } + } + } + function checkNonThenableType(type, location, message) { + type = getWidenedType(type); + if (!isTypeAny(type) && isTypeAssignableTo(type, getGlobalThenableType())) { + if (location) { + if (!message) { + message = ts.Diagnostics.Operand_for_await_does_not_have_a_valid_callable_then_member; + } + error(location, message); + } + return unknownType; + } + return type; + } + /** + * Gets the "promised type" of a promise. + * @param type The type of the promise. + * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback. + */ + function getPromisedType(promise) { + // + // { // promise + // then( // thenFunction + // onfulfilled: ( // onfulfilledParameterType + // value: T // valueParameterType + // ) => any + // ): any; + // } + // + if (promise.flags & 1 /* Any */) { + return undefined; + } + if ((promise.flags & 4096 /* Reference */) && promise.target === tryGetGlobalPromiseType()) { + return promise.typeArguments[0]; + } + var globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType(); + if (globalPromiseLikeType === emptyObjectType || !isTypeAssignableTo(promise, globalPromiseLikeType)) { + return undefined; + } + var thenFunction = getTypeOfPropertyOfType(promise, "then"); + if (thenFunction && (thenFunction.flags & 1 /* Any */)) { + return undefined; + } + var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : emptyArray; + if (thenSignatures.length === 0) { + return undefined; + } + var onfulfilledParameterType = getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)); + if (onfulfilledParameterType.flags & 1 /* Any */) { + return undefined; + } + var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */); + if (onfulfilledParameterSignatures.length === 0) { + return undefined; + } + var valueParameterType = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); + return valueParameterType; + } + function getTypeOfFirstParameterOfSignature(signature) { + return getTypeAtPosition(signature, 0); + } + /** + * Gets the "awaited type" of a type. + * @param type The type to await. + * @remarks The "awaited type" of an expression is its "promised type" if the expression is a + * Promise-like type; otherwise, it is the type of the expression. This is used to reflect + * The runtime behavior of the `await` keyword. + */ + function getAwaitedType(type) { + return checkAwaitedType(type, /*location*/ undefined, /*message*/ undefined); + } + function checkAwaitedType(type, location, message) { + return checkAwaitedTypeWorker(type); + function checkAwaitedTypeWorker(type) { + if (type.flags & 16384 /* Union */) { + var types = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var constituentType = _a[_i]; + types.push(checkAwaitedTypeWorker(constituentType)); + } + return getUnionType(types); + } + else { + var promisedType = getPromisedType(type); + if (promisedType === undefined) { + // The type was not a PromiseLike, so it could not be unwrapped any further. + // As long as the type does not have a callable "then" property, it is + // safe to return the type; otherwise, an error will have been reported in + // the call to checkNonThenableType and we will return unknownType. + // + // An example of a non-promise "thenable" might be: + // + // await { then(): void {} } + // + // The "thenable" does not match the minimal definition for a PromiseLike. When + // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise + // will never settle. We treat this as an error to help flag an early indicator + // of a runtime problem. If the user wants to return this value from an async + // function, they would need to wrap it in some other value. If they want it to + // be treated as a promise, they can cast to . + return checkNonThenableType(type, location, message); + } + else { + if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { + // We have a bad actor in the form of a promise whose promised type is + // the same promise type, or a mutually recursive promise. Return the + // unknown type as we cannot guess the shape. If this were the actual + // case in the JavaScript, this Promise would never resolve. + // + // An example of a bad actor with a singly-recursive promise type might + // be: + // + // interface BadPromise { + // then( + // onfulfilled: (value: BadPromise) => any, + // onrejected: (error: any) => any): BadPromise; + // } + // + // The above interface will pass the PromiseLike check, and return a + // promised type of `BadPromise`. Since this is a self reference, we + // don't want to keep recursing ad infinitum. + // + // An example of a bad actor in the form of a mutually-recursive + // promise type might be: + // + // interface BadPromiseA { + // then( + // onfulfilled: (value: BadPromiseB) => any, + // onrejected: (error: any) => any): BadPromiseB; + // } + // + // interface BadPromiseB { + // then( + // onfulfilled: (value: BadPromiseA) => any, + // onrejected: (error: any) => any): BadPromiseA; + // } + // + if (location) { + error(location, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method, symbolToString(type.symbol)); + } + return unknownType; + } + // Keep track of the type we're about to unwrap to avoid bad recursive promise types. + // See the comments above for more information. + awaitedTypeStack.push(type.id); + var awaitedType = checkAwaitedTypeWorker(promisedType); + awaitedTypeStack.pop(); + return awaitedType; + } + } + } + } + /** + * Checks the return type of an async function to ensure it is a compatible + * Promise implementation. + * @param node The signature to check + * @param returnType The return type for the function + * @remarks + * This checks that an async function has a valid Promise-compatible return type, + * and returns the *awaited type* of the promise. An async function has a valid + * Promise-compatible return type if the resolved value of the return type has a + * construct signature that takes in an `initializer` function that in turn supplies + * a `resolve` function as one of its arguments and results in an object with a + * callable `then` signature. + */ + function checkAsyncFunctionReturnType(node) { + var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); + if (globalPromiseConstructorLikeType === emptyObjectType) { + // If we couldn't resolve the global PromiseConstructorLike type we cannot verify + // compatibility with __awaiter. + return unknownType; + } + // As part of our emit for an async function, we will need to emit the entity name of + // the return type annotation as an expression. To meet the necessary runtime semantics + // for __awaiter, we must also check that the type of the declaration (e.g. the static + // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`. + // + // An example might be (from lib.es6.d.ts): + // + // interface Promise { ... } + // interface PromiseConstructor { + // new (...): Promise; + // } + // declare var Promise: PromiseConstructor; + // + // When an async function declares a return type annotation of `Promise`, we + // need to get the type of the `Promise` variable declaration above, which would + // be `PromiseConstructor`. + // + // The same case applies to a class: + // + // declare class Promise { + // constructor(...); + // then(...): Promise; + // } + // + // When we get the type of the `Promise` symbol here, we get the type of the static + // side of the `Promise` class, which would be `{ new (...): Promise }`. + var promiseType = getTypeFromTypeNode(node.type); + if (promiseType === unknownType && compilerOptions.isolatedModules) { + // If we are compiling with isolatedModules, we may not be able to resolve the + // type as a value. As such, we will just return unknownType; + return unknownType; + } + var promiseConstructor = getNodeLinks(node.type).resolvedSymbol; + if (!promiseConstructor || !symbolIsValue(promiseConstructor)) { + var typeName = promiseConstructor + ? symbolToString(promiseConstructor) + : typeToString(promiseType); + error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); + return unknownType; + } + // Validate the promise constructor type. + var promiseConstructorType = getTypeOfSymbol(promiseConstructor); + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { + return unknownType; + } + // Verify there is no local declaration that could collide with the promise constructor. + var promiseName = ts.getEntityNameFromTypeNode(node.type); + var root = getFirstIdentifier(promiseName); + var rootSymbol = getSymbol(node.locals, root.text, 107455 /* Value */); + if (rootSymbol) { + error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, root.text, getFullyQualifiedName(promiseConstructor)); + return unknownType; + } + // Get and return the awaited type of the return type. + return checkAwaitedType(promiseType, node, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + } + /** Check a decorator */ + function checkDecorator(node) { + var signature = getResolvedSignature(node); + var returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 1 /* Any */) { + return; + } + var expectedReturnType; + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + var errorInfo; + switch (node.parent.kind) { + case 214 /* ClassDeclaration */: + var classSymbol = getSymbolOfNode(node.parent); + var classConstructorType = getTypeOfSymbol(classSymbol); + expectedReturnType = getUnionType([classConstructorType, voidType]); + break; + case 138 /* Parameter */: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + break; + case 141 /* PropertyDeclaration */: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); + break; + case 143 /* MethodDeclaration */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + var methodType = getTypeOfNode(node.parent); + var descriptorType = createTypedPropertyDescriptorType(methodType); + expectedReturnType = getUnionType([descriptorType, voidType]); + break; + } + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); + } + /** Checks a type reference node as an expression. */ + function checkTypeNodeAsExpression(node) { + // When we are emitting type metadata for decorators, we need to try to check the type + // as if it were an expression so that we can emit the type in a value position when we + // serialize the type metadata. + if (node && node.kind === 151 /* TypeReference */) { + var root = getFirstIdentifier(node.typeName); + var meaning = root.parent.kind === 151 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */; + // Resolve type so we know which symbol is referenced + var rootSymbol = resolveName(root, root.text, meaning | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + // Resolved symbol is alias + if (rootSymbol && rootSymbol.flags & 8388608 /* Alias */) { + var aliasTarget = resolveAlias(rootSymbol); + // If alias has value symbol - mark alias as referenced + if (aliasTarget.flags & 107455 /* Value */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { + markAliasSymbolAsReferenced(rootSymbol); + } + } + } + } + /** + * Checks the type annotation of an accessor declaration or property declaration as + * an expression if it is a type reference to a type with a value declaration. + */ + function checkTypeAnnotationAsExpression(node) { + switch (node.kind) { + case 141 /* PropertyDeclaration */: + checkTypeNodeAsExpression(node.type); + break; + case 138 /* Parameter */: + checkTypeNodeAsExpression(node.type); + break; + case 143 /* MethodDeclaration */: + checkTypeNodeAsExpression(node.type); + break; + case 145 /* GetAccessor */: + checkTypeNodeAsExpression(node.type); + break; + case 146 /* SetAccessor */: + checkTypeNodeAsExpression(ts.getSetAccessorTypeAnnotationNode(node)); + break; + } + } + /** Checks the type annotation of the parameters of a function/method or the constructor of a class as expressions */ + function checkParameterTypeAnnotationsAsExpressions(node) { + // ensure all type annotations with a value declaration are checked as an expression + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + checkTypeAnnotationAsExpression(parameter); + } + } + /** Check the decorators of a node */ + function checkDecorators(node) { + if (!node.decorators) { + return; + } + // skip this check for nodes that cannot have decorators. These should have already had an error reported by + // checkGrammarDecorators. + if (!ts.nodeCanBeDecorated(node)) { + return; + } + if (!compilerOptions.experimentalDecorators) { + error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Specify_experimentalDecorators_to_remove_this_warning); + } + if (compilerOptions.emitDecoratorMetadata) { + // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. + switch (node.kind) { + case 214 /* ClassDeclaration */: + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + checkParameterTypeAnnotationsAsExpressions(constructor); + } + break; + case 143 /* MethodDeclaration */: + checkParameterTypeAnnotationsAsExpressions(node); + // fall-through + case 146 /* SetAccessor */: + case 145 /* GetAccessor */: + case 141 /* PropertyDeclaration */: + case 138 /* Parameter */: + checkTypeAnnotationAsExpression(node); + break; + } + } + emitDecorate = true; + if (node.kind === 138 /* Parameter */) { + emitParam = true; + } + ts.forEach(node.decorators, checkDecorator); + } + function checkFunctionDeclaration(node) { + if (produceDiagnostics) { + checkFunctionLikeDeclaration(node) || checkGrammarForGenerator(node); + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + } + } + function checkFunctionLikeDeclaration(node) { + checkDecorators(node); + checkSignatureDeclaration(node); + var isAsync = ts.isAsyncFunctionLike(node); + if (isAsync) { + emitAwaiter = true; + } + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name && node.name.kind === 136 /* ComputedPropertyName */) { + // This check will account for methods in class/interface declarations, + // as well as accessors in classes/object literals + checkComputedPropertyName(node.name); + } + if (!ts.hasDynamicName(node)) { + // first we want to check the local symbol that contain this declaration + // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol + // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode + var symbol = getSymbolOfNode(node); + var localSymbol = node.localSymbol || symbol; + var firstDeclaration = ts.getDeclarationOfKind(localSymbol, node.kind); + // Only type check the symbol once + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(localSymbol); + } + if (symbol.parent) { + // run check once for the first declaration + if (ts.getDeclarationOfKind(symbol, node.kind) === node) { + // run check on export symbol to check that modifiers agree across all exported declarations + checkFunctionOrConstructorSymbol(symbol); + } + } + } + checkSourceElement(node.body); + if (node.type && !isAccessor(node.kind) && !node.asteriskToken) { + var returnType = getTypeFromTypeNode(node.type); + var promisedType; + if (isAsync) { + promisedType = checkAsyncFunctionReturnType(node); + } + checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, isAsync ? promisedType : returnType); + } + if (produceDiagnostics && !node.type) { + // Report an implicit any error if there is no body, no explicit return type, and node is not a private method + // in an ambient context + if (compilerOptions.noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { + reportImplicitAnyError(node, anyType); + } + if (node.asteriskToken && ts.nodeIsPresent(node.body)) { + // A generator with a body and no type annotation can still cause errors. It can error if the + // yielded values have no common supertype, or it can give an implicit any error if it has no + // yielded values. The only way to trigger these errors is to try checking its return type. + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + } + } + function checkBlock(node) { + // Grammar checking for SyntaxKind.Block + if (node.kind === 192 /* Block */) { + checkGrammarStatementInAmbientContext(node); + } + ts.forEach(node.statements, checkSourceElement); + if (ts.isFunctionBlock(node) || node.kind === 219 /* ModuleBlock */) { + checkFunctionAndClassExpressionBodies(node); + } + } + function checkCollisionWithArgumentsInGeneratedCode(node) { + // no rest parameters \ declaration context \ overload - no codegen impact + if (!ts.hasRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + return; + } + ts.forEach(node.parameters, function (p) { + if (p.name && !ts.isBindingPattern(p.name) && p.name.text === argumentsSymbol.name) { + error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); + } + }); + } + function needCollisionCheckForIdentifier(node, identifier, name) { + if (!(identifier && identifier.text === name)) { + return false; + } + if (node.kind === 141 /* PropertyDeclaration */ || + node.kind === 140 /* PropertySignature */ || + node.kind === 143 /* MethodDeclaration */ || + node.kind === 142 /* MethodSignature */ || + node.kind === 145 /* GetAccessor */ || + node.kind === 146 /* SetAccessor */) { + // it is ok to have member named '_super' or '_this' - member access is always qualified + return false; + } + if (ts.isInAmbientContext(node)) { + // ambient context - no codegen impact + return false; + } + var root = ts.getRootDeclaration(node); + if (root.kind === 138 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + // just an overload - no codegen impact + return false; + } + return true; + } + function checkCollisionWithCapturedThisVariable(node, name) { + if (needCollisionCheckForIdentifier(node, name, "_this")) { + potentialThisCollisions.push(node); + } + } + // this function will run after checking the source file so 'CaptureThis' is correct for all nodes + function checkIfThisIsCapturedInEnclosingScope(node) { + var current = node; + while (current) { + if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { + var isDeclaration_1 = node.kind !== 69 /* Identifier */; + if (isDeclaration_1) { + error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); + } + return; + } + current = current.parent; + } + } + function checkCollisionWithCapturedSuperVariable(node, name) { + if (!needCollisionCheckForIdentifier(node, name, "_super")) { + return; + } + // bubble up and find containing type + var enclosingClass = ts.getContainingClass(node); + // if containing type was not found or it is ambient - exit (no codegen) + if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { + return; + } + if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { + var isDeclaration_2 = node.kind !== 69 /* Identifier */; + if (isDeclaration_2) { + error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference); + } + } + } + function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { + return; + } + // Uninstantiated modules shouldnt do this check + if (node.kind === 218 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return; + } + // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent + var parent = getDeclarationContainer(node); + if (parent.kind === 248 /* SourceFile */ && ts.isExternalModule(parent)) { + // If the declaration happens to be in external module, report error that require and exports are reserved keywords + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkVarDeclaredNamesNotShadowed(node) { + // - ScriptBody : StatementList + // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList + // also occurs in the VarDeclaredNames of StatementList. + // - Block : { StatementList } + // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList + // also occurs in the VarDeclaredNames of StatementList. + // Variable declarations are hoisted to the top of their function scope. They can shadow + // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition + // by the binder as the declaration scope is different. + // A non-initialized declaration is a no-op as the block declaration will resolve before the var + // declaration. the problem is if the declaration has an initializer. this will act as a write to the + // block declared value. this is fine for let, but not const. + // Only consider declarations with initializers, uninitialized let declarations will not + // step on a let/const variable. + // Do not consider let and const declarations, as duplicate block-scoped declarations + // are handled by the binder. + // We are only looking for let declarations that step on let\const declarations from a + // different scope. e.g.: + // { + // const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration + // let x = 0; // symbol for this declaration will be 'symbol' + // } + // skip block-scoped variables and parameters + if ((ts.getCombinedNodeFlags(node) & 49152 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { + return; + } + // skip variable declarations that don't have initializers + // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern + // so we'll always treat binding elements as initialized + if (node.kind === 211 /* VariableDeclaration */ && !node.initializer) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol.flags & 1 /* FunctionScopedVariable */) { + var localDeclarationSymbol = resolveName(node, node.name.text, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); + if (localDeclarationSymbol && + localDeclarationSymbol !== symbol && + localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { + if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 49152 /* BlockScoped */) { + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 212 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 193 /* VariableStatement */ && varDeclList.parent.parent + ? varDeclList.parent.parent + : undefined; + // names of block-scoped and function scoped variables can collide only + // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) + var namesShareScope = container && + (container.kind === 192 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 219 /* ModuleBlock */ || + container.kind === 218 /* ModuleDeclaration */ || + container.kind === 248 /* SourceFile */); + // here we know that function scoped variable is shadowed by block scoped one + // if they are defined in the same scope - binder has already reported redeclaration error + // otherwise if variable has an initializer - show error that initialization will fail + // since LHS will be block scoped name instead of function scoped + if (!namesShareScope) { + var name_14 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_14, name_14); + } + } + } + } + } + // Check that a parameter initializer contains no references to parameters declared to the right of itself + function checkParameterInitializer(node) { + if (ts.getRootDeclaration(node).kind !== 138 /* Parameter */) { + return; + } + var func = ts.getContainingFunction(node); + visit(node.initializer); + function visit(n) { + if (n.kind === 69 /* Identifier */) { + var referencedSymbol = getNodeLinks(n).resolvedSymbol; + // check FunctionLikeDeclaration.locals (stores parameters\function local variable) + // if it contains entry with a specified name and if this entry matches the resolved symbol + if (referencedSymbol && referencedSymbol !== unknownSymbol && getSymbol(func.locals, referencedSymbol.name, 107455 /* Value */) === referencedSymbol) { + if (referencedSymbol.valueDeclaration.kind === 138 /* Parameter */) { + if (referencedSymbol.valueDeclaration === node) { + error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); + return; + } + if (referencedSymbol.valueDeclaration.pos < node.pos) { + // legal case - parameter initializer references some parameter strictly on left of current parameter declaration + return; + } + } + error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); + } + } + else { + ts.forEachChild(n, visit); + } + } + } + // Check variable, parameter, or property declaration + function checkVariableLikeDeclaration(node) { + checkDecorators(node); + checkSourceElement(node.type); + // For a computed property, just check the initializer and exit + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 136 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + if (node.initializer) { + checkExpressionCached(node.initializer); + } + } + // For a binding pattern, check contained binding elements + if (ts.isBindingPattern(node.name)) { + ts.forEach(node.name.elements, checkSourceElement); + } + // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body + if (node.initializer && ts.getRootDeclaration(node).kind === 138 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); + return; + } + // For a binding pattern, validate the initializer and exit + if (ts.isBindingPattern(node.name)) { + if (node.initializer) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); + checkParameterInitializer(node); + } + return; + } + var symbol = getSymbolOfNode(node); + var type = getTypeOfVariableOrParameterOrProperty(symbol); + if (node === symbol.valueDeclaration) { + // Node is the primary declaration of the symbol, just validate the initializer + if (node.initializer) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined); + checkParameterInitializer(node); + } + } + else { + // Node is a secondary declaration, check that type is identical to primary declaration and check that + // initializer is consistent with type associated with the node + var declarationType = getWidenedTypeForVariableLikeDeclaration(node); + if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { + error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); + } + if (node.initializer) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); + } + } + if (node.kind !== 141 /* PropertyDeclaration */ && node.kind !== 140 /* PropertySignature */) { + // We know we don't have a binding pattern or computed name here + checkExportsOnMergedDeclarations(node); + if (node.kind === 211 /* VariableDeclaration */ || node.kind === 163 /* BindingElement */) { + checkVarDeclaredNamesNotShadowed(node); + } + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + } + } + function checkVariableDeclaration(node) { + checkGrammarVariableDeclaration(node); + return checkVariableLikeDeclaration(node); + } + function checkBindingElement(node) { + checkGrammarBindingElement(node); + return checkVariableLikeDeclaration(node); + } + function checkVariableStatement(node) { + // Grammar checking + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); + ts.forEach(node.declarationList.declarations, checkSourceElement); + } + function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { + // We only disallow modifier on a method declaration if it is a property of object-literal-expression + if (node.modifiers && node.parent.kind === 165 /* ObjectLiteralExpression */) { + if (ts.isAsyncFunctionLike(node)) { + if (node.modifiers.length > 1) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + } + } + function checkExpressionStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + } + function checkIfStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + checkSourceElement(node.thenStatement); + checkSourceElement(node.elseStatement); + } + function checkDoStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkSourceElement(node.statement); + checkExpression(node.expression); + } + function checkWhileStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + checkSourceElement(node.statement); + } + function checkForStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.initializer && node.initializer.kind === 212 /* VariableDeclarationList */) { + checkGrammarVariableDeclarationList(node.initializer); + } + } + if (node.initializer) { + if (node.initializer.kind === 212 /* VariableDeclarationList */) { + ts.forEach(node.initializer.declarations, checkVariableDeclaration); + } + else { + checkExpression(node.initializer); + } + } + if (node.condition) + checkExpression(node.condition); + if (node.incrementor) + checkExpression(node.incrementor); + checkSourceElement(node.statement); + } + function checkForOfStatement(node) { + checkGrammarForInOrForOfStatement(node); + // Check the LHS and RHS + // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS + // via checkRightHandSideOfForOf. + // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. + // Then check that the RHS is assignable to it. + if (node.initializer.kind === 212 /* VariableDeclarationList */) { + checkForInOrForOfVariableDeclaration(node); + } + else { + var varExpr = node.initializer; + var iteratedType = checkRightHandSideOfForOf(node.expression); + // There may be a destructuring assignment on the left side + if (varExpr.kind === 164 /* ArrayLiteralExpression */ || varExpr.kind === 165 /* ObjectLiteralExpression */) { + // iteratedType may be undefined. In this case, we still want to check the structure of + // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like + // to short circuit the type relation checking as much as possible, so we pass the unknownType. + checkDestructuringAssignment(varExpr, iteratedType || unknownType); + } + else { + var leftType = checkExpression(varExpr); + checkReferenceExpression(varExpr, /*invalidReferenceMessage*/ ts.Diagnostics.Invalid_left_hand_side_in_for_of_statement, + /*constantVariableMessage*/ ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_be_a_previously_defined_constant); + // iteratedType will be undefined if the rightType was missing properties/signatures + // required to get its iteratedType (like [Symbol.iterator] or next). This may be + // because we accessed properties from anyType, or it may have led to an error inside + // getElementTypeOfIterable. + if (iteratedType) { + checkTypeAssignableTo(iteratedType, leftType, varExpr, /*headMessage*/ undefined); + } + } + } + checkSourceElement(node.statement); + } + function checkForInStatement(node) { + // Grammar checking + checkGrammarForInOrForOfStatement(node); + // TypeScript 1.0 spec (April 2014): 5.4 + // In a 'for-in' statement of the form + // for (let VarDecl in Expr) Statement + // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, + // and Expr must be an expression of type Any, an object type, or a type parameter type. + if (node.initializer.kind === 212 /* VariableDeclarationList */) { + var variable = node.initializer.declarations[0]; + if (variable && ts.isBindingPattern(variable.name)) { + error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + checkForInOrForOfVariableDeclaration(node); + } + else { + // In a 'for-in' statement of the form + // for (Var in Expr) Statement + // Var must be an expression classified as a reference of type Any or the String primitive type, + // and Expr must be an expression of type Any, an object type, or a type parameter type. + var varExpr = node.initializer; + var leftType = checkExpression(varExpr); + if (varExpr.kind === 164 /* ArrayLiteralExpression */ || varExpr.kind === 165 /* ObjectLiteralExpression */) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + else if (!isTypeAnyOrAllConstituentTypesHaveKind(leftType, 258 /* StringLike */)) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); + } + else { + // run check only former check succeeded to avoid cascading errors + checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_in_statement, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_previously_defined_constant); + } + } + var rightType = checkExpression(node.expression); + // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved + // in this case error about missing name is already reported - do not report extra one + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 80896 /* ObjectType */ | 512 /* TypeParameter */)) { + error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + checkSourceElement(node.statement); + } + function checkForInOrForOfVariableDeclaration(iterationStatement) { + var variableDeclarationList = iterationStatement.initializer; + // checkGrammarForInOrForOfStatement will check that there is exactly one declaration. + if (variableDeclarationList.declarations.length >= 1) { + var decl = variableDeclarationList.declarations[0]; + checkVariableDeclaration(decl); + } + } + function checkRightHandSideOfForOf(rhsExpression) { + var expressionType = getTypeOfExpression(rhsExpression); + return checkIteratedTypeOrElementType(expressionType, rhsExpression, /*allowStringInput*/ true); + } + function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput) { + if (isTypeAny(inputType)) { + return inputType; + } + if (languageVersion >= 2 /* ES6 */) { + return checkElementTypeOfIterable(inputType, errorNode); + } + if (allowStringInput) { + return checkElementTypeOfArrayOrString(inputType, errorNode); + } + if (isArrayLikeType(inputType)) { + var indexType = getIndexTypeOfType(inputType, 1 /* Number */); + if (indexType) { + return indexType; + } + } + error(errorNode, ts.Diagnostics.Type_0_is_not_an_array_type, typeToString(inputType)); + return unknownType; + } + /** + * When errorNode is undefined, it means we should not report any errors. + */ + function checkElementTypeOfIterable(iterable, errorNode) { + var elementType = getElementTypeOfIterable(iterable, errorNode); + // Now even though we have extracted the iteratedType, we will have to validate that the type + // passed in is actually an Iterable. + if (errorNode && elementType) { + checkTypeAssignableTo(iterable, createIterableType(elementType), errorNode); + } + return elementType || anyType; + } + /** + * We want to treat type as an iterable, and get the type it is an iterable of. The iterable + * must have the following structure (annotated with the names of the variables below): + * + * { // iterable + * [Symbol.iterator]: { // iteratorFunction + * (): Iterator + * } + * } + * + * T is the type we are after. At every level that involves analyzing return types + * of signatures, we union the return types of all the signatures. + * + * Another thing to note is that at any step of this process, we could run into a dead end, + * meaning either the property is missing, or we run into the anyType. If either of these things + * happens, we return undefined to signal that we could not find the iterated type. If a property + * is missing, and the previous step did not result in 'any', then we also give an error if the + * caller requested it. Then the caller can decide what to do in the case where there is no iterated + * type. This is different from returning anyType, because that would signify that we have matched the + * whole pattern and that T (above) is 'any'. + */ + function getElementTypeOfIterable(type, errorNode) { + if (isTypeAny(type)) { + return undefined; + } + var typeAsIterable = type; + if (!typeAsIterable.iterableElementType) { + // As an optimization, if the type is instantiated directly using the globalIterableType (Iterable), + // then just grab its type argument. + if ((type.flags & 4096 /* Reference */) && type.target === globalIterableType) { + typeAsIterable.iterableElementType = type.typeArguments[0]; + } + else { + var iteratorFunction = getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")); + if (isTypeAny(iteratorFunction)) { + return undefined; + } + var iteratorFunctionSignatures = iteratorFunction ? getSignaturesOfType(iteratorFunction, 0 /* Call */) : emptyArray; + if (iteratorFunctionSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); + } + return undefined; + } + typeAsIterable.iterableElementType = getElementTypeOfIterator(getUnionType(ts.map(iteratorFunctionSignatures, getReturnTypeOfSignature)), errorNode); + } + } + return typeAsIterable.iterableElementType; + } + /** + * This function has very similar logic as getElementTypeOfIterable, except that it operates on + * Iterators instead of Iterables. Here is the structure: + * + * { // iterator + * next: { // iteratorNextFunction + * (): { // iteratorNextResult + * value: T // iteratorNextValue + * } + * } + * } + * + */ + function getElementTypeOfIterator(type, errorNode) { + if (isTypeAny(type)) { + return undefined; + } + var typeAsIterator = type; + if (!typeAsIterator.iteratorElementType) { + // As an optimization, if the type is instantiated directly using the globalIteratorType (Iterator), + // then just grab its type argument. + if ((type.flags & 4096 /* Reference */) && type.target === globalIteratorType) { + typeAsIterator.iteratorElementType = type.typeArguments[0]; + } + else { + var iteratorNextFunction = getTypeOfPropertyOfType(type, "next"); + if (isTypeAny(iteratorNextFunction)) { + return undefined; + } + var iteratorNextFunctionSignatures = iteratorNextFunction ? getSignaturesOfType(iteratorNextFunction, 0 /* Call */) : emptyArray; + if (iteratorNextFunctionSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.An_iterator_must_have_a_next_method); + } + return undefined; + } + var iteratorNextResult = getUnionType(ts.map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); + if (isTypeAny(iteratorNextResult)) { + return undefined; + } + var iteratorNextValue = getTypeOfPropertyOfType(iteratorNextResult, "value"); + if (!iteratorNextValue) { + if (errorNode) { + error(errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); + } + return undefined; + } + typeAsIterator.iteratorElementType = iteratorNextValue; + } + } + return typeAsIterator.iteratorElementType; + } + function getElementTypeOfIterableIterator(type) { + if (isTypeAny(type)) { + return undefined; + } + // As an optimization, if the type is instantiated directly using the globalIterableIteratorType (IterableIterator), + // then just grab its type argument. + if ((type.flags & 4096 /* Reference */) && type.target === globalIterableIteratorType) { + return type.typeArguments[0]; + } + return getElementTypeOfIterable(type, /*errorNode*/ undefined) || + getElementTypeOfIterator(type, /*errorNode*/ undefined); + } + /** + * This function does the following steps: + * 1. Break up arrayOrStringType (possibly a union) into its string constituents and array constituents. + * 2. Take the element types of the array constituents. + * 3. Return the union of the element types, and string if there was a string constitutent. + * + * For example: + * string -> string + * number[] -> number + * string[] | number[] -> string | number + * string | number[] -> string | number + * string | string[] | number[] -> string | number + * + * It also errors if: + * 1. Some constituent is neither a string nor an array. + * 2. Some constituent is a string and target is less than ES5 (because in ES3 string is not indexable). + */ + function checkElementTypeOfArrayOrString(arrayOrStringType, errorNode) { + ts.Debug.assert(languageVersion < 2 /* ES6 */); + // After we remove all types that are StringLike, we will know if there was a string constituent + // based on whether the remaining type is the same as the initial type. + var arrayType = removeTypesFromUnionType(arrayOrStringType, 258 /* StringLike */, /*isTypeOfKind*/ true, /*allowEmptyUnionResult*/ true); + var hasStringConstituent = arrayOrStringType !== arrayType; + var reportedError = false; + if (hasStringConstituent) { + if (languageVersion < 1 /* ES5 */) { + error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); + reportedError = true; + } + // Now that we've removed all the StringLike types, if no constituents remain, then the entire + // arrayOrStringType was a string. + if (arrayType === emptyObjectType) { + return stringType; + } + } + if (!isArrayLikeType(arrayType)) { + if (!reportedError) { + // Which error we report depends on whether there was a string constituent. For example, + // if the input type is number | string, we want to say that number is not an array type. + // But if the input was just number, we want to say that number is not an array type + // or a string type. + var diagnostic = hasStringConstituent + ? ts.Diagnostics.Type_0_is_not_an_array_type + : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; + error(errorNode, diagnostic, typeToString(arrayType)); + } + return hasStringConstituent ? stringType : unknownType; + } + var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */) || unknownType; + if (hasStringConstituent) { + // This is just an optimization for the case where arrayOrStringType is string | string[] + if (arrayElementType.flags & 258 /* StringLike */) { + return stringType; + } + return getUnionType([arrayElementType, stringType]); + } + return arrayElementType; + } + function checkBreakOrContinueStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); + // TODO: Check that target label is valid + } + function isGetAccessorWithAnnotatatedSetAccessor(node) { + return !!(node.kind === 145 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 146 /* SetAccessor */))); + } + function checkReturnStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + var functionBlock = ts.getContainingFunction(node); + if (!functionBlock) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + } + } + if (node.expression) { + var func = ts.getContainingFunction(node); + if (func) { + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); + var exprType = checkExpressionCached(node.expression); + if (func.asteriskToken) { + // A generator does not need its return expressions checked against its return type. + // Instead, the yield expressions are checked against the element type. + // TODO: Check return expressions of generators when return type tracking is added + // for generators. + return; + } + if (func.kind === 146 /* SetAccessor */) { + error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); + } + else if (func.kind === 144 /* Constructor */) { + if (!isTypeAssignableTo(exprType, returnType)) { + error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); + } + } + else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func) || signature.typePredicate) { + if (ts.isAsyncFunctionLike(func)) { + var promisedType = getPromisedType(returnType); + var awaitedType = checkAwaitedType(exprType, node.expression, ts.Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); + if (promisedType) { + // If the function has a return type, but promisedType is + // undefined, an error will be reported in checkAsyncFunctionReturnType + // so we don't need to report one here. + checkTypeAssignableTo(awaitedType, promisedType, node.expression); + } + } + else { + checkTypeAssignableTo(exprType, returnType, node.expression); + } + } + } + } + } + function checkWithStatement(node) { + // Grammar checking for withStatement + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.parserContextFlags & 8 /* Await */) { + grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); + } + } + checkExpression(node.expression); + error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); + } + function checkSwitchStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + var firstDefaultClause; + var hasDuplicateDefaultClause = false; + var expressionType = checkExpression(node.expression); + ts.forEach(node.caseBlock.clauses, function (clause) { + // Grammar check for duplicate default clauses, skip if we already report duplicate default clause + if (clause.kind === 242 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (firstDefaultClause === undefined) { + firstDefaultClause = clause; + } + else { + var sourceFile = ts.getSourceFileOfNode(node); + var start = ts.skipTrivia(sourceFile.text, clause.pos); + var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + hasDuplicateDefaultClause = true; + } + } + if (produceDiagnostics && clause.kind === 241 /* CaseClause */) { + var caseClause = clause; + // TypeScript 1.0 spec (April 2014):5.9 + // In a 'switch' statement, each 'case' expression must be of a type that is assignable to or from the type of the 'switch' expression. + var caseType = checkExpression(caseClause.expression); + if (!isTypeAssignableTo(expressionType, caseType)) { + // check 'expressionType isAssignableTo caseType' failed, try the reversed check and report errors if it fails + checkTypeAssignableTo(caseType, expressionType, caseClause.expression, /*headMessage*/ undefined); + } + } + ts.forEach(clause.statements, checkSourceElement); + }); + } + function checkLabeledStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + var current = node.parent; + while (current) { + if (ts.isFunctionLike(current)) { + break; + } + if (current.kind === 207 /* LabeledStatement */ && current.label.text === node.label.text) { + var sourceFile = ts.getSourceFileOfNode(node); + grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); + break; + } + current = current.parent; + } + } + // ensure that label is unique + checkSourceElement(node.statement); + } + function checkThrowStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.expression === undefined) { + grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here); + } + } + if (node.expression) { + checkExpression(node.expression); + } + } + function checkTryStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkBlock(node.tryBlock); + var catchClause = node.catchClause; + if (catchClause) { + // Grammar checking + if (catchClause.variableDeclaration) { + if (catchClause.variableDeclaration.name.kind !== 69 /* Identifier */) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.name, ts.Diagnostics.Catch_clause_variable_name_must_be_an_identifier); + } + else if (catchClause.variableDeclaration.type) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); + } + else if (catchClause.variableDeclaration.initializer) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); + } + else { + var identifierName = catchClause.variableDeclaration.name.text; + var locals = catchClause.block.locals; + if (locals && ts.hasProperty(locals, identifierName)) { + var localSymbol = locals[identifierName]; + if (localSymbol && (localSymbol.flags & 2 /* BlockScopedVariable */) !== 0) { + grammarErrorOnNode(localSymbol.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); + } + } + } + } + checkBlock(catchClause.block); + } + if (node.finallyBlock) { + checkBlock(node.finallyBlock); + } + } + function checkIndexConstraints(type) { + var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */); + var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */); + var stringIndexType = getIndexTypeOfType(type, 0 /* String */); + var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); + if (stringIndexType || numberIndexType) { + ts.forEach(getPropertiesOfObjectType(type), function (prop) { + var propType = getTypeOfSymbol(prop); + checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + }); + if (type.flags & 1024 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { + var classDeclaration = type.symbol.valueDeclaration; + for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { + var member = _a[_i]; + // Only process instance properties with computed names here. + // Static properties cannot be in conflict with indexers, + // and properties with literal names were already checked. + if (!(member.flags & 128 /* Static */) && ts.hasDynamicName(member)) { + var propType = getTypeOfSymbol(member.symbol); + checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + } + } + } + } + var errorNode; + if (stringIndexType && numberIndexType) { + errorNode = declaredNumberIndexer || declaredStringIndexer; + // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer + if (!errorNode && (type.flags & 2048 /* Interface */)) { + var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); + errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + } + } + if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { + error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); + } + function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { + if (!indexType) { + return; + } + // index is numeric and property name is not valid numeric literal + if (indexKind === 1 /* Number */ && !isNumericName(prop.valueDeclaration.name)) { + return; + } + // perform property check if property or indexer is declared in 'type' + // this allows to rule out cases when both property and indexer are inherited from the base class + var errorNode; + if (prop.valueDeclaration.name.kind === 136 /* ComputedPropertyName */ || prop.parent === containingType.symbol) { + errorNode = prop.valueDeclaration; + } + else if (indexDeclaration) { + errorNode = indexDeclaration; + } + else if (containingType.flags & 2048 /* Interface */) { + // for interfaces property and indexer might be inherited from different bases + // check if any base class already has both property and indexer. + // check should be performed only if 'type' is the first type that brings property\indexer together + var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); + errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + } + if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { + var errorMessage = indexKind === 0 /* String */ + ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 + : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; + error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); + } + } + } + function checkTypeNameIsReserved(name, message) { + // TS 1.0 spec (April 2014): 3.6.1 + // The predefined type keywords are reserved and cannot be used as names of user defined types. + switch (name.text) { + case "any": + case "number": + case "boolean": + case "string": + case "symbol": + case "void": + error(name, message, name.text); + } + } + // Check each type parameter and check that list has no duplicate type parameter declarations + function checkTypeParameters(typeParameterDeclarations) { + if (typeParameterDeclarations) { + for (var i = 0, n = typeParameterDeclarations.length; i < n; i++) { + var node = typeParameterDeclarations[i]; + checkTypeParameter(node); + if (produceDiagnostics) { + for (var j = 0; j < i; j++) { + if (typeParameterDeclarations[j].symbol === node.symbol) { + error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name)); + } + } + } + } + } + } + function checkClassExpression(node) { + checkClassLikeDeclaration(node); + return getTypeOfSymbol(getSymbolOfNode(node)); + } + function checkClassDeclaration(node) { + if (!node.name && !(node.flags & 1024 /* Default */)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); + } + checkClassLikeDeclaration(node); + ts.forEach(node.members, checkSourceElement); + } + function checkClassLikeDeclaration(node) { + checkGrammarClassDeclarationHeritageClauses(node); + checkDecorators(node); + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + } + checkTypeParameters(node.typeParameters); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + var staticType = getTypeOfSymbol(symbol); + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + if (baseTypeNode) { + emitExtends = emitExtends || !ts.isInAmbientContext(node); + var baseTypes = getBaseTypes(type); + if (baseTypes.length && produceDiagnostics) { + var baseType = baseTypes[0]; + var staticBaseType = getBaseConstructorTypeOfClass(type); + checkSourceElement(baseTypeNode.expression); + if (baseTypeNode.typeArguments) { + ts.forEach(baseTypeNode.typeArguments, checkSourceElement); + for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); _i < _a.length; _i++) { + var constructor = _a[_i]; + if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) { + break; + } + } + } + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */)) { + // When the static base type is a "class-like" constructor function (but not actually a class), we verify + // that all instantiated base constructor signatures return the same type. We can simply compare the type + // references (as opposed to checking the structure of the types) because elsewhere we have already checked + // that the base type is a class or interface type (and not, for example, an anonymous object type). + var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); + if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType; })) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); + } + } + checkKindsOfPropertyMemberOverrides(type, baseType); + } + } + var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); + if (implementedTypeNodes) { + for (var _b = 0; _b < implementedTypeNodes.length; _b++) { + var typeRefNode = implementedTypeNodes[_b]; + if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { + error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(typeRefNode); + if (produceDiagnostics) { + var t = getTypeFromTypeNode(typeRefNode); + if (t !== unknownType) { + var declaredType = (t.flags & 4096 /* Reference */) ? t.target : t; + if (declaredType.flags & (1024 /* Class */ | 2048 /* Interface */)) { + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); + } + else { + error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); + } + } + } + } + } + if (produceDiagnostics) { + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + } + } + function getTargetSymbol(s) { + // if symbol is instantiated its flags are not copied from the 'target' + // so we'll need to get back original 'target' symbol to work with correct set of flags + return s.flags & 16777216 /* Instantiated */ ? getSymbolLinks(s).target : s; + } + function getClassLikeDeclarationOfSymbol(symbol) { + return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); + } + function checkKindsOfPropertyMemberOverrides(type, baseType) { + // TypeScript 1.0 spec (April 2014): 8.2.3 + // A derived class inherits all members from its base class it doesn't override. + // Inheritance means that a derived class implicitly contains all non - overridden members of the base class. + // Both public and private property members are inherited, but only public property members can be overridden. + // A property member in a derived class is said to override a property member in a base class + // when the derived class property member has the same name and kind(instance or static) + // as the base class property member. + // The type of an overriding property member must be assignable(section 3.8.4) + // to the type of the overridden property member, or otherwise a compile - time error occurs. + // Base class instance member functions can be overridden by derived class instance member functions, + // but not by other kinds of members. + // Base class instance member variables and accessors can be overridden by + // derived class instance member variables and accessors, but not by other kinds of members. + // NOTE: assignability is checked in checkClassDeclaration + var baseProperties = getPropertiesOfObjectType(baseType); + for (var _i = 0; _i < baseProperties.length; _i++) { + var baseProperty = baseProperties[_i]; + var base = getTargetSymbol(baseProperty); + if (base.flags & 134217728 /* Prototype */) { + continue; + } + var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); + var baseDeclarationFlags = getDeclarationFlagsFromSymbol(base); + ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); + if (derived) { + // In order to resolve whether the inherited method was overriden in the base class or not, + // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated* + // type declaration, derived and base resolve to the same symbol even in the case of generic classes. + if (derived === base) { + // derived class inherits base without override/redeclaration + var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); + // It is an error to inherit an abstract member without implementing it or being declared abstract. + // If there is no declaration for the derived class (as in the case of class expressions), + // then the class cannot be declared abstract. + if (baseDeclarationFlags & 256 /* Abstract */ && (!derivedClassDecl || !(derivedClassDecl.flags & 256 /* Abstract */))) { + if (derivedClassDecl.kind === 186 /* ClassExpression */) { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); + } + else { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType)); + } + } + } + else { + // derived overrides base. + var derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); + if ((baseDeclarationFlags & 32 /* Private */) || (derivedDeclarationFlags & 32 /* Private */)) { + // either base or derived property is private - not override, skip it + continue; + } + if ((baseDeclarationFlags & 128 /* Static */) !== (derivedDeclarationFlags & 128 /* Static */)) { + // value of 'static' is not the same for properties - not override, skip it + continue; + } + if ((base.flags & derived.flags & 8192 /* Method */) || ((base.flags & 98308 /* PropertyOrAccessor */) && (derived.flags & 98308 /* PropertyOrAccessor */))) { + // method is overridden with method or property/accessor is overridden with property/accessor - correct case + continue; + } + var errorMessage = void 0; + if (base.flags & 8192 /* Method */) { + if (derived.flags & 98304 /* Accessor */) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; + } + else { + ts.Debug.assert((derived.flags & 4 /* Property */) !== 0); + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + } + } + else if (base.flags & 4 /* Property */) { + ts.Debug.assert((derived.flags & 8192 /* Method */) !== 0); + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + } + else { + ts.Debug.assert((base.flags & 98304 /* Accessor */) !== 0); + ts.Debug.assert((derived.flags & 8192 /* Method */) !== 0); + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } + error(derived.valueDeclaration.name, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + } + } + } + } + function isAccessor(kind) { + return kind === 145 /* GetAccessor */ || kind === 146 /* SetAccessor */; + } + function areTypeParametersIdentical(list1, list2) { + if (!list1 && !list2) { + return true; + } + if (!list1 || !list2 || list1.length !== list2.length) { + return false; + } + // TypeScript 1.0 spec (April 2014): + // When a generic interface has multiple declarations, all declarations must have identical type parameter + // lists, i.e. identical type parameter names with identical constraints in identical order. + for (var i = 0, len = list1.length; i < len; i++) { + var tp1 = list1[i]; + var tp2 = list2[i]; + if (tp1.name.text !== tp2.name.text) { + return false; + } + if (!tp1.constraint && !tp2.constraint) { + continue; + } + if (!tp1.constraint || !tp2.constraint) { + return false; + } + if (!isTypeIdenticalTo(getTypeFromTypeNode(tp1.constraint), getTypeFromTypeNode(tp2.constraint))) { + return false; + } + } + return true; + } + function checkInheritedPropertiesAreIdentical(type, typeNode) { + var baseTypes = getBaseTypes(type); + if (baseTypes.length < 2) { + return true; + } + var seen = {}; + ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen[p.name] = { prop: p, containingType: type }; }); + var ok = true; + for (var _i = 0; _i < baseTypes.length; _i++) { + var base = baseTypes[_i]; + var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); + for (var _a = 0; _a < properties.length; _a++) { + var prop = properties[_a]; + if (!ts.hasProperty(seen, prop.name)) { + seen[prop.name] = { prop: prop, containingType: base }; + } + else { + var existing = seen[prop.name]; + var isInheritedProperty = existing.containingType !== type; + if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { + ok = false; + var typeName1 = typeToString(existing.containingType); + var typeName2 = typeToString(base); + var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); + } + } + } + } + return ok; + } + function checkInterfaceDeclaration(node) { + // Grammar checking + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); + checkTypeParameters(node.typeParameters); + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 215 /* InterfaceDeclaration */); + if (symbol.declarations.length > 1) { + if (node !== firstInterfaceDecl && !areTypeParametersIdentical(firstInterfaceDecl.typeParameters, node.typeParameters)) { + error(node.name, ts.Diagnostics.All_declarations_of_an_interface_must_have_identical_type_parameters); + } + } + // Only check this symbol once + if (node === firstInterfaceDecl) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + // run subsequent checks only if first set succeeded + if (checkInheritedPropertiesAreIdentical(type, node.name)) { + for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) { + var baseType = _a[_i]; + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); + } + checkIndexConstraints(type); + } + } + } + ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { + if (!ts.isSupportedExpressionWithTypeArguments(heritageElement)) { + error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(heritageElement); + }); + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + checkTypeForDuplicateIndexSignatures(node); + } + } + function checkTypeAliasDeclaration(node) { + // Grammar checking + checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + checkSourceElement(node.type); + } + function computeEnumMemberValues(node) { + var nodeLinks = getNodeLinks(node); + if (!(nodeLinks.flags & 8192 /* EnumValuesComputed */)) { + var enumSymbol = getSymbolOfNode(node); + var enumType = getDeclaredTypeOfSymbol(enumSymbol); + var autoValue = 0; // set to undefined when enum member is non-constant + var ambient = ts.isInAmbientContext(node); + var enumIsConst = ts.isConst(node); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.name.kind === 136 /* ComputedPropertyName */) { + error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); + } + else if (isNumericLiteralName(member.name.text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); + } + var previousEnumMemberIsNonConstant = autoValue === undefined; + var initializer = member.initializer; + if (initializer) { + autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); + } + else if (ambient && !enumIsConst) { + // In ambient enum declarations that specify no const modifier, enum member declarations + // that omit a value are considered computed members (as opposed to having auto-incremented values assigned). + autoValue = undefined; + } + else if (previousEnumMemberIsNonConstant) { + // If the member declaration specifies no value, the member is considered a constant enum member. + // If the member is the first member in the enum declaration, it is assigned the value zero. + // Otherwise, it is assigned the value of the immediately preceding member plus one, + // and an error occurs if the immediately preceding member is not a constant enum member + error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); + } + if (autoValue !== undefined) { + getNodeLinks(member).enumMemberValue = autoValue++; + } + } + nodeLinks.flags |= 8192 /* EnumValuesComputed */; + } + function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { + // Controls if error should be reported after evaluation of constant value is completed + // Can be false if another more precise error was already reported during evaluation. + var reportError = true; + var value = evalConstant(initializer); + if (reportError) { + if (value === undefined) { + if (enumIsConst) { + error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (ambient) { + error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); + } + else { + // Only here do we need to check that the initializer is assignable to the enum type. + checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, /*headMessage*/ undefined); + } + } + else if (enumIsConst) { + if (isNaN(value)) { + error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); + } + else if (!isFinite(value)) { + error(initializer, ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + } + return value; + function evalConstant(e) { + switch (e.kind) { + case 179 /* PrefixUnaryExpression */: + var value_1 = evalConstant(e.operand); + if (value_1 === undefined) { + return undefined; + } + switch (e.operator) { + case 35 /* PlusToken */: return value_1; + case 36 /* MinusToken */: return -value_1; + case 50 /* TildeToken */: return ~value_1; + } + return undefined; + case 181 /* BinaryExpression */: + var left = evalConstant(e.left); + if (left === undefined) { + return undefined; + } + var right = evalConstant(e.right); + if (right === undefined) { + return undefined; + } + switch (e.operatorToken.kind) { + case 47 /* BarToken */: return left | right; + case 46 /* AmpersandToken */: return left & right; + case 44 /* GreaterThanGreaterThanToken */: return left >> right; + case 45 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; + case 43 /* LessThanLessThanToken */: return left << right; + case 48 /* CaretToken */: return left ^ right; + case 37 /* AsteriskToken */: return left * right; + case 39 /* SlashToken */: return left / right; + case 35 /* PlusToken */: return left + right; + case 36 /* MinusToken */: return left - right; + case 40 /* PercentToken */: return left % right; + } + return undefined; + case 8 /* NumericLiteral */: + return +e.text; + case 172 /* ParenthesizedExpression */: + return evalConstant(e.expression); + case 69 /* Identifier */: + case 167 /* ElementAccessExpression */: + case 166 /* PropertyAccessExpression */: + var member = initializer.parent; + var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); + var enumType_1; + var propertyName; + if (e.kind === 69 /* Identifier */) { + // unqualified names can refer to member that reside in different declaration of the enum so just doing name resolution won't work. + // instead pick current enum type and later try to fetch member from the type + enumType_1 = currentType; + propertyName = e.text; + } + else { + var expression; + if (e.kind === 167 /* ElementAccessExpression */) { + if (e.argumentExpression === undefined || + e.argumentExpression.kind !== 9 /* StringLiteral */) { + return undefined; + } + expression = e.expression; + propertyName = e.argumentExpression.text; + } + else { + expression = e.expression; + propertyName = e.name.text; + } + // expression part in ElementAccess\PropertyAccess should be either identifier or dottedName + var current = expression; + while (current) { + if (current.kind === 69 /* Identifier */) { + break; + } + else if (current.kind === 166 /* PropertyAccessExpression */) { + current = current.expression; + } + else { + return undefined; + } + } + enumType_1 = checkExpression(expression); + // allow references to constant members of other enums + if (!(enumType_1.symbol && (enumType_1.symbol.flags & 384 /* Enum */))) { + return undefined; + } + } + if (propertyName === undefined) { + return undefined; + } + var property = getPropertyOfObjectType(enumType_1, propertyName); + if (!property || !(property.flags & 8 /* EnumMember */)) { + return undefined; + } + var propertyDecl = property.valueDeclaration; + // self references are illegal + if (member === propertyDecl) { + return undefined; + } + // illegal case: forward reference + if (!isBlockScopedNameDeclaredBeforeUse(propertyDecl, member)) { + reportError = false; + error(e, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); + return undefined; + } + return getNodeLinks(propertyDecl).enumMemberValue; + } + } + } + } + function checkEnumDeclaration(node) { + if (!produceDiagnostics) { + return; + } + // Grammar checking + checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkExportsOnMergedDeclarations(node); + computeEnumMemberValues(node); + var enumIsConst = ts.isConst(node); + if (compilerOptions.isolatedModules && enumIsConst && ts.isInAmbientContext(node)) { + error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); + } + // Spec 2014 - Section 9.3: + // It isn't possible for one enum declaration to continue the automatic numbering sequence of another, + // and when an enum type has multiple declarations, only one declaration is permitted to omit a value + // for the first member. + // + // Only perform this check once per symbol + var enumSymbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); + if (node === firstDeclaration) { + if (enumSymbol.declarations.length > 1) { + // check that const is placed\omitted on all enum declarations + ts.forEach(enumSymbol.declarations, function (decl) { + if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { + error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + } + }); + } + var seenEnumMissingInitialInitializer = false; + ts.forEach(enumSymbol.declarations, function (declaration) { + // return true if we hit a violation of the rule, false otherwise + if (declaration.kind !== 217 /* EnumDeclaration */) { + return false; + } + var enumDeclaration = declaration; + if (!enumDeclaration.members.length) { + return false; + } + var firstEnumMember = enumDeclaration.members[0]; + if (!firstEnumMember.initializer) { + if (seenEnumMissingInitialInitializer) { + error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); + } + else { + seenEnumMissingInitialInitializer = true; + } + } + }); + } + } + function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0; _i < declarations.length; _i++) { + var declaration = declarations[_i]; + if ((declaration.kind === 214 /* ClassDeclaration */ || + (declaration.kind === 213 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + !ts.isInAmbientContext(declaration)) { + return declaration; + } + } + return undefined; + } + function inSameLexicalScope(node1, node2) { + var container1 = ts.getEnclosingBlockScopeContainer(node1); + var container2 = ts.getEnclosingBlockScopeContainer(node2); + if (isGlobalSourceFile(container1)) { + return isGlobalSourceFile(container2); + } + else if (isGlobalSourceFile(container2)) { + return false; + } + else { + return container1 === container2; + } + } + function checkModuleDeclaration(node) { + if (produceDiagnostics) { + // Grammar checking + var isAmbientExternalModule = node.name.kind === 9 /* StringLiteral */; + var contextErrorMessage = isAmbientExternalModule + ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file + : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; + if (checkGrammarModuleElementContext(node, contextErrorMessage)) { + // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { + if (!ts.isInAmbientContext(node) && node.name.kind === 9 /* StringLiteral */) { + grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); + } + } + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + // The following checks only apply on a non-ambient instantiated module declaration. + if (symbol.flags & 512 /* ValueModule */ + && symbol.declarations.length > 1 + && !ts.isInAmbientContext(node) + && ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { + var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); + if (firstNonAmbientClassOrFunc) { + if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); + } + else if (node.pos < firstNonAmbientClassOrFunc.pos) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); + } + } + // if the module merges with a class declaration in the same lexical scope, + // we need to track this to ensure the correct emit. + var mergedClass = ts.getDeclarationOfKind(symbol, 214 /* ClassDeclaration */); + if (mergedClass && + inSameLexicalScope(node, mergedClass)) { + getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; + } + } + // Checks for ambient external modules. + if (isAmbientExternalModule) { + if (!isGlobalSourceFile(node.parent)) { + error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + } + if (ts.isExternalModuleNameRelative(node.name.text)) { + error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } + } + } + checkSourceElement(node.body); + } + function getFirstIdentifier(node) { + while (true) { + if (node.kind === 135 /* QualifiedName */) { + node = node.left; + } + else if (node.kind === 166 /* PropertyAccessExpression */) { + node = node.expression; + } + else { + break; + } + } + ts.Debug.assert(node.kind === 69 /* Identifier */); + return node; + } + function checkExternalImportOrExportDeclaration(node) { + var moduleName = ts.getExternalModuleName(node); + if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9 /* StringLiteral */) { + error(moduleName, ts.Diagnostics.String_literal_expected); + return false; + } + var inAmbientExternalModule = node.parent.kind === 219 /* ModuleBlock */ && node.parent.parent.name.kind === 9 /* StringLiteral */; + if (node.parent.kind !== 248 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 228 /* ExportDeclaration */ ? + ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : + ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); + return false; + } + if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { + // TypeScript 1.0 spec (April 2013): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference + // other external modules only through top - level external module names. + // Relative external module names are not permitted. + error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); + return false; + } + return true; + } + function checkAliasSymbol(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target !== unknownSymbol) { + var excludedMeanings = (symbol.flags & 107455 /* Value */ ? 107455 /* Value */ : 0) | + (symbol.flags & 793056 /* Type */ ? 793056 /* Type */ : 0) | + (symbol.flags & 1536 /* Namespace */ ? 1536 /* Namespace */ : 0); + if (target.flags & excludedMeanings) { + var message = node.kind === 230 /* ExportSpecifier */ ? + ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : + ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; + error(node, message, symbolToString(symbol)); + } + } + } + function checkImportBinding(node) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkAliasSymbol(node); + } + function checkImportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 2035 /* Modifier */)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); + } + if (checkExternalImportOrExportDeclaration(node)) { + var importClause = node.importClause; + if (importClause) { + if (importClause.name) { + checkImportBinding(importClause); + } + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 224 /* NamespaceImport */) { + checkImportBinding(importClause.namedBindings); + } + else { + ts.forEach(importClause.namedBindings.elements, checkImportBinding); + } + } + } + } + } + function checkImportEqualsDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + checkGrammarDecorators(node) || checkGrammarModifiers(node); + if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { + checkImportBinding(node); + if (node.flags & 1 /* Export */) { + markExportAsReferenced(node); + } + if (ts.isInternalModuleImportEqualsDeclaration(node)) { + var target = resolveAlias(getSymbolOfNode(node)); + if (target !== unknownSymbol) { + if (target.flags & 107455 /* Value */) { + // Target is a value symbol, check that it is not hidden by a local declaration with the same name + var moduleName = getFirstIdentifier(node.moduleReference); + if (!(resolveEntityName(moduleName, 107455 /* Value */ | 1536 /* Namespace */).flags & 1536 /* Namespace */)) { + error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); + } + } + if (target.flags & 793056 /* Type */) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); + } + } + } + else { + if (modulekind === 5 /* ES6 */ && !ts.isInAmbientContext(node)) { + // Import equals declaration is deprecated in es6 or above + grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_6_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); + } + } + } + } + function checkExportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { + // If we hit an export in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 2035 /* Modifier */)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); + } + if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { + if (node.exportClause) { + // export { x, y } + // export { x, y } from "foo" + ts.forEach(node.exportClause.elements, checkExportSpecifier); + var inAmbientExternalModule = node.parent.kind === 219 /* ModuleBlock */ && node.parent.parent.name.kind === 9 /* StringLiteral */; + if (node.parent.kind !== 248 /* SourceFile */ && !inAmbientExternalModule) { + error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); + } + } + else { + // export * from "foo" + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleSymbol && moduleSymbol.exports["export="]) { + error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); + } + } + } + } + function checkGrammarModuleElementContext(node, errorMessage) { + if (node.parent.kind !== 248 /* SourceFile */ && node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 218 /* ModuleDeclaration */) { + return grammarErrorOnFirstToken(node, errorMessage); + } + } + function checkExportSpecifier(node) { + checkAliasSymbol(node); + if (!node.parent.parent.moduleSpecifier) { + markExportAsReferenced(node); + } + } + function checkExportAssignment(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. + return; + } + var container = node.parent.kind === 248 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 218 /* ModuleDeclaration */ && container.name.kind === 69 /* Identifier */) { + error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); + return; + } + // Grammar checking + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 2035 /* Modifier */)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); + } + if (node.expression.kind === 69 /* Identifier */) { + markExportAsReferenced(node); + } + else { + checkExpressionCached(node.expression); + } + checkExternalModuleExports(container); + if (node.isExportEquals && !ts.isInAmbientContext(node)) { + if (modulekind === 5 /* ES6 */) { + // export assignment is not supported in es6 modules + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_6_modules_Consider_using_export_default_or_another_module_format_instead); + } + else if (modulekind === 4 /* System */) { + // system modules does not support export assignment + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); + } + } + } + function getModuleStatements(node) { + if (node.kind === 248 /* SourceFile */) { + return node.statements; + } + if (node.kind === 218 /* ModuleDeclaration */ && node.body.kind === 219 /* ModuleBlock */) { + return node.body.statements; + } + return emptyArray; + } + function hasExportedMembers(moduleSymbol) { + for (var id in moduleSymbol.exports) { + if (id !== "export=") { + return true; + } + } + return false; + } + function checkExternalModuleExports(node) { + var moduleSymbol = getSymbolOfNode(node); + var links = getSymbolLinks(moduleSymbol); + if (!links.exportsChecked) { + var exportEqualsSymbol = moduleSymbol.exports["export="]; + if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { + var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; + error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + links.exportsChecked = true; + } + } + function checkTypePredicate(node) { + if (!isInLegalTypePredicatePosition(node)) { + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + } + } + function checkSourceElement(node) { + if (!node) { + return; + } + var kind = node.kind; + if (cancellationToken) { + // Only bother checking on a few construct kinds. We don't want to be excessivly + // hitting the cancellation token on every node we check. + switch (kind) { + case 218 /* ModuleDeclaration */: + case 214 /* ClassDeclaration */: + case 215 /* InterfaceDeclaration */: + case 213 /* FunctionDeclaration */: + cancellationToken.throwIfCancellationRequested(); + } + } + switch (kind) { + case 137 /* TypeParameter */: + return checkTypeParameter(node); + case 138 /* Parameter */: + return checkParameter(node); + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + return checkPropertyDeclaration(node); + case 152 /* FunctionType */: + case 153 /* ConstructorType */: + case 147 /* CallSignature */: + case 148 /* ConstructSignature */: + return checkSignatureDeclaration(node); + case 149 /* IndexSignature */: + return checkSignatureDeclaration(node); + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + return checkMethodDeclaration(node); + case 144 /* Constructor */: + return checkConstructorDeclaration(node); + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + return checkAccessorDeclaration(node); + case 151 /* TypeReference */: + return checkTypeReferenceNode(node); + case 150 /* TypePredicate */: + return checkTypePredicate(node); + case 154 /* TypeQuery */: + return checkTypeQuery(node); + case 155 /* TypeLiteral */: + return checkTypeLiteral(node); + case 156 /* ArrayType */: + return checkArrayType(node); + case 157 /* TupleType */: + return checkTupleType(node); + case 158 /* UnionType */: + case 159 /* IntersectionType */: + return checkUnionOrIntersectionType(node); + case 160 /* ParenthesizedType */: + return checkSourceElement(node.type); + case 213 /* FunctionDeclaration */: + return checkFunctionDeclaration(node); + case 192 /* Block */: + case 219 /* ModuleBlock */: + return checkBlock(node); + case 193 /* VariableStatement */: + return checkVariableStatement(node); + case 195 /* ExpressionStatement */: + return checkExpressionStatement(node); + case 196 /* IfStatement */: + return checkIfStatement(node); + case 197 /* DoStatement */: + return checkDoStatement(node); + case 198 /* WhileStatement */: + return checkWhileStatement(node); + case 199 /* ForStatement */: + return checkForStatement(node); + case 200 /* ForInStatement */: + return checkForInStatement(node); + case 201 /* ForOfStatement */: + return checkForOfStatement(node); + case 202 /* ContinueStatement */: + case 203 /* BreakStatement */: + return checkBreakOrContinueStatement(node); + case 204 /* ReturnStatement */: + return checkReturnStatement(node); + case 205 /* WithStatement */: + return checkWithStatement(node); + case 206 /* SwitchStatement */: + return checkSwitchStatement(node); + case 207 /* LabeledStatement */: + return checkLabeledStatement(node); + case 208 /* ThrowStatement */: + return checkThrowStatement(node); + case 209 /* TryStatement */: + return checkTryStatement(node); + case 211 /* VariableDeclaration */: + return checkVariableDeclaration(node); + case 163 /* BindingElement */: + return checkBindingElement(node); + case 214 /* ClassDeclaration */: + return checkClassDeclaration(node); + case 215 /* InterfaceDeclaration */: + return checkInterfaceDeclaration(node); + case 216 /* TypeAliasDeclaration */: + return checkTypeAliasDeclaration(node); + case 217 /* EnumDeclaration */: + return checkEnumDeclaration(node); + case 218 /* ModuleDeclaration */: + return checkModuleDeclaration(node); + case 222 /* ImportDeclaration */: + return checkImportDeclaration(node); + case 221 /* ImportEqualsDeclaration */: + return checkImportEqualsDeclaration(node); + case 228 /* ExportDeclaration */: + return checkExportDeclaration(node); + case 227 /* ExportAssignment */: + return checkExportAssignment(node); + case 194 /* EmptyStatement */: + checkGrammarStatementInAmbientContext(node); + return; + case 210 /* DebuggerStatement */: + checkGrammarStatementInAmbientContext(node); + return; + case 231 /* MissingDeclaration */: + return checkMissingDeclaration(node); + } + } + // Function and class expression bodies are checked after all statements in the enclosing body. This is + // to ensure constructs like the following are permitted: + // let foo = function () { + // let s = foo(); + // return "hello"; + // } + // Here, performing a full type check of the body of the function expression whilst in the process of + // determining the type of foo would cause foo to be given type any because of the recursive reference. + // Delaying the type check of the body ensures foo has been assigned a type. + function checkFunctionAndClassExpressionBodies(node) { + switch (node.kind) { + case 173 /* FunctionExpression */: + case 174 /* ArrowFunction */: + ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); + checkFunctionExpressionOrObjectLiteralMethodBody(node); + break; + case 186 /* ClassExpression */: + ts.forEach(node.members, checkSourceElement); + ts.forEachChild(node, checkFunctionAndClassExpressionBodies); + break; + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + ts.forEach(node.decorators, checkFunctionAndClassExpressionBodies); + ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); + if (ts.isObjectLiteralMethod(node)) { + checkFunctionExpressionOrObjectLiteralMethodBody(node); + } + break; + case 144 /* Constructor */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 213 /* FunctionDeclaration */: + ts.forEach(node.parameters, checkFunctionAndClassExpressionBodies); + break; + case 205 /* WithStatement */: + checkFunctionAndClassExpressionBodies(node.expression); + break; + case 139 /* Decorator */: + case 138 /* Parameter */: + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 161 /* ObjectBindingPattern */: + case 162 /* ArrayBindingPattern */: + case 163 /* BindingElement */: + case 164 /* ArrayLiteralExpression */: + case 165 /* ObjectLiteralExpression */: + case 245 /* PropertyAssignment */: + case 166 /* PropertyAccessExpression */: + case 167 /* ElementAccessExpression */: + case 168 /* CallExpression */: + case 169 /* NewExpression */: + case 170 /* TaggedTemplateExpression */: + case 183 /* TemplateExpression */: + case 190 /* TemplateSpan */: + case 171 /* TypeAssertionExpression */: + case 189 /* AsExpression */: + case 172 /* ParenthesizedExpression */: + case 176 /* TypeOfExpression */: + case 177 /* VoidExpression */: + case 178 /* AwaitExpression */: + case 175 /* DeleteExpression */: + case 179 /* PrefixUnaryExpression */: + case 180 /* PostfixUnaryExpression */: + case 181 /* BinaryExpression */: + case 182 /* ConditionalExpression */: + case 185 /* SpreadElementExpression */: + case 184 /* YieldExpression */: + case 192 /* Block */: + case 219 /* ModuleBlock */: + case 193 /* VariableStatement */: + case 195 /* ExpressionStatement */: + case 196 /* IfStatement */: + case 197 /* DoStatement */: + case 198 /* WhileStatement */: + case 199 /* ForStatement */: + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + case 202 /* ContinueStatement */: + case 203 /* BreakStatement */: + case 204 /* ReturnStatement */: + case 206 /* SwitchStatement */: + case 220 /* CaseBlock */: + case 241 /* CaseClause */: + case 242 /* DefaultClause */: + case 207 /* LabeledStatement */: + case 208 /* ThrowStatement */: + case 209 /* TryStatement */: + case 244 /* CatchClause */: + case 211 /* VariableDeclaration */: + case 212 /* VariableDeclarationList */: + case 214 /* ClassDeclaration */: + case 243 /* HeritageClause */: + case 188 /* ExpressionWithTypeArguments */: + case 217 /* EnumDeclaration */: + case 247 /* EnumMember */: + case 227 /* ExportAssignment */: + case 248 /* SourceFile */: + case 240 /* JsxExpression */: + case 233 /* JsxElement */: + case 234 /* JsxSelfClosingElement */: + case 238 /* JsxAttribute */: + case 239 /* JsxSpreadAttribute */: + case 235 /* JsxOpeningElement */: + ts.forEachChild(node, checkFunctionAndClassExpressionBodies); + break; + } + } + function checkSourceFile(node) { + var start = new Date().getTime(); + checkSourceFileWorker(node); + ts.checkTime += new Date().getTime() - start; + } + // Fully type check a source file and collect the relevant diagnostics. + function checkSourceFileWorker(node) { + var links = getNodeLinks(node); + if (!(links.flags & 1 /* TypeChecked */)) { + // Check whether the file has declared it is the default lib, + // and whether the user has specifically chosen to avoid checking it. + if (node.isDefaultLib && compilerOptions.skipDefaultLibCheck) { + return; + } + // Grammar checking + checkGrammarSourceFile(node); + emitExtends = false; + emitDecorate = false; + emitParam = false; + potentialThisCollisions.length = 0; + ts.forEach(node.statements, checkSourceElement); + checkFunctionAndClassExpressionBodies(node); + if (ts.isExternalModule(node)) { + checkExternalModuleExports(node); + } + if (potentialThisCollisions.length) { + ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); + potentialThisCollisions.length = 0; + } + if (emitExtends) { + links.flags |= 8 /* EmitExtends */; + } + if (emitDecorate) { + links.flags |= 16 /* EmitDecorate */; + } + if (emitParam) { + links.flags |= 32 /* EmitParam */; + } + if (emitAwaiter) { + links.flags |= 64 /* EmitAwaiter */; + } + if (emitGenerator || (emitAwaiter && languageVersion < 2 /* ES6 */)) { + links.flags |= 128 /* EmitGenerator */; + } + links.flags |= 1 /* TypeChecked */; + } + } + function getDiagnostics(sourceFile, ct) { + try { + // Record the cancellation token so it can be checked later on during checkSourceElement. + // Do this in a finally block so we can ensure that it gets reset back to nothing after + // this call is done. + cancellationToken = ct; + return getDiagnosticsWorker(sourceFile); + } + finally { + cancellationToken = undefined; + } + } + function getDiagnosticsWorker(sourceFile) { + throwIfNonDiagnosticsProducing(); + if (sourceFile) { + checkSourceFile(sourceFile); + return diagnostics.getDiagnostics(sourceFile.fileName); + } + ts.forEach(host.getSourceFiles(), checkSourceFile); + return diagnostics.getDiagnostics(); + } + function getGlobalDiagnostics() { + throwIfNonDiagnosticsProducing(); + return diagnostics.getGlobalDiagnostics(); + } + function throwIfNonDiagnosticsProducing() { + if (!produceDiagnostics) { + throw new Error("Trying to get diagnostics from a type checker that does not produce them."); + } + } + // Language service support + function isInsideWithStatementBody(node) { + if (node) { + while (node.parent) { + if (node.parent.kind === 205 /* WithStatement */ && node.parent.statement === node) { + return true; + } + node = node.parent; + } + } + return false; + } + function getSymbolsInScope(location, meaning) { + var symbols = {}; + var memberFlags = 0; + if (isInsideWithStatementBody(location)) { + // We cannot answer semantic questions within a with block, do not proceed any further + return []; + } + populateSymbols(); + return symbolsToArray(symbols); + function populateSymbols() { + while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + copySymbols(location.locals, meaning); + } + switch (location.kind) { + case 248 /* SourceFile */: + if (!ts.isExternalModule(location)) { + break; + } + case 218 /* ModuleDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & 8914931 /* ModuleMember */); + break; + case 217 /* EnumDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); + break; + case 186 /* ClassExpression */: + var className = location.name; + if (className) { + copySymbol(location.symbol, meaning); + } + // fall through; this fall-through is necessary because we would like to handle + // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration + case 214 /* ClassDeclaration */: + case 215 /* InterfaceDeclaration */: + // If we didn't come from static member of class or interface, + // add the type parameters into the symbol table + // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. + // Note: that the memberFlags come from previous iteration. + if (!(memberFlags & 128 /* Static */)) { + copySymbols(getSymbolOfNode(location).members, meaning & 793056 /* Type */); + } + break; + case 173 /* FunctionExpression */: + var funcName = location.name; + if (funcName) { + copySymbol(location.symbol, meaning); + } + break; + } + if (ts.introducesArgumentsExoticObject(location)) { + copySymbol(argumentsSymbol, meaning); + } + memberFlags = location.flags; + location = location.parent; + } + copySymbols(globals, meaning); + } + /** + * Copy the given symbol into symbol tables if the symbol has the given meaning + * and it doesn't already existed in the symbol table + * @param key a key for storing in symbol table; if undefined, use symbol.name + * @param symbol the symbol to be added into symbol table + * @param meaning meaning of symbol to filter by before adding to symbol table + */ + function copySymbol(symbol, meaning) { + if (symbol.flags & meaning) { + var id = symbol.name; + // We will copy all symbol regardless of its reserved name because + // symbolsToArray will check whether the key is a reserved name and + // it will not copy symbol with reserved name to the array + if (!ts.hasProperty(symbols, id)) { + symbols[id] = symbol; + } + } + } + function copySymbols(source, meaning) { + if (meaning) { + for (var id in source) { + var symbol = source[id]; + copySymbol(symbol, meaning); + } + } + } + } + function isTypeDeclarationName(name) { + return name.kind === 69 /* Identifier */ && + isTypeDeclaration(name.parent) && + name.parent.name === name; + } + function isTypeDeclaration(node) { + switch (node.kind) { + case 137 /* TypeParameter */: + case 214 /* ClassDeclaration */: + case 215 /* InterfaceDeclaration */: + case 216 /* TypeAliasDeclaration */: + case 217 /* EnumDeclaration */: + return true; + } + } + // True if the given identifier is part of a type reference + function isTypeReferenceIdentifier(entityName) { + var node = entityName; + while (node.parent && node.parent.kind === 135 /* QualifiedName */) { + node = node.parent; + } + return node.parent && node.parent.kind === 151 /* TypeReference */; + } + function isHeritageClauseElementIdentifier(entityName) { + var node = entityName; + while (node.parent && node.parent.kind === 166 /* PropertyAccessExpression */) { + node = node.parent; + } + return node.parent && node.parent.kind === 188 /* ExpressionWithTypeArguments */; + } + function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { + while (nodeOnRightSide.parent.kind === 135 /* QualifiedName */) { + nodeOnRightSide = nodeOnRightSide.parent; + } + if (nodeOnRightSide.parent.kind === 221 /* ImportEqualsDeclaration */) { + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; + } + if (nodeOnRightSide.parent.kind === 227 /* ExportAssignment */) { + return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; + } + return undefined; + } + function isInRightSideOfImportOrExportAssignment(node) { + return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; + } + function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) { + if (ts.isDeclarationName(entityName)) { + return getSymbolOfNode(entityName.parent); + } + if (entityName.parent.kind === 227 /* ExportAssignment */) { + return resolveEntityName(entityName, + /*all meanings*/ 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); + } + if (entityName.kind !== 166 /* PropertyAccessExpression */) { + if (isInRightSideOfImportOrExportAssignment(entityName)) { + // Since we already checked for ExportAssignment, this really could only be an Import + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName); + } + } + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + if (isHeritageClauseElementIdentifier(entityName)) { + var meaning = 0 /* None */; + // In an interface or class, we're definitely interested in a type. + if (entityName.parent.kind === 188 /* ExpressionWithTypeArguments */) { + meaning = 793056 /* Type */; + // In a class 'extends' clause we are also looking for a value. + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + meaning |= 107455 /* Value */; + } + } + else { + meaning = 1536 /* Namespace */; + } + meaning |= 8388608 /* Alias */; + return resolveEntityName(entityName, meaning); + } + else if ((entityName.parent.kind === 235 /* JsxOpeningElement */) || + (entityName.parent.kind === 234 /* JsxSelfClosingElement */) || + (entityName.parent.kind === 237 /* JsxClosingElement */)) { + return getJsxElementTagSymbol(entityName.parent); + } + else if (ts.isExpression(entityName)) { + if (ts.nodeIsMissing(entityName)) { + // Missing entity name. + return undefined; + } + if (entityName.kind === 69 /* Identifier */) { + // Include aliases in the meaning, this ensures that we do not follow aliases to where they point and instead + // return the alias symbol. + var meaning = 107455 /* Value */ | 8388608 /* Alias */; + return resolveEntityName(entityName, meaning); + } + else if (entityName.kind === 166 /* PropertyAccessExpression */) { + var symbol = getNodeLinks(entityName).resolvedSymbol; + if (!symbol) { + checkPropertyAccessExpression(entityName); + } + return getNodeLinks(entityName).resolvedSymbol; + } + else if (entityName.kind === 135 /* QualifiedName */) { + var symbol = getNodeLinks(entityName).resolvedSymbol; + if (!symbol) { + checkQualifiedName(entityName); + } + return getNodeLinks(entityName).resolvedSymbol; + } + } + else if (isTypeReferenceIdentifier(entityName)) { + var meaning = entityName.parent.kind === 151 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */; + // Include aliases in the meaning, this ensures that we do not follow aliases to where they point and instead + // return the alias symbol. + meaning |= 8388608 /* Alias */; + return resolveEntityName(entityName, meaning); + } + else if (entityName.parent.kind === 238 /* JsxAttribute */) { + return getJsxAttributePropertySymbol(entityName.parent); + } + if (entityName.parent.kind === 150 /* TypePredicate */) { + return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); + } + // Do we want to return undefined here? + return undefined; + } + function getSymbolAtLocation(node) { + if (isInsideWithStatementBody(node)) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + if (ts.isDeclarationName(node)) { + // This is a declaration, call getSymbolOfNode + return getSymbolOfNode(node.parent); + } + if (node.kind === 69 /* Identifier */) { + if (isInRightSideOfImportOrExportAssignment(node)) { + return node.parent.kind === 227 /* ExportAssignment */ + ? getSymbolOfEntityNameOrPropertyAccessExpression(node) + : getSymbolOfPartOfRightHandSideOfImportEquals(node); + } + else if (node.parent.kind === 163 /* BindingElement */ && + node.parent.parent.kind === 161 /* ObjectBindingPattern */ && + node === node.parent.propertyName) { + var typeOfPattern = getTypeOfNode(node.parent.parent); + var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); + if (propertyDeclaration) { + return propertyDeclaration; + } + } + } + switch (node.kind) { + case 69 /* Identifier */: + case 166 /* PropertyAccessExpression */: + case 135 /* QualifiedName */: + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + case 97 /* ThisKeyword */: + case 95 /* SuperKeyword */: + var type = ts.isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); + return type.symbol; + case 121 /* ConstructorKeyword */: + // constructor keyword for an overload, should take us to the definition if it exist + var constructorDeclaration = node.parent; + if (constructorDeclaration && constructorDeclaration.kind === 144 /* Constructor */) { + return constructorDeclaration.parent.symbol; + } + return undefined; + case 9 /* StringLiteral */: + // External module name in an import declaration + if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && + ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || + ((node.parent.kind === 222 /* ImportDeclaration */ || node.parent.kind === 228 /* ExportDeclaration */) && + node.parent.moduleSpecifier === node)) { + return resolveExternalModuleName(node, node); + } + // Fall through + case 8 /* NumericLiteral */: + // index access + if (node.parent.kind === 167 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { + var objectType = checkExpression(node.parent.expression); + if (objectType === unknownType) + return undefined; + var apparentType = getApparentType(objectType); + if (apparentType === unknownType) + return undefined; + return getPropertyOfType(apparentType, node.text); + } + break; + } + return undefined; + } + function getShorthandAssignmentValueSymbol(location) { + // The function returns a value symbol of an identifier in the short-hand property assignment. + // This is necessary as an identifier in short-hand property assignment can contains two meaning: + // property name and property value. + if (location && location.kind === 246 /* ShorthandPropertyAssignment */) { + return resolveEntityName(location.name, 107455 /* Value */); + } + return undefined; + } + function getTypeOfNode(node) { + if (isInsideWithStatementBody(node)) { + // We cannot answer semantic questions within a with block, do not proceed any further + return unknownType; + } + if (ts.isTypeNode(node)) { + return getTypeFromTypeNode(node); + } + if (ts.isExpression(node)) { + return getTypeOfExpression(node); + } + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the + // extends clause of a class. We handle that case here. + return getBaseTypes(getDeclaredTypeOfSymbol(getSymbolOfNode(node.parent.parent)))[0]; + } + if (isTypeDeclaration(node)) { + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration + var symbol = getSymbolOfNode(node); + return getDeclaredTypeOfSymbol(symbol); + } + if (isTypeDeclarationName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol && getDeclaredTypeOfSymbol(symbol); + } + if (ts.isDeclaration(node)) { + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration + var symbol = getSymbolOfNode(node); + return getTypeOfSymbol(symbol); + } + if (ts.isDeclarationName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol && getTypeOfSymbol(symbol); + } + if (ts.isBindingPattern(node)) { + return getTypeForVariableLikeDeclaration(node.parent); + } + if (isInRightSideOfImportOrExportAssignment(node)) { + var symbol = getSymbolAtLocation(node); + var declaredType = symbol && getDeclaredTypeOfSymbol(symbol); + return declaredType !== unknownType ? declaredType : getTypeOfSymbol(symbol); + } + return unknownType; + } + function getTypeOfExpression(expr) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { + expr = expr.parent; + } + return checkExpression(expr); + } + /** + * Gets either the static or instance type of a class element, based on + * whether the element is declared as "static". + */ + function getParentTypeOfClassElement(node) { + var classSymbol = getSymbolOfNode(node.parent); + return node.flags & 128 /* Static */ + ? getTypeOfSymbol(classSymbol) + : getDeclaredTypeOfSymbol(classSymbol); + } + // Return the list of properties of the given type, augmented with properties from Function + // if the type has call or construct signatures + function getAugmentedPropertiesOfType(type) { + type = getApparentType(type); + var propsByName = createSymbolTable(getPropertiesOfType(type)); + if (getSignaturesOfType(type, 0 /* Call */).length || getSignaturesOfType(type, 1 /* Construct */).length) { + ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + if (!ts.hasProperty(propsByName, p.name)) { + propsByName[p.name] = p; + } + }); + } + return getNamedMembers(propsByName); + } + function getRootSymbols(symbol) { + if (symbol.flags & 268435456 /* SyntheticProperty */) { + var symbols = []; + var name_15 = symbol.name; + ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { + var symbol = getPropertyOfType(t, name_15); + if (symbol) { + symbols.push(symbol); + } + }); + return symbols; + } + else if (symbol.flags & 67108864 /* Transient */) { + var target = getSymbolLinks(symbol).target; + if (target) { + return [target]; + } + } + return [symbol]; + } + // Emitter support + // When resolved as an expression identifier, if the given node references an exported entity, return the declaration + // node of the exported entity's container. Otherwise, return undefined. + function getReferencedExportContainer(node) { + var symbol = getReferencedValueSymbol(node); + if (symbol) { + if (symbol.flags & 1048576 /* ExportValue */) { + // If we reference an exported entity within the same module declaration, then whether + // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the + // kinds that we do NOT prefix. + var exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (exportSymbol.flags & 944 /* ExportHasLocal */) { + return undefined; + } + symbol = exportSymbol; + } + var parentSymbol = getParentOfSymbol(symbol); + if (parentSymbol) { + if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 248 /* SourceFile */) { + return parentSymbol.valueDeclaration; + } + for (var n = node.parent; n; n = n.parent) { + if ((n.kind === 218 /* ModuleDeclaration */ || n.kind === 217 /* EnumDeclaration */) && getSymbolOfNode(n) === parentSymbol) { + return n; + } + } + } + } + } + // When resolved as an expression identifier, if the given node references an import, return the declaration of + // that import. Otherwise, return undefined. + function getReferencedImportDeclaration(node) { + var symbol = getReferencedValueSymbol(node); + return symbol && symbol.flags & 8388608 /* Alias */ ? getDeclarationOfAliasSymbol(symbol) : undefined; + } + function isStatementWithLocals(node) { + switch (node.kind) { + case 192 /* Block */: + case 220 /* CaseBlock */: + case 199 /* ForStatement */: + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + return true; + } + return false; + } + function isNestedRedeclarationSymbol(symbol) { + if (symbol.flags & 418 /* BlockScoped */) { + var links = getSymbolLinks(symbol); + if (links.isNestedRedeclaration === undefined) { + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + links.isNestedRedeclaration = isStatementWithLocals(container) && + !!resolveName(container.parent, symbol.name, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + } + return links.isNestedRedeclaration; + } + return false; + } + // When resolved as an expression identifier, if the given node references a nested block scoped entity with + // a name that hides an existing name, return the declaration of that entity. Otherwise, return undefined. + function getReferencedNestedRedeclaration(node) { + var symbol = getReferencedValueSymbol(node); + return symbol && isNestedRedeclarationSymbol(symbol) ? symbol.valueDeclaration : undefined; + } + // Return true if the given node is a declaration of a nested block scoped entity with a name that hides an + // existing name. + function isNestedRedeclaration(node) { + return isNestedRedeclarationSymbol(getSymbolOfNode(node)); + } + function isValueAliasDeclaration(node) { + switch (node.kind) { + case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportClause */: + case 224 /* NamespaceImport */: + case 226 /* ImportSpecifier */: + case 230 /* ExportSpecifier */: + return isAliasResolvedToValue(getSymbolOfNode(node)); + case 228 /* ExportDeclaration */: + var exportClause = node.exportClause; + return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); + case 227 /* ExportAssignment */: + return node.expression && node.expression.kind === 69 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; + } + return false; + } + function isTopLevelValueImportEqualsWithEntityName(node) { + if (node.parent.kind !== 248 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + // parent is not source file or it is not reference to internal module + return false; + } + var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); + return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); + } + function isAliasResolvedToValue(symbol) { + var target = resolveAlias(symbol); + if (target === unknownSymbol && compilerOptions.isolatedModules) { + return true; + } + // const enums and modules that contain only const enums are not considered values from the emit perespective + // unless 'preserveConstEnums' option is set to true + return target !== unknownSymbol && + target && + target.flags & 107455 /* Value */ && + (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + } + function isConstEnumOrConstEnumOnlyModule(s) { + return isConstEnumSymbol(s) || s.constEnumOnlyModule; + } + function isReferencedAliasDeclaration(node, checkChildren) { + if (ts.isAliasSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + if (getSymbolLinks(symbol).referenced) { + return true; + } + } + if (checkChildren) { + return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); + } + return false; + } + function isImplementationOfOverload(node) { + if (ts.nodeIsPresent(node.body)) { + var symbol = getSymbolOfNode(node); + var signaturesOfSymbol = getSignaturesOfSymbol(symbol); + // If this function body corresponds to function with multiple signature, it is implementation of overload + // e.g.: function foo(a: string): string; + // function foo(a: number): number; + // function foo(a: any) { // This is implementation of the overloads + // return a; + // } + return signaturesOfSymbol.length > 1 || + // If there is single signature for the symbol, it is overload if that signature isn't coming from the node + // e.g.: function foo(a: string): string; + // function foo(a: any) { // This is implementation of the overloads + // return a; + // } + (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); + } + return false; + } + function getNodeCheckFlags(node) { + return getNodeLinks(node).flags; + } + function getEnumMemberValue(node) { + computeEnumMemberValues(node.parent); + return getNodeLinks(node).enumMemberValue; + } + function getConstantValue(node) { + if (node.kind === 247 /* EnumMember */) { + return getEnumMemberValue(node); + } + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol && (symbol.flags & 8 /* EnumMember */)) { + // inline property\index accesses only for const enums + if (ts.isConstEnumDeclaration(symbol.valueDeclaration.parent)) { + return getEnumMemberValue(symbol.valueDeclaration); + } + } + return undefined; + } + function isFunctionType(type) { + return type.flags & 80896 /* ObjectType */ && getSignaturesOfType(type, 0 /* Call */).length > 0; + } + function getTypeReferenceSerializationKind(typeName) { + // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. + var valueSymbol = resolveEntityName(typeName, 107455 /* Value */, /*ignoreErrors*/ true); + var constructorType = valueSymbol ? getTypeOfSymbol(valueSymbol) : undefined; + if (constructorType && isConstructorType(constructorType)) { + return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; + } + // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. + var typeSymbol = resolveEntityName(typeName, 793056 /* Type */, /*ignoreErrors*/ true); + // We might not be able to resolve type symbol so use unknown type in that case (eg error case) + if (!typeSymbol) { + return ts.TypeReferenceSerializationKind.ObjectType; + } + var type = getDeclaredTypeOfSymbol(typeSymbol); + if (type === unknownType) { + return ts.TypeReferenceSerializationKind.Unknown; + } + else if (type.flags & 1 /* Any */) { + return ts.TypeReferenceSerializationKind.ObjectType; + } + else if (allConstituentTypesHaveKind(type, 16 /* Void */)) { + return ts.TypeReferenceSerializationKind.VoidType; + } + else if (allConstituentTypesHaveKind(type, 8 /* Boolean */)) { + return ts.TypeReferenceSerializationKind.BooleanType; + } + else if (allConstituentTypesHaveKind(type, 132 /* NumberLike */)) { + return ts.TypeReferenceSerializationKind.NumberLikeType; + } + else if (allConstituentTypesHaveKind(type, 258 /* StringLike */)) { + return ts.TypeReferenceSerializationKind.StringLikeType; + } + else if (allConstituentTypesHaveKind(type, 8192 /* Tuple */)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else if (allConstituentTypesHaveKind(type, 16777216 /* ESSymbol */)) { + return ts.TypeReferenceSerializationKind.ESSymbolType; + } + else if (isFunctionType(type)) { + return ts.TypeReferenceSerializationKind.TypeWithCallSignature; + } + else if (isArrayType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else { + return ts.TypeReferenceSerializationKind.ObjectType; + } + } + function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { + // Get type of the symbol if this is the valid symbol otherwise get type at location + var symbol = getSymbolOfNode(declaration); + var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) + ? getTypeOfSymbol(symbol) + : unknownType; + getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + } + function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { + var signature = getSignatureFromDeclaration(signatureDeclaration); + getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); + } + function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { + var type = getTypeOfExpression(expr); + getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + } + function hasGlobalName(name) { + return ts.hasProperty(globals, name); + } + function getReferencedValueSymbol(reference) { + return getNodeLinks(reference).resolvedSymbol || + resolveName(reference, reference.text, 107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */, + /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); + } + function getReferencedValueDeclaration(reference) { + ts.Debug.assert(!ts.nodeIsSynthesized(reference)); + var symbol = getReferencedValueSymbol(reference); + return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + } + function instantiateSingleCallFunctionType(functionType, typeArguments) { + if (functionType === unknownType) { + return unknownType; + } + var signature = getSingleCallSignature(functionType); + if (!signature) { + return unknownType; + } + var instantiatedSignature = getSignatureInstantiation(signature, typeArguments); + return getOrCreateTypeFromSignature(instantiatedSignature); + } + function createResolver() { + return { + getReferencedExportContainer: getReferencedExportContainer, + getReferencedImportDeclaration: getReferencedImportDeclaration, + getReferencedNestedRedeclaration: getReferencedNestedRedeclaration, + isNestedRedeclaration: isNestedRedeclaration, + isValueAliasDeclaration: isValueAliasDeclaration, + hasGlobalName: hasGlobalName, + isReferencedAliasDeclaration: isReferencedAliasDeclaration, + getNodeCheckFlags: getNodeCheckFlags, + isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, + isDeclarationVisible: isDeclarationVisible, + isImplementationOfOverload: isImplementationOfOverload, + writeTypeOfDeclaration: writeTypeOfDeclaration, + writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, + writeTypeOfExpression: writeTypeOfExpression, + isSymbolAccessible: isSymbolAccessible, + isEntityNameVisible: isEntityNameVisible, + getConstantValue: getConstantValue, + collectLinkedAliases: collectLinkedAliases, + getReferencedValueDeclaration: getReferencedValueDeclaration, + getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, + isOptionalParameter: isOptionalParameter + }; + } + function initializeTypeChecker() { + // Bind all source files and propagate errors + ts.forEach(host.getSourceFiles(), function (file) { + ts.bindSourceFile(file); + }); + // Initialize global symbol table + ts.forEach(host.getSourceFiles(), function (file) { + if (!ts.isExternalModule(file)) { + mergeSymbolTable(globals, file.locals); + } + }); + // Initialize special symbols + getSymbolLinks(undefinedSymbol).type = undefinedType; + getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments"); + getSymbolLinks(unknownSymbol).type = unknownType; + globals[undefinedSymbol.name] = undefinedSymbol; + // Initialize special types + globalArrayType = getGlobalType("Array", /*arity*/ 1); + globalObjectType = getGlobalType("Object"); + globalFunctionType = getGlobalType("Function"); + globalStringType = getGlobalType("String"); + globalNumberType = getGlobalType("Number"); + globalBooleanType = getGlobalType("Boolean"); + globalRegExpType = getGlobalType("RegExp"); + jsxElementType = getExportedTypeFromNamespace("JSX", JsxNames.Element); + getGlobalClassDecoratorType = ts.memoize(function () { return getGlobalType("ClassDecorator"); }); + getGlobalPropertyDecoratorType = ts.memoize(function () { return getGlobalType("PropertyDecorator"); }); + getGlobalMethodDecoratorType = ts.memoize(function () { return getGlobalType("MethodDecorator"); }); + getGlobalParameterDecoratorType = ts.memoize(function () { return getGlobalType("ParameterDecorator"); }); + getGlobalTypedPropertyDescriptorType = ts.memoize(function () { return getGlobalType("TypedPropertyDescriptor", /*arity*/ 1); }); + getGlobalPromiseType = ts.memoize(function () { return getGlobalType("Promise", /*arity*/ 1); }); + tryGetGlobalPromiseType = ts.memoize(function () { return getGlobalSymbol("Promise", 793056 /* Type */, /*diagnostic*/ undefined) && getGlobalPromiseType(); }); + getGlobalPromiseLikeType = ts.memoize(function () { return getGlobalType("PromiseLike", /*arity*/ 1); }); + getInstantiatedGlobalPromiseLikeType = ts.memoize(createInstantiatedPromiseLikeType); + getGlobalPromiseConstructorSymbol = ts.memoize(function () { return getGlobalValueSymbol("Promise"); }); + getGlobalPromiseConstructorLikeType = ts.memoize(function () { return getGlobalType("PromiseConstructorLike"); }); + getGlobalThenableType = ts.memoize(createThenableType); + // If we're in ES6 mode, load the TemplateStringsArray. + // Otherwise, default to 'unknown' for the purposes of type checking in LS scenarios. + if (languageVersion >= 2 /* ES6 */) { + globalTemplateStringsArrayType = getGlobalType("TemplateStringsArray"); + globalESSymbolType = getGlobalType("Symbol"); + globalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol"); + globalIterableType = getGlobalType("Iterable", /*arity*/ 1); + globalIteratorType = getGlobalType("Iterator", /*arity*/ 1); + globalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1); + } + else { + globalTemplateStringsArrayType = unknownType; + // Consider putting Symbol interface in lib.d.ts. On the plus side, putting it in lib.d.ts would make it + // extensible for Polyfilling Symbols. But putting it into lib.d.ts could also break users that have + // a global Symbol already, particularly if it is a class. + globalESSymbolType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + globalESSymbolConstructorSymbol = undefined; + globalIterableType = emptyGenericType; + globalIteratorType = emptyGenericType; + globalIterableIteratorType = emptyGenericType; + } + anyArrayType = createArrayType(anyType); + } + function createInstantiatedPromiseLikeType() { + var promiseLikeType = getGlobalPromiseLikeType(); + if (promiseLikeType !== emptyGenericType) { + return createTypeReference(promiseLikeType, [anyType]); + } + return emptyObjectType; + } + function createThenableType() { + // build the thenable type that is used to verify against a non-promise "thenable" operand to `await`. + var thenPropertySymbol = createSymbol(67108864 /* Transient */ | 4 /* Property */, "then"); + getSymbolLinks(thenPropertySymbol).type = globalFunctionType; + var thenableType = createObjectType(65536 /* Anonymous */); + thenableType.properties = [thenPropertySymbol]; + thenableType.members = createSymbolTable(thenableType.properties); + thenableType.callSignatures = []; + thenableType.constructSignatures = []; + return thenableType; + } + // GRAMMAR CHECKING + function checkGrammarDecorators(node) { + if (!node.decorators) { + return false; + } + if (!ts.nodeCanBeDecorated(node)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } + else if (node.kind === 145 /* GetAccessor */ || node.kind === 146 /* SetAccessor */) { + var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); + } + } + return false; + } + function checkGrammarModifiers(node) { + switch (node.kind) { + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 144 /* Constructor */: + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 149 /* IndexSignature */: + case 218 /* ModuleDeclaration */: + case 222 /* ImportDeclaration */: + case 221 /* ImportEqualsDeclaration */: + case 228 /* ExportDeclaration */: + case 227 /* ExportAssignment */: + case 138 /* Parameter */: + break; + case 213 /* FunctionDeclaration */: + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118 /* AsyncKeyword */) && + node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 248 /* SourceFile */) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 214 /* ClassDeclaration */: + case 215 /* InterfaceDeclaration */: + case 193 /* VariableStatement */: + case 216 /* TypeAliasDeclaration */: + if (node.modifiers && node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 248 /* SourceFile */) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + case 217 /* EnumDeclaration */: + if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74 /* ConstKeyword */) && + node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 248 /* SourceFile */) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + break; + default: + return false; + } + if (!node.modifiers) { + return; + } + var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync; + var flags = 0; + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + switch (modifier.kind) { + case 112 /* PublicKeyword */: + case 111 /* ProtectedKeyword */: + case 110 /* PrivateKeyword */: + var text = void 0; + if (modifier.kind === 112 /* PublicKeyword */) { + text = "public"; + } + else if (modifier.kind === 111 /* ProtectedKeyword */) { + text = "protected"; + lastProtected = modifier; + } + else { + text = "private"; + lastPrivate = modifier; + } + if (flags & 112 /* AccessibilityModifier */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); + } + else if (flags & 128 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); + } + else if (flags & 512 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); + } + else if (node.parent.kind === 219 /* ModuleBlock */ || node.parent.kind === 248 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); + } + else if (flags & 256 /* Abstract */) { + if (modifier.kind === 110 /* PrivateKeyword */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); + } + else { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); + } + } + flags |= ts.modifierToFlag(modifier.kind); + break; + case 113 /* StaticKeyword */: + if (flags & 128 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); + } + else if (flags & 512 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); + } + else if (node.parent.kind === 219 /* ModuleBlock */ || node.parent.kind === 248 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, "static"); + } + else if (node.kind === 138 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); + } + else if (flags & 256 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + flags |= 128 /* Static */; + lastStatic = modifier; + break; + case 82 /* ExportKeyword */: + if (flags & 1 /* Export */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); + } + else if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); + } + else if (flags & 256 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); + } + else if (flags & 512 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); + } + else if (node.parent.kind === 214 /* ClassDeclaration */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); + } + else if (node.kind === 138 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); + } + flags |= 1 /* Export */; + break; + case 122 /* DeclareKeyword */: + if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); + } + else if (flags & 512 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.parent.kind === 214 /* ClassDeclaration */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); + } + else if (node.kind === 138 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); + } + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 219 /* ModuleBlock */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); + } + flags |= 2 /* Ambient */; + lastDeclare = modifier; + break; + case 115 /* AbstractKeyword */: + if (flags & 256 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); + } + if (node.kind !== 214 /* ClassDeclaration */) { + if (node.kind !== 143 /* MethodDeclaration */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_or_method_declaration); + } + if (!(node.parent.kind === 214 /* ClassDeclaration */ && node.parent.flags & 256 /* Abstract */)) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); + } + if (flags & 128 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + if (flags & 32 /* Private */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); + } + } + flags |= 256 /* Abstract */; + break; + case 118 /* AsyncKeyword */: + if (flags & 512 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); + } + else if (flags & 2 /* Ambient */ || ts.isInAmbientContext(node.parent)) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.kind === 138 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); + } + flags |= 512 /* Async */; + lastAsync = modifier; + break; + } + } + if (node.kind === 144 /* Constructor */) { + if (flags & 128 /* Static */) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); + } + if (flags & 256 /* Abstract */) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); + } + else if (flags & 64 /* Protected */) { + return grammarErrorOnNode(lastProtected, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "protected"); + } + else if (flags & 32 /* Private */) { + return grammarErrorOnNode(lastPrivate, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "private"); + } + else if (flags & 512 /* Async */) { + return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); + } + return; + } + else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); + } + else if (node.kind === 138 /* Parameter */ && (flags & 112 /* AccessibilityModifier */) && ts.isBindingPattern(node.name)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); + } + if (flags & 512 /* Async */) { + return checkGrammarAsyncModifier(node, lastAsync); + } + } + function checkGrammarAsyncModifier(node, asyncModifier) { + if (languageVersion < 2 /* ES6 */) { + return grammarErrorOnNode(asyncModifier, ts.Diagnostics.Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher); + } + switch (node.kind) { + case 143 /* MethodDeclaration */: + case 213 /* FunctionDeclaration */: + case 173 /* FunctionExpression */: + case 174 /* ArrowFunction */: + if (!node.asteriskToken) { + return false; + } + break; + } + return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); + } + function checkGrammarForDisallowedTrailingComma(list) { + if (list && list.hasTrailingComma) { + var start = list.end - ",".length; + var end = list.end; + var sourceFile = ts.getSourceFileOfNode(list[0]); + return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); + } + } + function checkGrammarTypeParameterList(node, typeParameters, file) { + if (checkGrammarForDisallowedTrailingComma(typeParameters)) { + return true; + } + if (typeParameters && typeParameters.length === 0) { + var start = typeParameters.pos - "<".length; + var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; + return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); + } + } + function checkGrammarParameterList(parameters) { + if (checkGrammarForDisallowedTrailingComma(parameters)) { + return true; + } + var seenOptionalParameter = false; + var parameterCount = parameters.length; + for (var i = 0; i < parameterCount; i++) { + var parameter = parameters[i]; + if (parameter.dotDotDotToken) { + if (i !== (parameterCount - 1)) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + if (ts.isBindingPattern(parameter.name)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); + } + } + else if (parameter.questionToken) { + seenOptionalParameter = true; + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); + } + } + else if (seenOptionalParameter && !parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); + } + } + } + function checkGrammarFunctionLikeDeclaration(node) { + // Prevent cascading error by short-circuit + var file = ts.getSourceFileOfNode(node); + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node, node.typeParameters, file) || + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + } + function checkGrammarArrowFunction(node, file) { + if (node.kind === 174 /* ArrowFunction */) { + var arrowFunction = node; + var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; + if (startLine !== endLine) { + return grammarErrorOnNode(arrowFunction.equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow); + } + } + return false; + } + function checkGrammarIndexSignatureParameters(node) { + var parameter = node.parameters[0]; + if (node.parameters.length !== 1) { + if (parameter) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + else { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + } + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); + } + if (parameter.flags & 2035 /* Modifier */) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer); + } + if (!parameter.type) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); + } + if (parameter.type.kind !== 130 /* StringKeyword */ && parameter.type.kind !== 128 /* NumberKeyword */) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + } + if (!node.type) { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); + } + } + function checkGrammarForIndexSignatureModifier(node) { + if (node.flags & 2035 /* Modifier */) { + grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_not_permitted_on_index_signature_members); + } + } + function checkGrammarIndexSignature(node) { + // Prevent cascading error by short-circuit + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node) || checkGrammarForIndexSignatureModifier(node); + } + function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { + if (typeArguments && typeArguments.length === 0) { + var sourceFile = ts.getSourceFileOfNode(node); + var start = typeArguments.pos - "<".length; + var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; + return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); + } + } + function checkGrammarTypeArguments(node, typeArguments) { + return checkGrammarForDisallowedTrailingComma(typeArguments) || + checkGrammarForAtLeastOneTypeArgument(node, typeArguments); + } + function checkGrammarForOmittedArgument(node, args) { + if (args) { + var sourceFile = ts.getSourceFileOfNode(node); + for (var _i = 0; _i < args.length; _i++) { + var arg = args[_i]; + if (arg.kind === 187 /* OmittedExpression */) { + return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); + } + } + } + } + function checkGrammarArguments(node, args) { + return checkGrammarForDisallowedTrailingComma(args) || + checkGrammarForOmittedArgument(node, args); + } + function checkGrammarHeritageClause(node) { + var types = node.types; + if (checkGrammarForDisallowedTrailingComma(types)) { + return true; + } + if (types && types.length === 0) { + var listType = ts.tokenToString(node.token); + var sourceFile = ts.getSourceFileOfNode(node); + return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); + } + } + function checkGrammarClassDeclarationHeritageClauses(node) { + var seenExtendsClause = false; + var seenImplementsClause = false; + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 83 /* ExtendsKeyword */) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause); + } + if (heritageClause.types.length > 1) { + return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 106 /* ImplementsKeyword */); + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); + } + seenImplementsClause = true; + } + // Grammar checking heritageClause inside class declaration + checkGrammarHeritageClause(heritageClause); + } + } + } + function checkGrammarInterfaceDeclaration(node) { + var seenExtendsClause = false; + if (node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 83 /* ExtendsKeyword */) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 106 /* ImplementsKeyword */); + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); + } + // Grammar checking heritageClause inside class declaration + checkGrammarHeritageClause(heritageClause); + } + } + return false; + } + function checkGrammarComputedPropertyName(node) { + // If node is not a computedPropertyName, just skip the grammar checking + if (node.kind !== 136 /* ComputedPropertyName */) { + return false; + } + var computedPropertyName = node; + if (computedPropertyName.expression.kind === 181 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 24 /* CommaToken */) { + return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); + } + } + function checkGrammarForGenerator(node) { + if (node.asteriskToken) { + ts.Debug.assert(node.kind === 213 /* FunctionDeclaration */ || + node.kind === 173 /* FunctionExpression */ || + node.kind === 143 /* MethodDeclaration */); + if (ts.isInAmbientContext(node)) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); + } + if (!node.body) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); + } + if (languageVersion < 2 /* ES6 */) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_only_available_when_targeting_ECMAScript_6_or_higher); + } + } + } + function checkGrammarForInvalidQuestionMark(node, questionToken, message) { + if (questionToken) { + return grammarErrorOnNode(questionToken, message); + } + } + function checkGrammarObjectLiteralExpression(node, inDestructuring) { + var seen = {}; + var Property = 1; + var GetAccessor = 2; + var SetAccesor = 4; + var GetOrSetAccessor = GetAccessor | SetAccesor; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + var name_16 = prop.name; + if (prop.kind === 187 /* OmittedExpression */ || + name_16.kind === 136 /* ComputedPropertyName */) { + // If the name is not a ComputedPropertyName, the grammar checking will skip it + checkGrammarComputedPropertyName(name_16); + continue; + } + if (prop.kind === 246 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern + // outside of destructuring it is a syntax error + return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + } + // ECMA-262 11.1.5 Object Initialiser + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = void 0; + if (prop.kind === 245 /* PropertyAssignment */ || prop.kind === 246 /* ShorthandPropertyAssignment */) { + // Grammar checking for computedPropertName and shorthandPropertyAssignment + checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name_16.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(name_16); + } + currentKind = Property; + } + else if (prop.kind === 143 /* MethodDeclaration */) { + currentKind = Property; + } + else if (prop.kind === 145 /* GetAccessor */) { + currentKind = GetAccessor; + } + else if (prop.kind === 146 /* SetAccessor */) { + currentKind = SetAccesor; + } + else { + ts.Debug.fail("Unexpected syntax kind:" + prop.kind); + } + if (!ts.hasProperty(seen, name_16.text)) { + seen[name_16.text] = currentKind; + } + else { + var existingKind = seen[name_16.text]; + if (currentKind === Property && existingKind === Property) { + continue; + } + else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { + if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { + seen[name_16.text] = currentKind | existingKind; + } + else { + return grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + } + } + else { + return grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + } + } + } + } + function checkGrammarJsxElement(node) { + var seen = {}; + for (var _i = 0, _a = node.attributes; _i < _a.length; _i++) { + var attr = _a[_i]; + if (attr.kind === 239 /* JsxSpreadAttribute */) { + continue; + } + var jsxAttr = attr; + var name_17 = jsxAttr.name; + if (!ts.hasProperty(seen, name_17.text)) { + seen[name_17.text] = true; + } + else { + return grammarErrorOnNode(name_17, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + } + var initializer = jsxAttr.initializer; + if (initializer && initializer.kind === 240 /* JsxExpression */ && !initializer.expression) { + return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); + } + } + } + function checkGrammarForInOrForOfStatement(forInOrOfStatement) { + if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { + return true; + } + if (forInOrOfStatement.initializer.kind === 212 /* VariableDeclarationList */) { + var variableList = forInOrOfStatement.initializer; + if (!checkGrammarVariableDeclarationList(variableList)) { + if (variableList.declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 200 /* ForInStatement */ + ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement + : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; + return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); + } + var firstDeclaration = variableList.declarations[0]; + if (firstDeclaration.initializer) { + var diagnostic = forInOrOfStatement.kind === 200 /* ForInStatement */ + ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer + : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; + return grammarErrorOnNode(firstDeclaration.name, diagnostic); + } + if (firstDeclaration.type) { + var diagnostic = forInOrOfStatement.kind === 200 /* ForInStatement */ + ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation + : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; + return grammarErrorOnNode(firstDeclaration, diagnostic); + } + } + } + return false; + } + function checkGrammarAccessor(accessor) { + var kind = accessor.kind; + if (languageVersion < 1 /* ES5 */) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); + } + else if (ts.isInAmbientContext(accessor)) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); + } + else if (accessor.body === undefined) { + return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + else if (accessor.typeParameters) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); + } + else if (kind === 145 /* GetAccessor */ && accessor.parameters.length) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_get_accessor_cannot_have_parameters); + } + else if (kind === 146 /* SetAccessor */) { + if (accessor.type) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); + } + else if (accessor.parameters.length !== 1) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); + } + else { + var parameter = accessor.parameters[0]; + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); + } + else if (parameter.flags & 2035 /* Modifier */) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); + } + else if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter); + } + else if (parameter.initializer) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer); + } + } + } + } + function checkGrammarForNonSymbolComputedProperty(node, message) { + if (node.kind === 136 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(node.expression)) { + return grammarErrorOnNode(node, message); + } + } + function checkGrammarMethod(node) { + if (checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) || + checkGrammarFunctionLikeDeclaration(node) || + checkGrammarForGenerator(node)) { + return true; + } + if (node.parent.kind === 165 /* ObjectLiteralExpression */) { + if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { + return true; + } + else if (node.body === undefined) { + return grammarErrorAtPos(getSourceFile(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + } + if (ts.isClassLike(node.parent)) { + if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { + return true; + } + // Technically, computed properties in ambient contexts is disallowed + // for property declarations and accessors too, not just methods. + // However, property declarations disallow computed names in general, + // and accessors are not allowed in ambient contexts in general, + // so this error only really matters for methods. + if (ts.isInAmbientContext(node)) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol); + } + else if (!node.body) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); + } + } + else if (node.parent.kind === 215 /* InterfaceDeclaration */) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); + } + else if (node.parent.kind === 155 /* TypeLiteral */) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); + } + } + function isIterationStatement(node, lookInLabeledStatements) { + switch (node.kind) { + case 199 /* ForStatement */: + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + case 197 /* DoStatement */: + case 198 /* WhileStatement */: + return true; + case 207 /* LabeledStatement */: + return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); + } + return false; + } + function checkGrammarBreakOrContinueStatement(node) { + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); + } + switch (current.kind) { + case 207 /* LabeledStatement */: + if (node.label && current.label.text === node.label.text) { + // found matching label - verify that label usage is correct + // continue can only target labels that are on iteration statements + var isMisplacedContinueLabel = node.kind === 202 /* ContinueStatement */ + && !isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); + if (isMisplacedContinueLabel) { + return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); + } + return false; + } + break; + case 206 /* SwitchStatement */: + if (node.kind === 203 /* BreakStatement */ && !node.label) { + // unlabeled break within switch statement - ok + return false; + } + break; + default: + if (isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) { + // unlabeled break or continue within iteration statement - ok + return false; + } + break; + } + current = current.parent; + } + if (node.label) { + var message = node.kind === 203 /* BreakStatement */ + ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement + : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + else { + var message = node.kind === 203 /* BreakStatement */ + ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement + : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + } + function checkGrammarBindingElement(node) { + if (node.dotDotDotToken) { + var elements = node.parent.elements; + if (node !== ts.lastOrUndefined(elements)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); + } + if (node.name.kind === 162 /* ArrayBindingPattern */ || node.name.kind === 161 /* ObjectBindingPattern */) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); + } + if (node.initializer) { + // Error on equals token which immediate precedes the initializer + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + } + } + function checkGrammarVariableDeclaration(node) { + if (node.parent.parent.kind !== 200 /* ForInStatement */ && node.parent.parent.kind !== 201 /* ForOfStatement */) { + if (ts.isInAmbientContext(node)) { + if (node.initializer) { + // Error on equals token which immediate precedes the initializer + var equalsTokenLength = "=".length; + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + else if (!node.initializer) { + if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); + } + if (ts.isConst(node)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); + } + } + } + var checkLetConstNames = languageVersion >= 2 /* ES6 */ && (ts.isLet(node) || ts.isConst(node)); + // 1. LexicalDeclaration : LetOrConst BindingList ; + // It is a Syntax Error if the BoundNames of BindingList contains "let". + // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding + // It is a Syntax Error if the BoundNames of ForDeclaration contains "let". + // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code + // and its Identifier is eval or arguments + return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); + } + function checkGrammarNameInLetOrConstDeclarations(name) { + if (name.kind === 69 /* Identifier */) { + if (name.text === "let") { + return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); + } + } + else { + var elements = name.elements; + for (var _i = 0; _i < elements.length; _i++) { + var element = elements[_i]; + if (element.kind !== 187 /* OmittedExpression */) { + checkGrammarNameInLetOrConstDeclarations(element.name); + } + } + } + } + function checkGrammarVariableDeclarationList(declarationList) { + var declarations = declarationList.declarations; + if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { + return true; + } + if (!declarationList.declarations.length) { + return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + } + } + function allowLetAndConstDeclarations(parent) { + switch (parent.kind) { + case 196 /* IfStatement */: + case 197 /* DoStatement */: + case 198 /* WhileStatement */: + case 205 /* WithStatement */: + case 199 /* ForStatement */: + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + return false; + case 207 /* LabeledStatement */: + return allowLetAndConstDeclarations(parent.parent); + } + return true; + } + function checkGrammarForDisallowedLetOrConstStatement(node) { + if (!allowLetAndConstDeclarations(node.parent)) { + if (ts.isLet(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); + } + else if (ts.isConst(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); + } + } + } + function isIntegerLiteral(expression) { + if (expression.kind === 179 /* PrefixUnaryExpression */) { + var unaryExpression = expression; + if (unaryExpression.operator === 35 /* PlusToken */ || unaryExpression.operator === 36 /* MinusToken */) { + expression = unaryExpression.operand; + } + } + if (expression.kind === 8 /* NumericLiteral */) { + // Allows for scientific notation since literalExpression.text was formed by + // coercing a number to a string. Sometimes this coercion can yield a string + // in scientific notation. + // We also don't need special logic for hex because a hex integer is converted + // to decimal when it is coerced. + return /^[0-9]+([eE]\+?[0-9]+)?$/.test(expression.text); + } + return false; + } + function hasParseDiagnostics(sourceFile) { + return sourceFile.parseDiagnostics.length > 0; + } + function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); + return true; + } + } + function grammarErrorAtPos(sourceFile, start, length, message, arg0, arg1, arg2) { + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); + return true; + } + } + function grammarErrorOnNode(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); + return true; + } + } + function isEvalOrArgumentsIdentifier(node) { + return node.kind === 69 /* Identifier */ && + (node.text === "eval" || node.text === "arguments"); + } + function checkGrammarConstructorTypeParameters(node) { + if (node.typeParameters) { + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarConstructorTypeAnnotation(node) { + if (node.type) { + return grammarErrorOnNode(node.type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarProperty(node) { + if (ts.isClassLike(node.parent)) { + if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional) || + checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { + return true; + } + } + else if (node.parent.kind === 215 /* InterfaceDeclaration */) { + if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { + return true; + } + } + else if (node.parent.kind === 155 /* TypeLiteral */) { + if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { + return true; + } + } + if (ts.isInAmbientContext(node) && node.initializer) { + return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { + // A declare modifier is required for any top level .d.ts declaration except export=, export default, + // interfaces and imports categories: + // + // DeclarationElement: + // ExportAssignment + // export_opt InterfaceDeclaration + // export_opt ImportDeclaration + // export_opt ExternalImportDeclaration + // export_opt AmbientDeclaration + // + if (node.kind === 215 /* InterfaceDeclaration */ || + node.kind === 222 /* ImportDeclaration */ || + node.kind === 221 /* ImportEqualsDeclaration */ || + node.kind === 228 /* ExportDeclaration */ || + node.kind === 227 /* ExportAssignment */ || + (node.flags & 2 /* Ambient */) || + (node.flags & (1 /* Export */ | 1024 /* Default */))) { + return false; + } + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); + } + function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isDeclaration(decl) || decl.kind === 193 /* VariableStatement */) { + if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { + return true; + } + } + } + } + function checkGrammarSourceFile(node) { + return ts.isInAmbientContext(node) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + } + function checkGrammarStatementInAmbientContext(node) { + if (ts.isInAmbientContext(node)) { + // An accessors is already reported about the ambient context + if (isAccessor(node.parent.kind)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = true; + } + // Find containing block which is either Block, ModuleBlock, SourceFile + var links = getNodeLinks(node); + if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } + // We are either parented by another statement, or some sort of block. + // If we're in a block, we only want to really report an error once + // to prevent noisyness. So use a bit on the block to indicate if + // this has already been reported, and don't report if it has. + // + if (node.parent.kind === 192 /* Block */ || node.parent.kind === 219 /* ModuleBlock */ || node.parent.kind === 248 /* SourceFile */) { + var links_1 = getNodeLinks(node.parent); + // Check if the containing block ever report this error + if (!links_1.hasReportedStatementInAmbientContext) { + return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + } + } + else { + } + } + } + function checkGrammarNumericLiteral(node) { + // Grammar checking + if (node.flags & 65536 /* OctalLiteral */ && languageVersion >= 1 /* ES5 */) { + return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); + } + } + function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); + return true; + } + } + } + ts.createTypeChecker = createTypeChecker; +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + function getDeclarationDiagnostics(host, resolver, targetSourceFile) { + var diagnostics = []; + var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); + emitDeclarations(host, resolver, diagnostics, jsFilePath, targetSourceFile); + return diagnostics; + } + ts.getDeclarationDiagnostics = getDeclarationDiagnostics; + function emitDeclarations(host, resolver, diagnostics, jsFilePath, root) { + var newLine = host.getNewLine(); + var compilerOptions = host.getCompilerOptions(); + var write; + var writeLine; + var increaseIndent; + var decreaseIndent; + var writeTextOfNode; + var writer = createAndSetNewTextWriterWithSymbolWriter(); + var enclosingDeclaration; + var currentSourceFile; + var reportedDeclarationError = false; + var errorNameNode; + var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { } : writeJsDocComments; + var emit = compilerOptions.stripInternal ? stripInternal : emitNode; + var moduleElementDeclarationEmitInfo = []; + var asynchronousSubModuleDeclarationEmitInfo; + // Contains the reference paths that needs to go in the declaration file. + // Collecting this separately because reference paths need to be first thing in the declaration file + // and we could be collecting these paths from multiple files into single one with --out option + var referencePathsOutput = ""; + if (root) { + // Emitting just a single file, so emit references in this file only + if (!compilerOptions.noResolve) { + var addedGlobalFileReference = false; + ts.forEach(root.referencedFiles, function (fileReference) { + var referencedFile = ts.tryResolveScriptReference(host, root, fileReference); + // All the references that are not going to be part of same file + if (referencedFile && ((referencedFile.flags & 8192 /* DeclarationFile */) || + ts.shouldEmitToOwnFile(referencedFile, compilerOptions) || + !addedGlobalFileReference)) { + writeReferencePath(referencedFile); + if (!ts.isExternalModuleOrDeclarationFile(referencedFile)) { + addedGlobalFileReference = true; + } + } + }); + } + emitSourceFile(root); + // create asynchronous output for the importDeclarations + if (moduleElementDeclarationEmitInfo.length) { + var oldWriter = writer; + ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { + if (aliasEmitInfo.isVisible) { + ts.Debug.assert(aliasEmitInfo.node.kind === 222 /* ImportDeclaration */); + createAndSetNewTextWriterWithSymbolWriter(); + ts.Debug.assert(aliasEmitInfo.indent === 0); + writeImportDeclaration(aliasEmitInfo.node); + aliasEmitInfo.asynchronousOutput = writer.getText(); + } + }); + setWriter(oldWriter); + } + } + else { + // Emit references corresponding to this file + var emittedReferencedFiles = []; + ts.forEach(host.getSourceFiles(), function (sourceFile) { + if (!ts.isExternalModuleOrDeclarationFile(sourceFile)) { + // Check what references need to be added + if (!compilerOptions.noResolve) { + ts.forEach(sourceFile.referencedFiles, function (fileReference) { + var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); + // If the reference file is a declaration file or an external module, emit that reference + if (referencedFile && (ts.isExternalModuleOrDeclarationFile(referencedFile) && + !ts.contains(emittedReferencedFiles, referencedFile))) { + writeReferencePath(referencedFile); + emittedReferencedFiles.push(referencedFile); + } + }); + } + emitSourceFile(sourceFile); + } + }); + } + return { + reportedDeclarationError: reportedDeclarationError, + moduleElementDeclarationEmitInfo: moduleElementDeclarationEmitInfo, + synchronousDeclarationOutput: writer.getText(), + referencePathsOutput: referencePathsOutput + }; + function hasInternalAnnotation(range) { + var text = currentSourceFile.text; + var comment = text.substring(range.pos, range.end); + return comment.indexOf("@internal") >= 0; + } + function stripInternal(node) { + if (node) { + var leadingCommentRanges = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); + if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { + return; + } + emitNode(node); + } + } + function createAndSetNewTextWriterWithSymbolWriter() { + var writer = ts.createTextWriter(newLine); + writer.trackSymbol = trackSymbol; + writer.reportInaccessibleThisError = reportInaccessibleThisError; + writer.writeKeyword = writer.write; + writer.writeOperator = writer.write; + writer.writePunctuation = writer.write; + writer.writeSpace = writer.write; + writer.writeStringLiteral = writer.writeLiteral; + writer.writeParameter = writer.write; + writer.writeSymbol = writer.write; + setWriter(writer); + return writer; + } + function setWriter(newWriter) { + writer = newWriter; + write = newWriter.write; + writeTextOfNode = newWriter.writeTextOfNode; + writeLine = newWriter.writeLine; + increaseIndent = newWriter.increaseIndent; + decreaseIndent = newWriter.decreaseIndent; + } + function writeAsynchronousModuleElements(nodes) { + var oldWriter = writer; + ts.forEach(nodes, function (declaration) { + var nodeToCheck; + if (declaration.kind === 211 /* VariableDeclaration */) { + nodeToCheck = declaration.parent.parent; + } + else if (declaration.kind === 225 /* NamedImports */ || declaration.kind === 226 /* ImportSpecifier */ || declaration.kind === 223 /* ImportClause */) { + ts.Debug.fail("We should be getting ImportDeclaration instead to write"); + } + else { + nodeToCheck = declaration; + } + var moduleElementEmitInfo = ts.forEach(moduleElementDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); + if (!moduleElementEmitInfo && asynchronousSubModuleDeclarationEmitInfo) { + moduleElementEmitInfo = ts.forEach(asynchronousSubModuleDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); + } + // If the alias was marked as not visible when we saw its declaration, we would have saved the aliasEmitInfo, but if we haven't yet visited the alias declaration + // then we don't need to write it at this point. We will write it when we actually see its declaration + // Eg. + // export function bar(a: foo.Foo) { } + // import foo = require("foo"); + // Writing of function bar would mark alias declaration foo as visible but we haven't yet visited that declaration so do nothing, + // we would write alias foo declaration when we visit it since it would now be marked as visible + if (moduleElementEmitInfo) { + if (moduleElementEmitInfo.node.kind === 222 /* ImportDeclaration */) { + // we have to create asynchronous output only after we have collected complete information + // because it is possible to enable multiple bindings as asynchronously visible + moduleElementEmitInfo.isVisible = true; + } + else { + createAndSetNewTextWriterWithSymbolWriter(); + for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { + increaseIndent(); + } + if (nodeToCheck.kind === 218 /* ModuleDeclaration */) { + ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); + asynchronousSubModuleDeclarationEmitInfo = []; + } + writeModuleElement(nodeToCheck); + if (nodeToCheck.kind === 218 /* ModuleDeclaration */) { + moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; + asynchronousSubModuleDeclarationEmitInfo = undefined; + } + moduleElementEmitInfo.asynchronousOutput = writer.getText(); + } + } + }); + setWriter(oldWriter); + } + function handleSymbolAccessibilityError(symbolAccesibilityResult) { + if (symbolAccesibilityResult.accessibility === 0 /* Accessible */) { + // write the aliases + if (symbolAccesibilityResult && symbolAccesibilityResult.aliasesToMakeVisible) { + writeAsynchronousModuleElements(symbolAccesibilityResult.aliasesToMakeVisible); + } + } + else { + // Report error + reportedDeclarationError = true; + var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); + if (errorInfo) { + if (errorInfo.typeName) { + diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + } + else { + diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + } + } + } + } + function trackSymbol(symbol, enclosingDeclaration, meaning) { + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning)); + } + function reportInaccessibleThisError() { + if (errorNameNode) { + diagnostics.push(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode))); + } + } + function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { + writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; + write(": "); + if (type) { + // Write the type + emitType(type); + } + else { + errorNameNode = declaration.name; + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + errorNameNode = undefined; + } + } + function writeReturnTypeAtSignature(signature, getSymbolAccessibilityDiagnostic) { + writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; + write(": "); + if (signature.type) { + // Write the type + emitType(signature.type); + } + else { + errorNameNode = signature.name; + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + errorNameNode = undefined; + } + } + function emitLines(nodes) { + for (var _i = 0; _i < nodes.length; _i++) { + var node = nodes[_i]; + emit(node); + } + } + function emitSeparatedList(nodes, separator, eachNodeEmitFn, canEmitFn) { + var currentWriterPos = writer.getTextPos(); + for (var _i = 0; _i < nodes.length; _i++) { + var node = nodes[_i]; + if (!canEmitFn || canEmitFn(node)) { + if (currentWriterPos !== writer.getTextPos()) { + write(separator); + } + currentWriterPos = writer.getTextPos(); + eachNodeEmitFn(node); + } + } + } + function emitCommaList(nodes, eachNodeEmitFn, canEmitFn) { + emitSeparatedList(nodes, ", ", eachNodeEmitFn, canEmitFn); + } + function writeJsDocComments(declaration) { + if (declaration) { + var jsDocComments = ts.getJsDocComments(declaration, currentSourceFile); + ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, declaration, jsDocComments); + // jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space + ts.emitComments(currentSourceFile, writer, jsDocComments, /*trailingSeparator*/ true, newLine, ts.writeCommentRange); + } + } + function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { + writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; + emitType(type); + } + function emitType(type) { + switch (type.kind) { + case 117 /* AnyKeyword */: + case 130 /* StringKeyword */: + case 128 /* NumberKeyword */: + case 120 /* BooleanKeyword */: + case 131 /* SymbolKeyword */: + case 103 /* VoidKeyword */: + case 97 /* ThisKeyword */: + case 9 /* StringLiteral */: + return writeTextOfNode(currentSourceFile, type); + case 188 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(type); + case 151 /* TypeReference */: + return emitTypeReference(type); + case 154 /* TypeQuery */: + return emitTypeQuery(type); + case 156 /* ArrayType */: + return emitArrayType(type); + case 157 /* TupleType */: + return emitTupleType(type); + case 158 /* UnionType */: + return emitUnionType(type); + case 159 /* IntersectionType */: + return emitIntersectionType(type); + case 160 /* ParenthesizedType */: + return emitParenType(type); + case 152 /* FunctionType */: + case 153 /* ConstructorType */: + return emitSignatureDeclarationWithJsDocComments(type); + case 155 /* TypeLiteral */: + return emitTypeLiteral(type); + case 69 /* Identifier */: + return emitEntityName(type); + case 135 /* QualifiedName */: + return emitEntityName(type); + case 150 /* TypePredicate */: + return emitTypePredicate(type); + } + function writeEntityName(entityName) { + if (entityName.kind === 69 /* Identifier */) { + writeTextOfNode(currentSourceFile, entityName); + } + else { + var left = entityName.kind === 135 /* QualifiedName */ ? entityName.left : entityName.expression; + var right = entityName.kind === 135 /* QualifiedName */ ? entityName.right : entityName.name; + writeEntityName(left); + write("."); + writeTextOfNode(currentSourceFile, right); + } + } + function emitEntityName(entityName) { + var visibilityResult = resolver.isEntityNameVisible(entityName, + // Aliases can be written asynchronously so use correct enclosing declaration + entityName.parent.kind === 221 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + writeEntityName(entityName); + } + function emitExpressionWithTypeArguments(node) { + if (ts.isSupportedExpressionWithTypeArguments(node)) { + ts.Debug.assert(node.expression.kind === 69 /* Identifier */ || node.expression.kind === 166 /* PropertyAccessExpression */); + emitEntityName(node.expression); + if (node.typeArguments) { + write("<"); + emitCommaList(node.typeArguments, emitType); + write(">"); + } + } + } + function emitTypeReference(type) { + emitEntityName(type.typeName); + if (type.typeArguments) { + write("<"); + emitCommaList(type.typeArguments, emitType); + write(">"); + } + } + function emitTypePredicate(type) { + writeTextOfNode(currentSourceFile, type.parameterName); + write(" is "); + emitType(type.type); + } + function emitTypeQuery(type) { + write("typeof "); + emitEntityName(type.exprName); + } + function emitArrayType(type) { + emitType(type.elementType); + write("[]"); + } + function emitTupleType(type) { + write("["); + emitCommaList(type.elementTypes, emitType); + write("]"); + } + function emitUnionType(type) { + emitSeparatedList(type.types, " | ", emitType); + } + function emitIntersectionType(type) { + emitSeparatedList(type.types, " & ", emitType); + } + function emitParenType(type) { + write("("); + emitType(type.type); + write(")"); + } + function emitTypeLiteral(type) { + write("{"); + if (type.members.length) { + writeLine(); + increaseIndent(); + // write members + emitLines(type.members); + decreaseIndent(); + } + write("}"); + } + } + function emitSourceFile(node) { + currentSourceFile = node; + enclosingDeclaration = node; + emitLines(node.statements); + } + // Return a temp variable name to be used in `export default` statements. + // The temp name will be of the form _default_counter. + // Note that export default is only allowed at most once in a module, so we + // do not need to keep track of created temp names. + function getExportDefaultTempVariableName() { + var baseName = "_default"; + if (!ts.hasProperty(currentSourceFile.identifiers, baseName)) { + return baseName; + } + var count = 0; + while (true) { + var name_18 = baseName + "_" + (++count); + if (!ts.hasProperty(currentSourceFile.identifiers, name_18)) { + return name_18; + } + } + } + function emitExportAssignment(node) { + if (node.expression.kind === 69 /* Identifier */) { + write(node.isExportEquals ? "export = " : "export default "); + writeTextOfNode(currentSourceFile, node.expression); + } + else { + // Expression + var tempVarName = getExportDefaultTempVariableName(); + write("declare var "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + write(";"); + writeLine(); + write(node.isExportEquals ? "export = " : "export default "); + write(tempVarName); + } + write(";"); + writeLine(); + // Make all the declarations visible for the export name + if (node.expression.kind === 69 /* Identifier */) { + var nodes = resolver.collectLinkedAliases(node.expression); + // write each of these declarations asynchronously + writeAsynchronousModuleElements(nodes); + } + function getDefaultExportAccessibilityDiagnostic(diagnostic) { + return { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }; + } + } + function isModuleElementVisible(node) { + return resolver.isDeclarationVisible(node); + } + function emitModuleElement(node, isModuleElementVisible) { + if (isModuleElementVisible) { + writeModuleElement(node); + } + else if (node.kind === 221 /* ImportEqualsDeclaration */ || + (node.parent.kind === 248 /* SourceFile */ && ts.isExternalModule(currentSourceFile))) { + var isVisible; + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 248 /* SourceFile */) { + // Import declaration of another module that is visited async so lets put it in right spot + asynchronousSubModuleDeclarationEmitInfo.push({ + node: node, + outputPos: writer.getTextPos(), + indent: writer.getIndent(), + isVisible: isVisible + }); + } + else { + if (node.kind === 222 /* ImportDeclaration */) { + var importDeclaration = node; + if (importDeclaration.importClause) { + isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || + isVisibleNamedBinding(importDeclaration.importClause.namedBindings); + } + } + moduleElementDeclarationEmitInfo.push({ + node: node, + outputPos: writer.getTextPos(), + indent: writer.getIndent(), + isVisible: isVisible + }); + } + } + } + function writeModuleElement(node) { + switch (node.kind) { + case 213 /* FunctionDeclaration */: + return writeFunctionDeclaration(node); + case 193 /* VariableStatement */: + return writeVariableStatement(node); + case 215 /* InterfaceDeclaration */: + return writeInterfaceDeclaration(node); + case 214 /* ClassDeclaration */: + return writeClassDeclaration(node); + case 216 /* TypeAliasDeclaration */: + return writeTypeAliasDeclaration(node); + case 217 /* EnumDeclaration */: + return writeEnumDeclaration(node); + case 218 /* ModuleDeclaration */: + return writeModuleDeclaration(node); + case 221 /* ImportEqualsDeclaration */: + return writeImportEqualsDeclaration(node); + case 222 /* ImportDeclaration */: + return writeImportDeclaration(node); + default: + ts.Debug.fail("Unknown symbol kind"); + } + } + function emitModuleElementDeclarationFlags(node) { + // If the node is parented in the current source file we need to emit export declare or just export + if (node.parent === currentSourceFile) { + // If the node is exported + if (node.flags & 1 /* Export */) { + write("export "); + } + if (node.flags & 1024 /* Default */) { + write("default "); + } + else if (node.kind !== 215 /* InterfaceDeclaration */) { + write("declare "); + } + } + } + function emitClassMemberDeclarationFlags(node) { + if (node.flags & 32 /* Private */) { + write("private "); + } + else if (node.flags & 64 /* Protected */) { + write("protected "); + } + if (node.flags & 128 /* Static */) { + write("static "); + } + if (node.flags & 256 /* Abstract */) { + write("abstract "); + } + } + function writeImportEqualsDeclaration(node) { + // note usage of writer. methods instead of aliases created, just to make sure we are using + // correct writer especially to handle asynchronous alias writing + emitJsDocComments(node); + if (node.flags & 1 /* Export */) { + write("export "); + } + write("import "); + writeTextOfNode(currentSourceFile, node.name); + write(" = "); + if (ts.isInternalModuleImportEqualsDeclaration(node)) { + emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError); + write(";"); + } + else { + write("require("); + writeTextOfNode(currentSourceFile, ts.getExternalModuleImportEqualsDeclarationExpression(node)); + write(");"); + } + writer.writeLine(); + function getImportEntityNameVisibilityError(symbolAccesibilityResult) { + return { + diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, + errorNode: node, + typeName: node.name + }; + } + } + function isVisibleNamedBinding(namedBindings) { + if (namedBindings) { + if (namedBindings.kind === 224 /* NamespaceImport */) { + return resolver.isDeclarationVisible(namedBindings); + } + else { + return ts.forEach(namedBindings.elements, function (namedImport) { return resolver.isDeclarationVisible(namedImport); }); + } + } + } + function writeImportDeclaration(node) { + if (!node.importClause && !(node.flags & 1 /* Export */)) { + // do not write non-exported import declarations that don't have import clauses + return; + } + emitJsDocComments(node); + if (node.flags & 1 /* Export */) { + write("export "); + } + write("import "); + if (node.importClause) { + var currentWriterPos = writer.getTextPos(); + if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) { + writeTextOfNode(currentSourceFile, node.importClause.name); + } + if (node.importClause.namedBindings && isVisibleNamedBinding(node.importClause.namedBindings)) { + if (currentWriterPos !== writer.getTextPos()) { + // If the default binding was emitted, write the separated + write(", "); + } + if (node.importClause.namedBindings.kind === 224 /* NamespaceImport */) { + write("* as "); + writeTextOfNode(currentSourceFile, node.importClause.namedBindings.name); + } + else { + write("{ "); + emitCommaList(node.importClause.namedBindings.elements, emitImportOrExportSpecifier, resolver.isDeclarationVisible); + write(" }"); + } + } + write(" from "); + } + writeTextOfNode(currentSourceFile, node.moduleSpecifier); + write(";"); + writer.writeLine(); + } + function emitImportOrExportSpecifier(node) { + if (node.propertyName) { + writeTextOfNode(currentSourceFile, node.propertyName); + write(" as "); + } + writeTextOfNode(currentSourceFile, node.name); + } + function emitExportSpecifier(node) { + emitImportOrExportSpecifier(node); + // Make all the declarations visible for the export name + var nodes = resolver.collectLinkedAliases(node.propertyName || node.name); + // write each of these declarations asynchronously + writeAsynchronousModuleElements(nodes); + } + function emitExportDeclaration(node) { + emitJsDocComments(node); + write("export "); + if (node.exportClause) { + write("{ "); + emitCommaList(node.exportClause.elements, emitExportSpecifier); + write(" }"); + } + else { + write("*"); + } + if (node.moduleSpecifier) { + write(" from "); + writeTextOfNode(currentSourceFile, node.moduleSpecifier); + } + write(";"); + writer.writeLine(); + } + function writeModuleDeclaration(node) { + emitJsDocComments(node); + emitModuleElementDeclarationFlags(node); + if (node.flags & 131072 /* Namespace */) { + write("namespace "); + } + else { + write("module "); + } + writeTextOfNode(currentSourceFile, node.name); + while (node.body.kind !== 219 /* ModuleBlock */) { + node = node.body; + write("."); + writeTextOfNode(currentSourceFile, node.name); + } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.body.statements); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + function writeTypeAliasDeclaration(node) { + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + emitJsDocComments(node); + emitModuleElementDeclarationFlags(node); + write("type "); + writeTextOfNode(currentSourceFile, node.name); + emitTypeParameters(node.typeParameters); + write(" = "); + emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError); + write(";"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + function getTypeAliasDeclarationVisibilityError(symbolAccesibilityResult) { + return { + diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: node.type, + typeName: node.name + }; + } + } + function writeEnumDeclaration(node) { + emitJsDocComments(node); + emitModuleElementDeclarationFlags(node); + if (ts.isConst(node)) { + write("const "); + } + write("enum "); + writeTextOfNode(currentSourceFile, node.name); + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.members); + decreaseIndent(); + write("}"); + writeLine(); + } + function emitEnumMemberDeclaration(node) { + emitJsDocComments(node); + writeTextOfNode(currentSourceFile, node.name); + var enumMemberValue = resolver.getConstantValue(node); + if (enumMemberValue !== undefined) { + write(" = "); + write(enumMemberValue.toString()); + } + write(","); + writeLine(); + } + function isPrivateMethodTypeParameter(node) { + return node.parent.kind === 143 /* MethodDeclaration */ && (node.parent.flags & 32 /* Private */); + } + function emitTypeParameters(typeParameters) { + function emitTypeParameter(node) { + increaseIndent(); + emitJsDocComments(node); + decreaseIndent(); + writeTextOfNode(currentSourceFile, node.name); + // If there is constraint present and this is not a type parameter of the private method emit the constraint + if (node.constraint && !isPrivateMethodTypeParameter(node)) { + write(" extends "); + if (node.parent.kind === 152 /* FunctionType */ || + node.parent.kind === 153 /* ConstructorType */ || + (node.parent.parent && node.parent.parent.kind === 155 /* TypeLiteral */)) { + ts.Debug.assert(node.parent.kind === 143 /* MethodDeclaration */ || + node.parent.kind === 142 /* MethodSignature */ || + node.parent.kind === 152 /* FunctionType */ || + node.parent.kind === 153 /* ConstructorType */ || + node.parent.kind === 147 /* CallSignature */ || + node.parent.kind === 148 /* ConstructSignature */); + emitType(node.constraint); + } + else { + emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); + } + } + function getTypeParameterConstraintVisibilityError(symbolAccesibilityResult) { + // Type parameter constraints are named by user so we should always be able to name it + var diagnosticMessage; + switch (node.parent.kind) { + case 214 /* ClassDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; + break; + case 215 /* InterfaceDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; + break; + case 148 /* ConstructSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 147 /* CallSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + if (node.parent.flags & 128 /* Static */) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 214 /* ClassDeclaration */) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + break; + case 213 /* FunctionDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + default: + ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + }; + } + } + if (typeParameters) { + write("<"); + emitCommaList(typeParameters, emitTypeParameter); + write(">"); + } + } + function emitHeritageClause(typeReferences, isImplementsList) { + if (typeReferences) { + write(isImplementsList ? " implements " : " extends "); + emitCommaList(typeReferences, emitTypeOfTypeReference); + } + function emitTypeOfTypeReference(node) { + if (ts.isSupportedExpressionWithTypeArguments(node)) { + emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); + } + else if (!isImplementsList && node.expression.kind === 93 /* NullKeyword */) { + write("null"); + } + function getHeritageClauseVisibilityError(symbolAccesibilityResult) { + var diagnosticMessage; + // Heritage clause is written by user so it can always be named + if (node.parent.parent.kind === 214 /* ClassDeclaration */) { + // Class or Interface implemented/extended is inaccessible + diagnosticMessage = isImplementsList ? + ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : + ts.Diagnostics.Extends_clause_of_exported_class_0_has_or_is_using_private_name_1; + } + else { + // interface is inaccessible + diagnosticMessage = ts.Diagnostics.Extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.parent.parent.name + }; + } + } + } + function writeClassDeclaration(node) { + function emitParameterProperties(constructorDeclaration) { + if (constructorDeclaration) { + ts.forEach(constructorDeclaration.parameters, function (param) { + if (param.flags & 112 /* AccessibilityModifier */) { + emitPropertyDeclaration(param); + } + }); + } + } + emitJsDocComments(node); + emitModuleElementDeclarationFlags(node); + if (node.flags & 256 /* Abstract */) { + write("abstract "); + } + write("class "); + writeTextOfNode(currentSourceFile, node.name); + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + emitTypeParameters(node.typeParameters); + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + if (baseTypeNode) { + emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); + } + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); + write(" {"); + writeLine(); + increaseIndent(); + emitParameterProperties(ts.getFirstConstructorWithBody(node)); + emitLines(node.members); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + function writeInterfaceDeclaration(node) { + emitJsDocComments(node); + emitModuleElementDeclarationFlags(node); + write("interface "); + writeTextOfNode(currentSourceFile, node.name); + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + emitTypeParameters(node.typeParameters); + emitHeritageClause(ts.getInterfaceBaseTypeNodes(node), /*isImplementsList*/ false); + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.members); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + function emitPropertyDeclaration(node) { + if (ts.hasDynamicName(node)) { + return; + } + emitJsDocComments(node); + emitClassMemberDeclarationFlags(node); + emitVariableDeclaration(node); + write(";"); + writeLine(); + } + function emitVariableDeclaration(node) { + // If we are emitting property it isn't moduleElement and hence we already know it needs to be emitted + // so there is no check needed to see if declaration is visible + if (node.kind !== 211 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { + if (ts.isBindingPattern(node.name)) { + emitBindingPattern(node.name); + } + else { + // If this node is a computed name, it can only be a symbol, because we've already skipped + // it if it's not a well known symbol. In that case, the text of the name will be exactly + // what we want, namely the name expression enclosed in brackets. + writeTextOfNode(currentSourceFile, node.name); + // If optional property emit ? + if ((node.kind === 141 /* PropertyDeclaration */ || node.kind === 140 /* PropertySignature */) && ts.hasQuestionToken(node)) { + write("?"); + } + if ((node.kind === 141 /* PropertyDeclaration */ || node.kind === 140 /* PropertySignature */) && node.parent.kind === 155 /* TypeLiteral */) { + emitTypeOfVariableDeclarationFromTypeLiteral(node); + } + else if (!(node.flags & 32 /* Private */)) { + writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); + } + } + } + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { + if (node.kind === 211 /* VariableDeclaration */) { + return symbolAccesibilityResult.errorModuleName ? + symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; + } + else if (node.kind === 141 /* PropertyDeclaration */ || node.kind === 140 /* PropertySignature */) { + // TODO(jfreeman): Deal with computed properties in error reporting. + if (node.flags & 128 /* Static */) { + return symbolAccesibilityResult.errorModuleName ? + symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 214 /* ClassDeclaration */) { + return symbolAccesibilityResult.errorModuleName ? + symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + // Interfaces cannot have types that cannot be named + return symbolAccesibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + function getVariableDeclarationTypeVisibilityError(symbolAccesibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function emitBindingPattern(bindingPattern) { + // Only select non-omitted expression from the bindingPattern's elements. + // We have to do this to avoid emitting trailing commas. + // For example: + // original: var [, c,,] = [ 2,3,4] + // emitted: declare var c: number; // instead of declare var c:number, ; + var elements = []; + for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.kind !== 187 /* OmittedExpression */) { + elements.push(element); + } + } + emitCommaList(elements, emitBindingElement); + } + function emitBindingElement(bindingElement) { + function getBindingElementTypeVisibilityError(symbolAccesibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: bindingElement, + typeName: bindingElement.name + } : undefined; + } + if (bindingElement.name) { + if (ts.isBindingPattern(bindingElement.name)) { + emitBindingPattern(bindingElement.name); + } + else { + writeTextOfNode(currentSourceFile, bindingElement.name); + writeTypeOfDeclaration(bindingElement, /*type*/ undefined, getBindingElementTypeVisibilityError); + } + } + } + } + function emitTypeOfVariableDeclarationFromTypeLiteral(node) { + // if this is property of type literal, + // or is parameter of method/call/construct/index signature of type literal + // emit only if type is specified + if (node.type) { + write(": "); + emitType(node.type); + } + } + function isVariableStatementVisible(node) { + return ts.forEach(node.declarationList.declarations, function (varDeclaration) { return resolver.isDeclarationVisible(varDeclaration); }); + } + function writeVariableStatement(node) { + emitJsDocComments(node); + emitModuleElementDeclarationFlags(node); + if (ts.isLet(node.declarationList)) { + write("let "); + } + else if (ts.isConst(node.declarationList)) { + write("const "); + } + else { + write("var "); + } + emitCommaList(node.declarationList.declarations, emitVariableDeclaration, resolver.isDeclarationVisible); + write(";"); + writeLine(); + } + function emitAccessorDeclaration(node) { + if (ts.hasDynamicName(node)) { + return; + } + var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + var accessorWithTypeAnnotation; + if (node === accessors.firstAccessor) { + emitJsDocComments(accessors.getAccessor); + emitJsDocComments(accessors.setAccessor); + emitClassMemberDeclarationFlags(node); + writeTextOfNode(currentSourceFile, node.name); + if (!(node.flags & 32 /* Private */)) { + accessorWithTypeAnnotation = node; + var type = getTypeAnnotationFromAccessor(node); + if (!type) { + // couldn't get type for the first accessor, try the another one + var anotherAccessor = node.kind === 145 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; + type = getTypeAnnotationFromAccessor(anotherAccessor); + if (type) { + accessorWithTypeAnnotation = anotherAccessor; + } + } + writeTypeOfDeclaration(node, type, getAccessorDeclarationTypeVisibilityError); + } + write(";"); + writeLine(); + } + function getTypeAnnotationFromAccessor(accessor) { + if (accessor) { + return accessor.kind === 145 /* GetAccessor */ + ? accessor.type // Getter - return type + : accessor.parameters.length > 0 + ? accessor.parameters[0].type // Setter parameter type + : undefined; + } + } + function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult) { + var diagnosticMessage; + if (accessorWithTypeAnnotation.kind === 146 /* SetAccessor */) { + // Setters have to have type named and cannot infer it so, the type should always be named + if (accessorWithTypeAnnotation.parent.flags & 128 /* Static */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1; + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: accessorWithTypeAnnotation.parameters[0], + // TODO(jfreeman): Investigate why we are passing node.name instead of node.parameters[0].name + typeName: accessorWithTypeAnnotation.name + }; + } + else { + if (accessorWithTypeAnnotation.flags & 128 /* Static */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0; + } + else { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0; + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: accessorWithTypeAnnotation.name, + typeName: undefined + }; + } + } + } + function writeFunctionDeclaration(node) { + if (ts.hasDynamicName(node)) { + return; + } + // If we are emitting Method/Constructor it isn't moduleElement and hence already determined to be emitting + // so no need to verify if the declaration is visible + if (!resolver.isImplementationOfOverload(node)) { + emitJsDocComments(node); + if (node.kind === 213 /* FunctionDeclaration */) { + emitModuleElementDeclarationFlags(node); + } + else if (node.kind === 143 /* MethodDeclaration */) { + emitClassMemberDeclarationFlags(node); + } + if (node.kind === 213 /* FunctionDeclaration */) { + write("function "); + writeTextOfNode(currentSourceFile, node.name); + } + else if (node.kind === 144 /* Constructor */) { + write("constructor"); + } + else { + writeTextOfNode(currentSourceFile, node.name); + if (ts.hasQuestionToken(node)) { + write("?"); + } + } + emitSignatureDeclaration(node); + } + } + function emitSignatureDeclarationWithJsDocComments(node) { + emitJsDocComments(node); + emitSignatureDeclaration(node); + } + function emitSignatureDeclaration(node) { + // Construct signature or constructor type write new Signature + if (node.kind === 148 /* ConstructSignature */ || node.kind === 153 /* ConstructorType */) { + write("new "); + } + emitTypeParameters(node.typeParameters); + if (node.kind === 149 /* IndexSignature */) { + write("["); + } + else { + write("("); + } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + // Parameters + emitCommaList(node.parameters, emitParameterDeclaration); + if (node.kind === 149 /* IndexSignature */) { + write("]"); + } + else { + write(")"); + } + // If this is not a constructor and is not private, emit the return type + var isFunctionTypeOrConstructorType = node.kind === 152 /* FunctionType */ || node.kind === 153 /* ConstructorType */; + if (isFunctionTypeOrConstructorType || node.parent.kind === 155 /* TypeLiteral */) { + // Emit type literal signature return type only if specified + if (node.type) { + write(isFunctionTypeOrConstructorType ? " => " : ": "); + emitType(node.type); + } + } + else if (node.kind !== 144 /* Constructor */ && !(node.flags & 32 /* Private */)) { + writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); + } + enclosingDeclaration = prevEnclosingDeclaration; + if (!isFunctionTypeOrConstructorType) { + write(";"); + writeLine(); + } + function getReturnTypeVisibilityError(symbolAccesibilityResult) { + var diagnosticMessage; + switch (node.kind) { + case 148 /* ConstructSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 147 /* CallSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 149 /* IndexSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + if (node.flags & 128 /* Static */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; + } + else if (node.parent.kind === 214 /* ClassDeclaration */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; + } + else { + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; + } + break; + case 213 /* FunctionDeclaration */: + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? + symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; + break; + default: + ts.Debug.fail("This is unknown kind for signature: " + node.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name || node + }; + } + } + function emitParameterDeclaration(node) { + increaseIndent(); + emitJsDocComments(node); + if (node.dotDotDotToken) { + write("..."); + } + if (ts.isBindingPattern(node.name)) { + // For bindingPattern, we can't simply writeTextOfNode from the source file + // because we want to omit the initializer and using writeTextOfNode will result in initializer get emitted. + // Therefore, we will have to recursively emit each element in the bindingPattern. + emitBindingPattern(node.name); + } + else { + writeTextOfNode(currentSourceFile, node.name); + } + if (resolver.isOptionalParameter(node)) { + write("?"); + } + decreaseIndent(); + if (node.parent.kind === 152 /* FunctionType */ || + node.parent.kind === 153 /* ConstructorType */ || + node.parent.parent.kind === 155 /* TypeLiteral */) { + emitTypeOfVariableDeclarationFromTypeLiteral(node); + } + else if (!(node.parent.flags & 32 /* Private */)) { + writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); + } + function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult) { + var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { + switch (node.parent.kind) { + case 144 /* Constructor */: + return symbolAccesibilityResult.errorModuleName ? + symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; + case 148 /* ConstructSignature */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccesibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + case 147 /* CallSignature */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccesibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + if (node.parent.flags & 128 /* Static */) { + return symbolAccesibilityResult.errorModuleName ? + symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 214 /* ClassDeclaration */) { + return symbolAccesibilityResult.errorModuleName ? + symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + // Interfaces cannot have parameter types that cannot be named + return symbolAccesibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + case 213 /* FunctionDeclaration */: + return symbolAccesibilityResult.errorModuleName ? + symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; + default: + ts.Debug.fail("This is unknown parent for parameter: " + node.parent.kind); + } + } + function emitBindingPattern(bindingPattern) { + // We have to explicitly emit square bracket and bracket because these tokens are not store inside the node. + if (bindingPattern.kind === 161 /* ObjectBindingPattern */) { + write("{"); + emitCommaList(bindingPattern.elements, emitBindingElement); + write("}"); + } + else if (bindingPattern.kind === 162 /* ArrayBindingPattern */) { + write("["); + var elements = bindingPattern.elements; + emitCommaList(elements, emitBindingElement); + if (elements && elements.hasTrailingComma) { + write(", "); + } + write("]"); + } + } + function emitBindingElement(bindingElement) { + function getBindingElementTypeVisibilityError(symbolAccesibilityResult) { + var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: bindingElement, + typeName: bindingElement.name + } : undefined; + } + if (bindingElement.kind === 187 /* OmittedExpression */) { + // If bindingElement is an omittedExpression (i.e. containing elision), + // we will emit blank space (although this may differ from users' original code, + // it allows emitSeparatedList to write separator appropriately) + // Example: + // original: function foo([, x, ,]) {} + // emit : function foo([ , x, , ]) {} + write(" "); + } + else if (bindingElement.kind === 163 /* BindingElement */) { + if (bindingElement.propertyName) { + // bindingElement has propertyName property in the following case: + // { y: [a,b,c] ...} -> bindingPattern will have a property called propertyName for "y" + // We have to explicitly emit the propertyName before descending into its binding elements. + // Example: + // original: function foo({y: [a,b,c]}) {} + // emit : declare function foo({y: [a, b, c]}: { y: [any, any, any] }) void; + writeTextOfNode(currentSourceFile, bindingElement.propertyName); + write(": "); + } + if (bindingElement.name) { + if (ts.isBindingPattern(bindingElement.name)) { + // If it is a nested binding pattern, we will recursively descend into each element and emit each one separately. + // In the case of rest element, we will omit rest element. + // Example: + // original: function foo([a, [[b]], c] = [1,[["string"]], 3]) {} + // emit : declare function foo([a, [[b]], c]: [number, [[string]], number]): void; + // original with rest: function foo([a, ...c]) {} + // emit : declare function foo([a, ...c]): void; + emitBindingPattern(bindingElement.name); + } + else { + ts.Debug.assert(bindingElement.name.kind === 69 /* Identifier */); + // If the node is just an identifier, we will simply emit the text associated with the node's name + // Example: + // original: function foo({y = 10, x}) {} + // emit : declare function foo({y, x}: {number, any}): void; + if (bindingElement.dotDotDotToken) { + write("..."); + } + writeTextOfNode(currentSourceFile, bindingElement.name); + } + } + } + } + } + function emitNode(node) { + switch (node.kind) { + case 213 /* FunctionDeclaration */: + case 218 /* ModuleDeclaration */: + case 221 /* ImportEqualsDeclaration */: + case 215 /* InterfaceDeclaration */: + case 214 /* ClassDeclaration */: + case 216 /* TypeAliasDeclaration */: + case 217 /* EnumDeclaration */: + return emitModuleElement(node, isModuleElementVisible(node)); + case 193 /* VariableStatement */: + return emitModuleElement(node, isVariableStatementVisible(node)); + case 222 /* ImportDeclaration */: + // Import declaration without import clause is visible, otherwise it is not visible + return emitModuleElement(node, /*isModuleElementVisible*/ !node.importClause); + case 228 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 144 /* Constructor */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + return writeFunctionDeclaration(node); + case 148 /* ConstructSignature */: + case 147 /* CallSignature */: + case 149 /* IndexSignature */: + return emitSignatureDeclarationWithJsDocComments(node); + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + return emitPropertyDeclaration(node); + case 247 /* EnumMember */: + return emitEnumMemberDeclaration(node); + case 227 /* ExportAssignment */: + return emitExportAssignment(node); + case 248 /* SourceFile */: + return emitSourceFile(node); + } + } + function writeReferencePath(referencedFile) { + var declFileName = referencedFile.flags & 8192 /* DeclarationFile */ + ? referencedFile.fileName // Declaration file, use declaration file name + : ts.shouldEmitToOwnFile(referencedFile, compilerOptions) + ? ts.getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") // Own output file so get the .d.ts file + : ts.removeFileExtension(compilerOptions.outFile || compilerOptions.out) + ".d.ts"; // Global out file + declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(jsFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ false); + referencePathsOutput += "/// " + newLine; + } + } + /* @internal */ + function writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics) { + var emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile); + // TODO(shkamat): Should we not write any declaration file if any of them can produce error, + // or should we just not write this file like we are doing now + if (!emitDeclarationResult.reportedDeclarationError) { + var declarationOutput = emitDeclarationResult.referencePathsOutput + + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); + ts.writeFile(host, diagnostics, ts.removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, host.getCompilerOptions().emitBOM); + } + function getDeclarationOutput(synchronousDeclarationOutput, moduleElementDeclarationEmitInfo) { + var appliedSyncOutputPos = 0; + var declarationOutput = ""; + // apply asynchronous additions to the synchronous output + ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { + if (aliasEmitInfo.asynchronousOutput) { + declarationOutput += synchronousDeclarationOutput.substring(appliedSyncOutputPos, aliasEmitInfo.outputPos); + declarationOutput += getDeclarationOutput(aliasEmitInfo.asynchronousOutput, aliasEmitInfo.subModuleElementDeclarationEmitInfo); + appliedSyncOutputPos = aliasEmitInfo.outputPos; + } + }); + declarationOutput += synchronousDeclarationOutput.substring(appliedSyncOutputPos); + return declarationOutput; + } + } + ts.writeDeclarationFile = writeDeclarationFile; +})(ts || (ts = {})); +/// +/// +/* @internal */ +var ts; +(function (ts) { + function isExternalModuleOrDeclarationFile(sourceFile) { + return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile); + } + ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile; + var entities = { + "quot": 0x0022, + "amp": 0x0026, + "apos": 0x0027, + "lt": 0x003C, + "gt": 0x003E, + "nbsp": 0x00A0, + "iexcl": 0x00A1, + "cent": 0x00A2, + "pound": 0x00A3, + "curren": 0x00A4, + "yen": 0x00A5, + "brvbar": 0x00A6, + "sect": 0x00A7, + "uml": 0x00A8, + "copy": 0x00A9, + "ordf": 0x00AA, + "laquo": 0x00AB, + "not": 0x00AC, + "shy": 0x00AD, + "reg": 0x00AE, + "macr": 0x00AF, + "deg": 0x00B0, + "plusmn": 0x00B1, + "sup2": 0x00B2, + "sup3": 0x00B3, + "acute": 0x00B4, + "micro": 0x00B5, + "para": 0x00B6, + "middot": 0x00B7, + "cedil": 0x00B8, + "sup1": 0x00B9, + "ordm": 0x00BA, + "raquo": 0x00BB, + "frac14": 0x00BC, + "frac12": 0x00BD, + "frac34": 0x00BE, + "iquest": 0x00BF, + "Agrave": 0x00C0, + "Aacute": 0x00C1, + "Acirc": 0x00C2, + "Atilde": 0x00C3, + "Auml": 0x00C4, + "Aring": 0x00C5, + "AElig": 0x00C6, + "Ccedil": 0x00C7, + "Egrave": 0x00C8, + "Eacute": 0x00C9, + "Ecirc": 0x00CA, + "Euml": 0x00CB, + "Igrave": 0x00CC, + "Iacute": 0x00CD, + "Icirc": 0x00CE, + "Iuml": 0x00CF, + "ETH": 0x00D0, + "Ntilde": 0x00D1, + "Ograve": 0x00D2, + "Oacute": 0x00D3, + "Ocirc": 0x00D4, + "Otilde": 0x00D5, + "Ouml": 0x00D6, + "times": 0x00D7, + "Oslash": 0x00D8, + "Ugrave": 0x00D9, + "Uacute": 0x00DA, + "Ucirc": 0x00DB, + "Uuml": 0x00DC, + "Yacute": 0x00DD, + "THORN": 0x00DE, + "szlig": 0x00DF, + "agrave": 0x00E0, + "aacute": 0x00E1, + "acirc": 0x00E2, + "atilde": 0x00E3, + "auml": 0x00E4, + "aring": 0x00E5, + "aelig": 0x00E6, + "ccedil": 0x00E7, + "egrave": 0x00E8, + "eacute": 0x00E9, + "ecirc": 0x00EA, + "euml": 0x00EB, + "igrave": 0x00EC, + "iacute": 0x00ED, + "icirc": 0x00EE, + "iuml": 0x00EF, + "eth": 0x00F0, + "ntilde": 0x00F1, + "ograve": 0x00F2, + "oacute": 0x00F3, + "ocirc": 0x00F4, + "otilde": 0x00F5, + "ouml": 0x00F6, + "divide": 0x00F7, + "oslash": 0x00F8, + "ugrave": 0x00F9, + "uacute": 0x00FA, + "ucirc": 0x00FB, + "uuml": 0x00FC, + "yacute": 0x00FD, + "thorn": 0x00FE, + "yuml": 0x00FF, + "OElig": 0x0152, + "oelig": 0x0153, + "Scaron": 0x0160, + "scaron": 0x0161, + "Yuml": 0x0178, + "fnof": 0x0192, + "circ": 0x02C6, + "tilde": 0x02DC, + "Alpha": 0x0391, + "Beta": 0x0392, + "Gamma": 0x0393, + "Delta": 0x0394, + "Epsilon": 0x0395, + "Zeta": 0x0396, + "Eta": 0x0397, + "Theta": 0x0398, + "Iota": 0x0399, + "Kappa": 0x039A, + "Lambda": 0x039B, + "Mu": 0x039C, + "Nu": 0x039D, + "Xi": 0x039E, + "Omicron": 0x039F, + "Pi": 0x03A0, + "Rho": 0x03A1, + "Sigma": 0x03A3, + "Tau": 0x03A4, + "Upsilon": 0x03A5, + "Phi": 0x03A6, + "Chi": 0x03A7, + "Psi": 0x03A8, + "Omega": 0x03A9, + "alpha": 0x03B1, + "beta": 0x03B2, + "gamma": 0x03B3, + "delta": 0x03B4, + "epsilon": 0x03B5, + "zeta": 0x03B6, + "eta": 0x03B7, + "theta": 0x03B8, + "iota": 0x03B9, + "kappa": 0x03BA, + "lambda": 0x03BB, + "mu": 0x03BC, + "nu": 0x03BD, + "xi": 0x03BE, + "omicron": 0x03BF, + "pi": 0x03C0, + "rho": 0x03C1, + "sigmaf": 0x03C2, + "sigma": 0x03C3, + "tau": 0x03C4, + "upsilon": 0x03C5, + "phi": 0x03C6, + "chi": 0x03C7, + "psi": 0x03C8, + "omega": 0x03C9, + "thetasym": 0x03D1, + "upsih": 0x03D2, + "piv": 0x03D6, + "ensp": 0x2002, + "emsp": 0x2003, + "thinsp": 0x2009, + "zwnj": 0x200C, + "zwj": 0x200D, + "lrm": 0x200E, + "rlm": 0x200F, + "ndash": 0x2013, + "mdash": 0x2014, + "lsquo": 0x2018, + "rsquo": 0x2019, + "sbquo": 0x201A, + "ldquo": 0x201C, + "rdquo": 0x201D, + "bdquo": 0x201E, + "dagger": 0x2020, + "Dagger": 0x2021, + "bull": 0x2022, + "hellip": 0x2026, + "permil": 0x2030, + "prime": 0x2032, + "Prime": 0x2033, + "lsaquo": 0x2039, + "rsaquo": 0x203A, + "oline": 0x203E, + "frasl": 0x2044, + "euro": 0x20AC, + "image": 0x2111, + "weierp": 0x2118, + "real": 0x211C, + "trade": 0x2122, + "alefsym": 0x2135, + "larr": 0x2190, + "uarr": 0x2191, + "rarr": 0x2192, + "darr": 0x2193, + "harr": 0x2194, + "crarr": 0x21B5, + "lArr": 0x21D0, + "uArr": 0x21D1, + "rArr": 0x21D2, + "dArr": 0x21D3, + "hArr": 0x21D4, + "forall": 0x2200, + "part": 0x2202, + "exist": 0x2203, + "empty": 0x2205, + "nabla": 0x2207, + "isin": 0x2208, + "notin": 0x2209, + "ni": 0x220B, + "prod": 0x220F, + "sum": 0x2211, + "minus": 0x2212, + "lowast": 0x2217, + "radic": 0x221A, + "prop": 0x221D, + "infin": 0x221E, + "ang": 0x2220, + "and": 0x2227, + "or": 0x2228, + "cap": 0x2229, + "cup": 0x222A, + "int": 0x222B, + "there4": 0x2234, + "sim": 0x223C, + "cong": 0x2245, + "asymp": 0x2248, + "ne": 0x2260, + "equiv": 0x2261, + "le": 0x2264, + "ge": 0x2265, + "sub": 0x2282, + "sup": 0x2283, + "nsub": 0x2284, + "sube": 0x2286, + "supe": 0x2287, + "oplus": 0x2295, + "otimes": 0x2297, + "perp": 0x22A5, + "sdot": 0x22C5, + "lceil": 0x2308, + "rceil": 0x2309, + "lfloor": 0x230A, + "rfloor": 0x230B, + "lang": 0x2329, + "rang": 0x232A, + "loz": 0x25CA, + "spades": 0x2660, + "clubs": 0x2663, + "hearts": 0x2665, + "diams": 0x2666 + }; + // Flags enum to track count of temp variables and a few dedicated names + var TempFlags; + (function (TempFlags) { + TempFlags[TempFlags["Auto"] = 0] = "Auto"; + TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; + TempFlags[TempFlags["_i"] = 268435456] = "_i"; + })(TempFlags || (TempFlags = {})); + // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature + function emitFiles(resolver, host, targetSourceFile) { + // emit output for the __extends helper function + var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; + // emit output for the __decorate helper function + var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; + // emit output for the __metadata helper function + var metadataHelper = "\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};"; + // emit output for the __param helper function + var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; + var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {\n return new Promise(function (resolve, reject) {\n generator = generator.call(thisArg, _arguments);\n function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }\n function onfulfill(value) { try { step(\"next\", value); } catch (e) { reject(e); } }\n function onreject(value) { try { step(\"throw\", value); } catch (e) { reject(e); } }\n function step(verb, value) {\n var result = generator[verb](value);\n result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);\n }\n step(\"next\", void 0);\n });\n};"; + var compilerOptions = host.getCompilerOptions(); + var languageVersion = compilerOptions.target || 0 /* ES3 */; + var modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === 2 /* ES6 */ ? 5 /* ES6 */ : 0 /* None */; + var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; + var diagnostics = []; + var newLine = host.getNewLine(); + var jsxDesugaring = host.getCompilerOptions().jsx !== 1 /* Preserve */; + var shouldEmitJsx = function (s) { return (s.languageVariant === 1 /* JSX */ && !jsxDesugaring); }; + if (targetSourceFile === undefined) { + ts.forEach(host.getSourceFiles(), function (sourceFile) { + if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) { + var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js"); + emitFile(jsFilePath, sourceFile); + } + }); + if (compilerOptions.outFile || compilerOptions.out) { + emitFile(compilerOptions.outFile || compilerOptions.out); + } + } + else { + // targetSourceFile is specified (e.g calling emitter from language service or calling getSemanticDiagnostic from language service) + if (ts.shouldEmitToOwnFile(targetSourceFile, compilerOptions)) { + var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? ".jsx" : ".js"); + emitFile(jsFilePath, targetSourceFile); + } + else if (!ts.isDeclarationFile(targetSourceFile) && (compilerOptions.outFile || compilerOptions.out)) { + emitFile(compilerOptions.outFile || compilerOptions.out); + } + } + // Sort and make the unique list of diagnostics + diagnostics = ts.sortAndDeduplicateDiagnostics(diagnostics); + return { + emitSkipped: false, + diagnostics: diagnostics, + sourceMaps: sourceMapDataList + }; + function isUniqueLocalName(name, container) { + for (var node = container; ts.isNodeDescendentOf(node, container); node = node.nextContainer) { + if (node.locals && ts.hasProperty(node.locals, name)) { + // We conservatively include alias symbols to cover cases where they're emitted as locals + if (node.locals[name].flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */)) { + return false; + } + } + } + return true; + } + function emitJavaScript(jsFilePath, root) { + var writer = ts.createTextWriter(newLine); + var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; + var currentSourceFile; + // name of an exporter function if file is a System external module + // System.register([...], function () {...}) + // exporting in System modules looks like: + // export var x; ... x = 1 + // => + // var x;... exporter("x", x = 1) + var exportFunctionForFile; + var generatedNameSet = {}; + var nodeToGeneratedName = []; + var computedPropertyNamesToGeneratedNames; + var extendsEmitted = false; + var decorateEmitted = false; + var paramEmitted = false; + var awaiterEmitted = false; + var tempFlags = 0; + var tempVariables; + var tempParameters; + var externalImports; + var exportSpecifiers; + var exportEquals; + var hasExportStars; + /** Write emitted output to disk */ + var writeEmittedFiles = writeJavaScriptFile; + var detachedCommentsInfo; + var writeComment = ts.writeCommentRange; + /** Emit a node */ + var emit = emitNodeWithCommentsAndWithoutSourcemap; + /** Called just before starting emit of a node */ + var emitStart = function (node) { }; + /** Called once the emit of the node is done */ + var emitEnd = function (node) { }; + /** Emit the text for the given token that comes after startPos + * This by default writes the text provided with the given tokenKind + * but if optional emitFn callback is provided the text is emitted using the callback instead of default text + * @param tokenKind the kind of the token to search and emit + * @param startPos the position in the source to start searching for the token + * @param emitFn if given will be invoked to emit the text instead of actual token emit */ + var emitToken = emitTokenText; + /** Called to before starting the lexical scopes as in function/class in the emitted code because of node + * @param scopeDeclaration node that starts the lexical scope + * @param scopeName Optional name of this scope instead of deducing one from the declaration node */ + var scopeEmitStart = function (scopeDeclaration, scopeName) { }; + /** Called after coming out of the scope */ + var scopeEmitEnd = function () { }; + /** Sourcemap data that will get encoded */ + var sourceMapData; + /** If removeComments is true, no leading-comments needed to be emitted **/ + var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; + var moduleEmitDelegates = (_a = {}, + _a[5 /* ES6 */] = emitES6Module, + _a[2 /* AMD */] = emitAMDModule, + _a[4 /* System */] = emitSystemModule, + _a[3 /* UMD */] = emitUMDModule, + _a[1 /* CommonJS */] = emitCommonJSModule, + _a + ); + if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { + initializeEmitterWithSourceMaps(); + } + if (root) { + // Do not call emit directly. It does not set the currentSourceFile. + emitSourceFile(root); + } + else { + ts.forEach(host.getSourceFiles(), function (sourceFile) { + if (!isExternalModuleOrDeclarationFile(sourceFile)) { + emitSourceFile(sourceFile); + } + }); + } + writeLine(); + writeEmittedFiles(writer.getText(), /*writeByteOrderMark*/ compilerOptions.emitBOM); + return; + function emitSourceFile(sourceFile) { + currentSourceFile = sourceFile; + exportFunctionForFile = undefined; + emit(sourceFile); + } + function isUniqueName(name) { + return !resolver.hasGlobalName(name) && + !ts.hasProperty(currentSourceFile.identifiers, name) && + !ts.hasProperty(generatedNameSet, name); + } + // Return the next available name in the pattern _a ... _z, _0, _1, ... + // TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. + // Note that names generated by makeTempVariableName and makeUniqueName will never conflict. + function makeTempVariableName(flags) { + if (flags && !(tempFlags & flags)) { + var name_19 = flags === 268435456 /* _i */ ? "_i" : "_n"; + if (isUniqueName(name_19)) { + tempFlags |= flags; + return name_19; + } + } + while (true) { + var count = tempFlags & 268435455 /* CountMask */; + tempFlags++; + // Skip over 'i' and 'n' + if (count !== 8 && count !== 13) { + var name_20 = count < 26 ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); + if (isUniqueName(name_20)) { + return name_20; + } + } + } + } + // Generate a name that is unique within the current file and doesn't conflict with any names + // in global scope. The name is formed by adding an '_n' suffix to the specified base name, + // where n is a positive integer. Note that names generated by makeTempVariableName and + // makeUniqueName are guaranteed to never conflict. + function makeUniqueName(baseName) { + // Find the first unique 'name_n', where n is a positive number + if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) { + baseName += "_"; + } + var i = 1; + while (true) { + var generatedName = baseName + i; + if (isUniqueName(generatedName)) { + return generatedNameSet[generatedName] = generatedName; + } + i++; + } + } + function generateNameForModuleOrEnum(node) { + var name = node.name.text; + // Use module/enum name itself if it is unique, otherwise make a unique variation + return isUniqueLocalName(name, node) ? name : makeUniqueName(name); + } + function generateNameForImportOrExportDeclaration(node) { + var expr = ts.getExternalModuleName(node); + var baseName = expr.kind === 9 /* StringLiteral */ ? + ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; + return makeUniqueName(baseName); + } + function generateNameForExportDefault() { + return makeUniqueName("default"); + } + function generateNameForClassExpression() { + return makeUniqueName("class"); + } + function generateNameForNode(node) { + switch (node.kind) { + case 69 /* Identifier */: + return makeUniqueName(node.text); + case 218 /* ModuleDeclaration */: + case 217 /* EnumDeclaration */: + return generateNameForModuleOrEnum(node); + case 222 /* ImportDeclaration */: + case 228 /* ExportDeclaration */: + return generateNameForImportOrExportDeclaration(node); + case 213 /* FunctionDeclaration */: + case 214 /* ClassDeclaration */: + case 227 /* ExportAssignment */: + return generateNameForExportDefault(); + case 186 /* ClassExpression */: + return generateNameForClassExpression(); + } + } + function getGeneratedNameForNode(node) { + var id = ts.getNodeId(node); + return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = ts.unescapeIdentifier(generateNameForNode(node))); + } + function initializeEmitterWithSourceMaps() { + var sourceMapDir; // The directory in which sourcemap will be + // Current source map file and its index in the sources list + var sourceMapSourceIndex = -1; + // Names and its index map + var sourceMapNameIndexMap = {}; + var sourceMapNameIndices = []; + function getSourceMapNameIndex() { + return sourceMapNameIndices.length ? ts.lastOrUndefined(sourceMapNameIndices) : -1; + } + // Last recorded and encoded spans + var lastRecordedSourceMapSpan; + var lastEncodedSourceMapSpan = { + emittedLine: 1, + emittedColumn: 1, + sourceLine: 1, + sourceColumn: 1, + sourceIndex: 0 + }; + var lastEncodedNameIndex = 0; + // Encoding for sourcemap span + function encodeLastRecordedSourceMapSpan() { + if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { + return; + } + var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; + // Line/Comma delimiters + if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { + // Emit comma to separate the entry + if (sourceMapData.sourceMapMappings) { + sourceMapData.sourceMapMappings += ","; + } + } + else { + // Emit line delimiters + for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { + sourceMapData.sourceMapMappings += ";"; + } + prevEncodedEmittedColumn = 1; + } + // 1. Relative Column 0 based + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); + // 2. Relative sourceIndex + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); + // 3. Relative sourceLine 0 based + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); + // 4. Relative sourceColumn 0 based + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); + // 5. Relative namePosition 0 based + if (lastRecordedSourceMapSpan.nameIndex >= 0) { + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); + lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; + } + lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; + sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); + function base64VLQFormatEncode(inValue) { + function base64FormatEncode(inValue) { + if (inValue < 64) { + return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + } + // Add a new least significant bit that has the sign of the value. + // if negative number the least significant bit that gets added to the number has value 1 + // else least significant bit value that gets added is 0 + // eg. -1 changes to binary : 01 [1] => 3 + // +1 changes to binary : 01 [0] => 2 + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + // Encode 5 bits at a time starting from least significant bits + var encodedStr = ""; + do { + var currentDigit = inValue & 31; // 11111 + inValue = inValue >> 5; + if (inValue > 0) { + // There are still more digits to decode, set the msb (6th bit) + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + base64FormatEncode(currentDigit); + } while (inValue > 0); + return encodedStr; + } + } + function recordSourceMapSpan(pos) { + var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); + // Convert the location to be one-based. + sourceLinePos.line++; + sourceLinePos.character++; + var emittedLine = writer.getLine(); + var emittedColumn = writer.getColumn(); + // If this location wasn't recorded or the location in source is going backwards, record the span + if (!lastRecordedSourceMapSpan || + lastRecordedSourceMapSpan.emittedLine !== emittedLine || + lastRecordedSourceMapSpan.emittedColumn !== emittedColumn || + (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && + (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || + (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { + // Encode the last recordedSpan before assigning new + encodeLastRecordedSourceMapSpan(); + // New span + lastRecordedSourceMapSpan = { + emittedLine: emittedLine, + emittedColumn: emittedColumn, + sourceLine: sourceLinePos.line, + sourceColumn: sourceLinePos.character, + nameIndex: getSourceMapNameIndex(), + sourceIndex: sourceMapSourceIndex + }; + } + else { + // Take the new pos instead since there is no change in emittedLine and column since last location + lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; + lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; + lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; + } + } + function recordEmitNodeStartSpan(node) { + // Get the token pos after skipping to the token (ignoring the leading trivia) + recordSourceMapSpan(ts.skipTrivia(currentSourceFile.text, node.pos)); + } + function recordEmitNodeEndSpan(node) { + recordSourceMapSpan(node.end); + } + function writeTextWithSpanRecord(tokenKind, startPos, emitFn) { + var tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos); + recordSourceMapSpan(tokenStartPos); + var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); + recordSourceMapSpan(tokenEndPos); + return tokenEndPos; + } + function recordNewSourceFileStart(node) { + // Add the file to tsFilePaths + // If sourceroot option: Use the relative path corresponding to the common directory path + // otherwise source locations relative to map file location + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + sourceMapData.sourceMapSources.push(ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true)); + sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1; + // The one that can be used from program to get the actual source file + sourceMapData.inputSourceFileNames.push(node.fileName); + if (compilerOptions.inlineSources) { + if (!sourceMapData.sourceMapSourcesContent) { + sourceMapData.sourceMapSourcesContent = []; + } + sourceMapData.sourceMapSourcesContent.push(node.text); + } + } + function recordScopeNameOfNode(node, scopeName) { + function recordScopeNameIndex(scopeNameIndex) { + sourceMapNameIndices.push(scopeNameIndex); + } + function recordScopeNameStart(scopeName) { + var scopeNameIndex = -1; + if (scopeName) { + var parentIndex = getSourceMapNameIndex(); + if (parentIndex !== -1) { + // Child scopes are always shown with a dot (even if they have no name), + // unless it is a computed property. Then it is shown with brackets, + // but the brackets are included in the name. + var name_21 = node.name; + if (!name_21 || name_21.kind !== 136 /* ComputedPropertyName */) { + scopeName = "." + scopeName; + } + scopeName = sourceMapData.sourceMapNames[parentIndex] + scopeName; + } + scopeNameIndex = ts.getProperty(sourceMapNameIndexMap, scopeName); + if (scopeNameIndex === undefined) { + scopeNameIndex = sourceMapData.sourceMapNames.length; + sourceMapData.sourceMapNames.push(scopeName); + sourceMapNameIndexMap[scopeName] = scopeNameIndex; + } + } + recordScopeNameIndex(scopeNameIndex); + } + if (scopeName) { + // The scope was already given a name use it + recordScopeNameStart(scopeName); + } + else if (node.kind === 213 /* FunctionDeclaration */ || + node.kind === 173 /* FunctionExpression */ || + node.kind === 143 /* MethodDeclaration */ || + node.kind === 142 /* MethodSignature */ || + node.kind === 145 /* GetAccessor */ || + node.kind === 146 /* SetAccessor */ || + node.kind === 218 /* ModuleDeclaration */ || + node.kind === 214 /* ClassDeclaration */ || + node.kind === 217 /* EnumDeclaration */) { + // Declaration and has associated name use it + if (node.name) { + var name_22 = node.name; + // For computed property names, the text will include the brackets + scopeName = name_22.kind === 136 /* ComputedPropertyName */ + ? ts.getTextOfNode(name_22) + : node.name.text; + } + recordScopeNameStart(scopeName); + } + else { + // Block just use the name from upper level scope + recordScopeNameIndex(getSourceMapNameIndex()); + } + } + function recordScopeNameEnd() { + sourceMapNameIndices.pop(); + } + ; + function writeCommentRangeWithMap(curentSourceFile, writer, comment, newLine) { + recordSourceMapSpan(comment.pos); + ts.writeCommentRange(currentSourceFile, writer, comment, newLine); + recordSourceMapSpan(comment.end); + } + function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings, sourcesContent) { + if (typeof JSON !== "undefined") { + var map_1 = { + version: version, + file: file, + sourceRoot: sourceRoot, + sources: sources, + names: names, + mappings: mappings + }; + if (sourcesContent !== undefined) { + map_1.sourcesContent = sourcesContent; + } + return JSON.stringify(map_1); + } + return "{\"version\":" + version + ",\"file\":\"" + ts.escapeString(file) + "\",\"sourceRoot\":\"" + ts.escapeString(sourceRoot) + "\",\"sources\":[" + serializeStringArray(sources) + "],\"names\":[" + serializeStringArray(names) + "],\"mappings\":\"" + ts.escapeString(mappings) + "\" " + (sourcesContent !== undefined ? ",\"sourcesContent\":[" + serializeStringArray(sourcesContent) + "]" : "") + "}"; + function serializeStringArray(list) { + var output = ""; + for (var i = 0, n = list.length; i < n; i++) { + if (i) { + output += ","; + } + output += "\"" + ts.escapeString(list[i]) + "\""; + } + return output; + } + } + function writeJavaScriptAndSourceMapFile(emitOutput, writeByteOrderMark) { + encodeLastRecordedSourceMapSpan(); + var sourceMapText = serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings, sourceMapData.sourceMapSourcesContent); + sourceMapDataList.push(sourceMapData); + var sourceMapUrl; + if (compilerOptions.inlineSourceMap) { + // Encode the sourceMap into the sourceMap url + var base64SourceMapText = ts.convertToBase64(sourceMapText); + sourceMapUrl = "//# sourceMappingURL=data:application/json;base64," + base64SourceMapText; + } + else { + // Write source map file + ts.writeFile(host, diagnostics, sourceMapData.sourceMapFilePath, sourceMapText, /*writeByteOrderMark*/ false); + sourceMapUrl = "//# sourceMappingURL=" + sourceMapData.jsSourceMappingURL; + } + // Write sourcemap url to the js file and write the js file + writeJavaScriptFile(emitOutput + sourceMapUrl, writeByteOrderMark); + } + // Initialize source map data + var sourceMapJsFile = ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)); + sourceMapData = { + sourceMapFilePath: jsFilePath + ".map", + jsSourceMappingURL: sourceMapJsFile + ".map", + sourceMapFile: sourceMapJsFile, + sourceMapSourceRoot: compilerOptions.sourceRoot || "", + sourceMapSources: [], + inputSourceFileNames: [], + sourceMapNames: [], + sourceMapMappings: "", + sourceMapSourcesContent: undefined, + sourceMapDecodedMappings: [] + }; + // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the + // relative paths of the sources list in the sourcemap + sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); + if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47 /* slash */) { + sourceMapData.sourceMapSourceRoot += ts.directorySeparator; + } + if (compilerOptions.mapRoot) { + sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); + if (root) { + // For modules or multiple emit files the mapRoot will have directory structure like the sources + // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(root, host, sourceMapDir)); + } + if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { + // The relative paths are relative to the common directory + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(jsFilePath)), // get the relative sourceMapDir path based on jsFilePath + ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap + host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + } + else { + sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); + } + } + else { + sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath)); + } + function emitNodeWithSourceMap(node) { + if (node) { + if (ts.nodeIsSynthesized(node)) { + return emitNodeWithoutSourceMap(node); + } + if (node.kind !== 248 /* SourceFile */) { + recordEmitNodeStartSpan(node); + emitNodeWithoutSourceMap(node); + recordEmitNodeEndSpan(node); + } + else { + recordNewSourceFileStart(node); + emitNodeWithoutSourceMap(node); + } + } + } + function emitNodeWithCommentsAndWithSourcemap(node) { + emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); + } + writeEmittedFiles = writeJavaScriptAndSourceMapFile; + emit = emitNodeWithCommentsAndWithSourcemap; + emitStart = recordEmitNodeStartSpan; + emitEnd = recordEmitNodeEndSpan; + emitToken = writeTextWithSpanRecord; + scopeEmitStart = recordScopeNameOfNode; + scopeEmitEnd = recordScopeNameEnd; + writeComment = writeCommentRangeWithMap; + } + function writeJavaScriptFile(emitOutput, writeByteOrderMark) { + ts.writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark); + } + // Create a temporary variable with a unique unused name. + function createTempVariable(flags) { + var result = ts.createSynthesizedNode(69 /* Identifier */); + result.text = makeTempVariableName(flags); + return result; + } + function recordTempDeclaration(name) { + if (!tempVariables) { + tempVariables = []; + } + tempVariables.push(name); + } + function createAndRecordTempVariable(flags) { + var temp = createTempVariable(flags); + recordTempDeclaration(temp); + return temp; + } + function emitTempDeclarations(newLine) { + if (tempVariables) { + if (newLine) { + writeLine(); + } + else { + write(" "); + } + write("var "); + emitCommaList(tempVariables); + write(";"); + } + } + function emitTokenText(tokenKind, startPos, emitFn) { + var tokenString = ts.tokenToString(tokenKind); + if (emitFn) { + emitFn(); + } + else { + write(tokenString); + } + return startPos + tokenString.length; + } + function emitOptional(prefix, node) { + if (node) { + write(prefix); + emit(node); + } + } + function emitParenthesizedIf(node, parenthesized) { + if (parenthesized) { + write("("); + } + emit(node); + if (parenthesized) { + write(")"); + } + } + function emitTrailingCommaIfPresent(nodeList) { + if (nodeList.hasTrailingComma) { + write(","); + } + } + function emitLinePreservingList(parent, nodes, allowTrailingComma, spacesBetweenBraces) { + ts.Debug.assert(nodes.length > 0); + increaseIndent(); + if (nodeStartPositionsAreOnSameLine(parent, nodes[0])) { + if (spacesBetweenBraces) { + write(" "); + } + } + else { + writeLine(); + } + for (var i = 0, n = nodes.length; i < n; i++) { + if (i) { + if (nodeEndIsOnSameLineAsNodeStart(nodes[i - 1], nodes[i])) { + write(", "); + } + else { + write(","); + writeLine(); + } + } + emit(nodes[i]); + } + if (nodes.hasTrailingComma && allowTrailingComma) { + write(","); + } + decreaseIndent(); + if (nodeEndPositionsAreOnSameLine(parent, ts.lastOrUndefined(nodes))) { + if (spacesBetweenBraces) { + write(" "); + } + } + else { + writeLine(); + } + } + function emitList(nodes, start, count, multiLine, trailingComma, leadingComma, noTrailingNewLine, emitNode) { + if (!emitNode) { + emitNode = emit; + } + for (var i = 0; i < count; i++) { + if (multiLine) { + if (i || leadingComma) { + write(","); + } + writeLine(); + } + else { + if (i || leadingComma) { + write(", "); + } + } + var node = nodes[start + i]; + // This emitting is to make sure we emit following comment properly + // ...(x, /*comment1*/ y)... + // ^ => node.pos + // "comment1" is not considered leading comment for "y" but rather + // considered as trailing comment of the previous node. + emitTrailingCommentsOfPosition(node.pos); + emitNode(node); + leadingComma = true; + } + if (trailingComma) { + write(","); + } + if (multiLine && !noTrailingNewLine) { + writeLine(); + } + return count; + } + function emitCommaList(nodes) { + if (nodes) { + emitList(nodes, 0, nodes.length, /*multiline*/ false, /*trailingComma*/ false); + } + } + function emitLines(nodes) { + emitLinesStartingAt(nodes, /*startIndex*/ 0); + } + function emitLinesStartingAt(nodes, startIndex) { + for (var i = startIndex; i < nodes.length; i++) { + writeLine(); + emit(nodes[i]); + } + } + function isBinaryOrOctalIntegerLiteral(node, text) { + if (node.kind === 8 /* NumericLiteral */ && text.length > 1) { + switch (text.charCodeAt(1)) { + case 98 /* b */: + case 66 /* B */: + case 111 /* o */: + case 79 /* O */: + return true; + } + } + return false; + } + function emitLiteral(node) { + var text = getLiteralText(node); + if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { + writer.writeLiteral(text); + } + else if (languageVersion < 2 /* ES6 */ && isBinaryOrOctalIntegerLiteral(node, text)) { + write(node.text); + } + else { + write(text); + } + } + function getLiteralText(node) { + // Any template literal or string literal with an extended escape + // (e.g. "\u{0067}") will need to be downleveled as a escaped string literal. + if (languageVersion < 2 /* ES6 */ && (ts.isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { + return getQuotedEscapedLiteralText("\"", node.text, "\""); + } + // If we don't need to downlevel and we can reach the original source text using + // the node's parent reference, then simply get the text as it was originally written. + if (node.parent) { + return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + } + // If we can't reach the original source text, use the canonical form if it's a number, + // or an escaped quoted form of the original text if it's string-like. + switch (node.kind) { + case 9 /* StringLiteral */: + return getQuotedEscapedLiteralText("\"", node.text, "\""); + case 11 /* NoSubstitutionTemplateLiteral */: + return getQuotedEscapedLiteralText("`", node.text, "`"); + case 12 /* TemplateHead */: + return getQuotedEscapedLiteralText("`", node.text, "${"); + case 13 /* TemplateMiddle */: + return getQuotedEscapedLiteralText("}", node.text, "${"); + case 14 /* TemplateTail */: + return getQuotedEscapedLiteralText("}", node.text, "`"); + case 8 /* NumericLiteral */: + return node.text; + } + ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + } + function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { + return leftQuote + ts.escapeNonAsciiCharacters(ts.escapeString(text)) + rightQuote; + } + function emitDownlevelRawTemplateLiteral(node) { + // Find original source text, since we need to emit the raw strings of the tagged template. + // The raw strings contain the (escaped) strings of what the user wrote. + // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". + var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), + // thus we need to remove those characters. + // First template piece starts with "`", others with "}" + // Last template piece ends with "`", others with "${" + var isLast = node.kind === 11 /* NoSubstitutionTemplateLiteral */ || node.kind === 14 /* TemplateTail */; + text = text.substring(1, text.length - (isLast ? 1 : 2)); + // Newline normalization: + // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's + // and LineTerminatorSequences are normalized to for both TV and TRV. + text = text.replace(/\r\n?/g, "\n"); + text = ts.escapeString(text); + write("\"" + text + "\""); + } + function emitDownlevelTaggedTemplateArray(node, literalEmitter) { + write("["); + if (node.template.kind === 11 /* NoSubstitutionTemplateLiteral */) { + literalEmitter(node.template); + } + else { + literalEmitter(node.template.head); + ts.forEach(node.template.templateSpans, function (child) { + write(", "); + literalEmitter(child.literal); + }); + } + write("]"); + } + function emitDownlevelTaggedTemplate(node) { + var tempVariable = createAndRecordTempVariable(0 /* Auto */); + write("("); + emit(tempVariable); + write(" = "); + emitDownlevelTaggedTemplateArray(node, emit); + write(", "); + emit(tempVariable); + write(".raw = "); + emitDownlevelTaggedTemplateArray(node, emitDownlevelRawTemplateLiteral); + write(", "); + emitParenthesizedIf(node.tag, needsParenthesisForPropertyAccessOrInvocation(node.tag)); + write("("); + emit(tempVariable); + // Now we emit the expressions + if (node.template.kind === 183 /* TemplateExpression */) { + ts.forEach(node.template.templateSpans, function (templateSpan) { + write(", "); + var needsParens = templateSpan.expression.kind === 181 /* BinaryExpression */ + && templateSpan.expression.operatorToken.kind === 24 /* CommaToken */; + emitParenthesizedIf(templateSpan.expression, needsParens); + }); + } + write("))"); + } + function emitTemplateExpression(node) { + // In ES6 mode and above, we can simply emit each portion of a template in order, but in + // ES3 & ES5 we must convert the template expression into a series of string concatenations. + if (languageVersion >= 2 /* ES6 */) { + ts.forEachChild(node, emit); + return; + } + var emitOuterParens = ts.isExpression(node.parent) + && templateNeedsParens(node, node.parent); + if (emitOuterParens) { + write("("); + } + var headEmitted = false; + if (shouldEmitTemplateHead()) { + emitLiteral(node.head); + headEmitted = true; + } + for (var i = 0, n = node.templateSpans.length; i < n; i++) { + var templateSpan = node.templateSpans[i]; + // Check if the expression has operands and binds its operands less closely than binary '+'. + // If it does, we need to wrap the expression in parentheses. Otherwise, something like + // `abc${ 1 << 2 }` + // becomes + // "abc" + 1 << 2 + "" + // which is really + // ("abc" + 1) << (2 + "") + // rather than + // "abc" + (1 << 2) + "" + var needsParens = templateSpan.expression.kind !== 172 /* ParenthesizedExpression */ + && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1 /* GreaterThan */; + if (i > 0 || headEmitted) { + // If this is the first span and the head was not emitted, then this templateSpan's + // expression will be the first to be emitted. Don't emit the preceding ' + ' in that + // case. + write(" + "); + } + emitParenthesizedIf(templateSpan.expression, needsParens); + // Only emit if the literal is non-empty. + // The binary '+' operator is left-associative, so the first string concatenation + // with the head will force the result up to this point to be a string. + // Emitting a '+ ""' has no semantic effect for middles and tails. + if (templateSpan.literal.text.length !== 0) { + write(" + "); + emitLiteral(templateSpan.literal); + } + } + if (emitOuterParens) { + write(")"); + } + function shouldEmitTemplateHead() { + // If this expression has an empty head literal and the first template span has a non-empty + // literal, then emitting the empty head literal is not necessary. + // `${ foo } and ${ bar }` + // can be emitted as + // foo + " and " + bar + // This is because it is only required that one of the first two operands in the emit + // output must be a string literal, so that the other operand and all following operands + // are forced into strings. + // + // If the first template span has an empty literal, then the head must still be emitted. + // `${ foo }${ bar }` + // must still be emitted as + // "" + foo + bar + // There is always atleast one templateSpan in this code path, since + // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() + ts.Debug.assert(node.templateSpans.length !== 0); + return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; + } + function templateNeedsParens(template, parent) { + switch (parent.kind) { + case 168 /* CallExpression */: + case 169 /* NewExpression */: + return parent.expression === template; + case 170 /* TaggedTemplateExpression */: + case 172 /* ParenthesizedExpression */: + return false; + default: + return comparePrecedenceToBinaryPlus(parent) !== -1 /* LessThan */; + } + } + /** + * Returns whether the expression has lesser, greater, + * or equal precedence to the binary '+' operator + */ + function comparePrecedenceToBinaryPlus(expression) { + // All binary expressions have lower precedence than '+' apart from '*', '/', and '%' + // which have greater precedence and '-' which has equal precedence. + // All unary operators have a higher precedence apart from yield. + // Arrow functions and conditionals have a lower precedence, + // although we convert the former into regular function expressions in ES5 mode, + // and in ES6 mode this function won't get called anyway. + // + // TODO (drosen): Note that we need to account for the upcoming 'yield' and + // spread ('...') unary operators that are anticipated for ES6. + switch (expression.kind) { + case 181 /* BinaryExpression */: + switch (expression.operatorToken.kind) { + case 37 /* AsteriskToken */: + case 39 /* SlashToken */: + case 40 /* PercentToken */: + return 1 /* GreaterThan */; + case 35 /* PlusToken */: + case 36 /* MinusToken */: + return 0 /* EqualTo */; + default: + return -1 /* LessThan */; + } + case 184 /* YieldExpression */: + case 182 /* ConditionalExpression */: + return -1 /* LessThan */; + default: + return 1 /* GreaterThan */; + } + } + } + function emitTemplateSpan(span) { + emit(span.expression); + emit(span.literal); + } + function jsxEmitReact(node) { + /// Emit a tag name, which is either '"div"' for lower-cased names, or + /// 'Div' for upper-cased or dotted names + function emitTagName(name) { + if (name.kind === 69 /* Identifier */ && ts.isIntrinsicJsxName(name.text)) { + write("\""); + emit(name); + write("\""); + } + else { + emit(name); + } + } + /// Emit an attribute name, which is quoted if it needs to be quoted. Because + /// these emit into an object literal property name, we don't need to be worried + /// about keywords, just non-identifier characters + function emitAttributeName(name) { + if (/[A-Za-z_]+[\w*]/.test(name.text)) { + write("\""); + emit(name); + write("\""); + } + else { + emit(name); + } + } + /// Emit an name/value pair for an attribute (e.g. "x: 3") + function emitJsxAttribute(node) { + emitAttributeName(node.name); + write(": "); + if (node.initializer) { + emit(node.initializer); + } + else { + write("true"); + } + } + function emitJsxElement(openingNode, children) { + var syntheticReactRef = ts.createSynthesizedNode(69 /* Identifier */); + syntheticReactRef.text = "React"; + syntheticReactRef.parent = openingNode; + // Call React.createElement(tag, ... + emitLeadingComments(openingNode); + emitExpressionIdentifier(syntheticReactRef); + write(".createElement("); + emitTagName(openingNode.tagName); + write(", "); + // Attribute list + if (openingNode.attributes.length === 0) { + // When there are no attributes, React wants "null" + write("null"); + } + else { + // Either emit one big object literal (no spread attribs), or + // a call to React.__spread + var attrs = openingNode.attributes; + if (ts.forEach(attrs, function (attr) { return attr.kind === 239 /* JsxSpreadAttribute */; })) { + emitExpressionIdentifier(syntheticReactRef); + write(".__spread("); + var haveOpenedObjectLiteral = false; + for (var i_1 = 0; i_1 < attrs.length; i_1++) { + if (attrs[i_1].kind === 239 /* JsxSpreadAttribute */) { + // If this is the first argument, we need to emit a {} as the first argument + if (i_1 === 0) { + write("{}, "); + } + if (haveOpenedObjectLiteral) { + write("}"); + haveOpenedObjectLiteral = false; + } + if (i_1 > 0) { + write(", "); + } + emit(attrs[i_1].expression); + } + else { + ts.Debug.assert(attrs[i_1].kind === 238 /* JsxAttribute */); + if (haveOpenedObjectLiteral) { + write(", "); + } + else { + haveOpenedObjectLiteral = true; + if (i_1 > 0) { + write(", "); + } + write("{"); + } + emitJsxAttribute(attrs[i_1]); + } + } + if (haveOpenedObjectLiteral) + write("}"); + write(")"); // closing paren to React.__spread( + } + else { + // One object literal with all the attributes in them + write("{"); + for (var i = 0; i < attrs.length; i++) { + if (i > 0) { + write(", "); + } + emitJsxAttribute(attrs[i]); + } + write("}"); + } + } + // Children + if (children) { + for (var i = 0; i < children.length; i++) { + // Don't emit empty expressions + if (children[i].kind === 240 /* JsxExpression */ && !(children[i].expression)) { + continue; + } + // Don't emit empty strings + if (children[i].kind === 236 /* JsxText */) { + var text = getTextToEmit(children[i]); + if (text !== undefined) { + write(", \""); + write(text); + write("\""); + } + } + else { + write(", "); + emit(children[i]); + } + } + } + // Closing paren + write(")"); // closes "React.createElement(" + emitTrailingComments(openingNode); + } + if (node.kind === 233 /* JsxElement */) { + emitJsxElement(node.openingElement, node.children); + } + else { + ts.Debug.assert(node.kind === 234 /* JsxSelfClosingElement */); + emitJsxElement(node); + } + } + function jsxEmitPreserve(node) { + function emitJsxAttribute(node) { + emit(node.name); + if (node.initializer) { + write("="); + emit(node.initializer); + } + } + function emitJsxSpreadAttribute(node) { + write("{..."); + emit(node.expression); + write("}"); + } + function emitAttributes(attribs) { + for (var i = 0, n = attribs.length; i < n; i++) { + if (i > 0) { + write(" "); + } + if (attribs[i].kind === 239 /* JsxSpreadAttribute */) { + emitJsxSpreadAttribute(attribs[i]); + } + else { + ts.Debug.assert(attribs[i].kind === 238 /* JsxAttribute */); + emitJsxAttribute(attribs[i]); + } + } + } + function emitJsxOpeningOrSelfClosingElement(node) { + write("<"); + emit(node.tagName); + if (node.attributes.length > 0 || (node.kind === 234 /* JsxSelfClosingElement */)) { + write(" "); + } + emitAttributes(node.attributes); + if (node.kind === 234 /* JsxSelfClosingElement */) { + write("/>"); + } + else { + write(">"); + } + } + function emitJsxClosingElement(node) { + write(""); + } + function emitJsxElement(node) { + emitJsxOpeningOrSelfClosingElement(node.openingElement); + for (var i = 0, n = node.children.length; i < n; i++) { + emit(node.children[i]); + } + emitJsxClosingElement(node.closingElement); + } + if (node.kind === 233 /* JsxElement */) { + emitJsxElement(node); + } + else { + ts.Debug.assert(node.kind === 234 /* JsxSelfClosingElement */); + emitJsxOpeningOrSelfClosingElement(node); + } + } + // This function specifically handles numeric/string literals for enum and accessor 'identifiers'. + // In a sense, it does not actually emit identifiers as much as it declares a name for a specific property. + // For example, this is utilized when feeding in a result to Object.defineProperty. + function emitExpressionForPropertyName(node) { + ts.Debug.assert(node.kind !== 163 /* BindingElement */); + if (node.kind === 9 /* StringLiteral */) { + emitLiteral(node); + } + else if (node.kind === 136 /* ComputedPropertyName */) { + // if this is a decorated computed property, we will need to capture the result + // of the property expression so that we can apply decorators later. This is to ensure + // we don't introduce unintended side effects: + // + // class C { + // [_a = x]() { } + // } + // + // The emit for the decorated computed property decorator is: + // + // __decorate([dec], C.prototype, _a, Object.getOwnPropertyDescriptor(C.prototype, _a)); + // + if (ts.nodeIsDecorated(node.parent)) { + if (!computedPropertyNamesToGeneratedNames) { + computedPropertyNamesToGeneratedNames = []; + } + var generatedName = computedPropertyNamesToGeneratedNames[ts.getNodeId(node)]; + if (generatedName) { + // we have already generated a variable for this node, write that value instead. + write(generatedName); + return; + } + generatedName = createAndRecordTempVariable(0 /* Auto */).text; + computedPropertyNamesToGeneratedNames[ts.getNodeId(node)] = generatedName; + write(generatedName); + write(" = "); + } + emit(node.expression); + } + else { + write("\""); + if (node.kind === 8 /* NumericLiteral */) { + write(node.text); + } + else { + writeTextOfNode(currentSourceFile, node); + } + write("\""); + } + } + function isExpressionIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 164 /* ArrayLiteralExpression */: + case 189 /* AsExpression */: + case 181 /* BinaryExpression */: + case 168 /* CallExpression */: + case 241 /* CaseClause */: + case 136 /* ComputedPropertyName */: + case 182 /* ConditionalExpression */: + case 139 /* Decorator */: + case 175 /* DeleteExpression */: + case 197 /* DoStatement */: + case 167 /* ElementAccessExpression */: + case 227 /* ExportAssignment */: + case 195 /* ExpressionStatement */: + case 188 /* ExpressionWithTypeArguments */: + case 199 /* ForStatement */: + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + case 196 /* IfStatement */: + case 234 /* JsxSelfClosingElement */: + case 235 /* JsxOpeningElement */: + case 239 /* JsxSpreadAttribute */: + case 240 /* JsxExpression */: + case 169 /* NewExpression */: + case 172 /* ParenthesizedExpression */: + case 180 /* PostfixUnaryExpression */: + case 179 /* PrefixUnaryExpression */: + case 204 /* ReturnStatement */: + case 246 /* ShorthandPropertyAssignment */: + case 185 /* SpreadElementExpression */: + case 206 /* SwitchStatement */: + case 170 /* TaggedTemplateExpression */: + case 190 /* TemplateSpan */: + case 208 /* ThrowStatement */: + case 171 /* TypeAssertionExpression */: + case 176 /* TypeOfExpression */: + case 177 /* VoidExpression */: + case 198 /* WhileStatement */: + case 205 /* WithStatement */: + case 184 /* YieldExpression */: + return true; + case 163 /* BindingElement */: + case 247 /* EnumMember */: + case 138 /* Parameter */: + case 245 /* PropertyAssignment */: + case 141 /* PropertyDeclaration */: + case 211 /* VariableDeclaration */: + return parent.initializer === node; + case 166 /* PropertyAccessExpression */: + return parent.expression === node; + case 174 /* ArrowFunction */: + case 173 /* FunctionExpression */: + return parent.body === node; + case 221 /* ImportEqualsDeclaration */: + return parent.moduleReference === node; + case 135 /* QualifiedName */: + return parent.left === node; + } + return false; + } + function emitExpressionIdentifier(node) { + if (resolver.getNodeCheckFlags(node) & 2048 /* LexicalArguments */) { + write("_arguments"); + return; + } + var container = resolver.getReferencedExportContainer(node); + if (container) { + if (container.kind === 248 /* SourceFile */) { + // Identifier references module export + if (modulekind !== 5 /* ES6 */ && modulekind !== 4 /* System */) { + write("exports."); + } + } + else { + // Identifier references namespace export + write(getGeneratedNameForNode(container)); + write("."); + } + } + else { + if (modulekind !== 5 /* ES6 */) { + var declaration = resolver.getReferencedImportDeclaration(node); + if (declaration) { + if (declaration.kind === 223 /* ImportClause */) { + // Identifier references default import + write(getGeneratedNameForNode(declaration.parent)); + write(languageVersion === 0 /* ES3 */ ? "[\"default\"]" : ".default"); + return; + } + else if (declaration.kind === 226 /* ImportSpecifier */) { + // Identifier references named import + write(getGeneratedNameForNode(declaration.parent.parent.parent)); + var name_23 = declaration.propertyName || declaration.name; + var identifier = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, name_23); + if (languageVersion === 0 /* ES3 */ && identifier === "default") { + write("[\"default\"]"); + } + else { + write("."); + write(identifier); + } + return; + } + } + } + if (languageVersion !== 2 /* ES6 */) { + var declaration = resolver.getReferencedNestedRedeclaration(node); + if (declaration) { + write(getGeneratedNameForNode(declaration.name)); + return; + } + } + } + if (ts.nodeIsSynthesized(node)) { + write(node.text); + } + else { + writeTextOfNode(currentSourceFile, node); + } + } + function isNameOfNestedRedeclaration(node) { + if (languageVersion < 2 /* ES6 */) { + var parent_6 = node.parent; + switch (parent_6.kind) { + case 163 /* BindingElement */: + case 214 /* ClassDeclaration */: + case 217 /* EnumDeclaration */: + case 211 /* VariableDeclaration */: + return parent_6.name === node && resolver.isNestedRedeclaration(parent_6); + } + } + return false; + } + function emitIdentifier(node) { + if (!node.parent) { + write(node.text); + } + else if (isExpressionIdentifier(node)) { + emitExpressionIdentifier(node); + } + else if (isNameOfNestedRedeclaration(node)) { + write(getGeneratedNameForNode(node)); + } + else if (ts.nodeIsSynthesized(node)) { + write(node.text); + } + else { + writeTextOfNode(currentSourceFile, node); + } + } + function emitThis(node) { + if (resolver.getNodeCheckFlags(node) & 2 /* LexicalThis */) { + write("_this"); + } + else { + write("this"); + } + } + function emitSuper(node) { + if (languageVersion >= 2 /* ES6 */) { + write("super"); + } + else { + var flags = resolver.getNodeCheckFlags(node); + if (flags & 256 /* SuperInstance */) { + write("_super.prototype"); + } + else { + write("_super"); + } + } + } + function emitObjectBindingPattern(node) { + write("{ "); + var elements = node.elements; + emitList(elements, 0, elements.length, /*multiLine*/ false, /*trailingComma*/ elements.hasTrailingComma); + write(" }"); + } + function emitArrayBindingPattern(node) { + write("["); + var elements = node.elements; + emitList(elements, 0, elements.length, /*multiLine*/ false, /*trailingComma*/ elements.hasTrailingComma); + write("]"); + } + function emitBindingElement(node) { + if (node.propertyName) { + emit(node.propertyName); + write(": "); + } + if (node.dotDotDotToken) { + write("..."); + } + if (ts.isBindingPattern(node.name)) { + emit(node.name); + } + else { + emitModuleMemberName(node); + } + emitOptional(" = ", node.initializer); + } + function emitSpreadElementExpression(node) { + write("..."); + emit(node.expression); + } + function emitYieldExpression(node) { + write(ts.tokenToString(114 /* YieldKeyword */)); + if (node.asteriskToken) { + write("*"); + } + if (node.expression) { + write(" "); + emit(node.expression); + } + } + function emitAwaitExpression(node) { + var needsParenthesis = needsParenthesisForAwaitExpressionAsYield(node); + if (needsParenthesis) { + write("("); + } + write(ts.tokenToString(114 /* YieldKeyword */)); + write(" "); + emit(node.expression); + if (needsParenthesis) { + write(")"); + } + } + function needsParenthesisForAwaitExpressionAsYield(node) { + if (node.parent.kind === 181 /* BinaryExpression */ && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { + return true; + } + else if (node.parent.kind === 182 /* ConditionalExpression */ && node.parent.condition === node) { + return true; + } + return false; + } + function needsParenthesisForPropertyAccessOrInvocation(node) { + switch (node.kind) { + case 69 /* Identifier */: + case 164 /* ArrayLiteralExpression */: + case 166 /* PropertyAccessExpression */: + case 167 /* ElementAccessExpression */: + case 168 /* CallExpression */: + case 172 /* ParenthesizedExpression */: + // This list is not exhaustive and only includes those cases that are relevant + // to the check in emitArrayLiteral. More cases can be added as needed. + return false; + } + return true; + } + function emitListWithSpread(elements, needsUniqueCopy, multiLine, trailingComma, useConcat) { + var pos = 0; + var group = 0; + var length = elements.length; + while (pos < length) { + // Emit using the pattern .concat(, , ...) + if (group === 1 && useConcat) { + write(".concat("); + } + else if (group > 0) { + write(", "); + } + var e = elements[pos]; + if (e.kind === 185 /* SpreadElementExpression */) { + e = e.expression; + emitParenthesizedIf(e, /*parenthesized*/ group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); + pos++; + if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 164 /* ArrayLiteralExpression */) { + write(".slice()"); + } + } + else { + var i = pos; + while (i < length && elements[i].kind !== 185 /* SpreadElementExpression */) { + i++; + } + write("["); + if (multiLine) { + increaseIndent(); + } + emitList(elements, pos, i - pos, multiLine, trailingComma && i === length); + if (multiLine) { + decreaseIndent(); + } + write("]"); + pos = i; + } + group++; + } + if (group > 1) { + if (useConcat) { + write(")"); + } + } + } + function isSpreadElementExpression(node) { + return node.kind === 185 /* SpreadElementExpression */; + } + function emitArrayLiteral(node) { + var elements = node.elements; + if (elements.length === 0) { + write("[]"); + } + else if (languageVersion >= 2 /* ES6 */ || !ts.forEach(elements, isSpreadElementExpression)) { + write("["); + emitLinePreservingList(node, node.elements, elements.hasTrailingComma, /*spacesBetweenBraces:*/ false); + write("]"); + } + else { + emitListWithSpread(elements, /*needsUniqueCopy*/ true, /*multiLine*/ (node.flags & 2048 /* MultiLine */) !== 0, + /*trailingComma*/ elements.hasTrailingComma, /*useConcat*/ true); + } + } + function emitObjectLiteralBody(node, numElements) { + if (numElements === 0) { + write("{}"); + return; + } + write("{"); + if (numElements > 0) { + var properties = node.properties; + // If we are not doing a downlevel transformation for object literals, + // then try to preserve the original shape of the object literal. + // Otherwise just try to preserve the formatting. + if (numElements === properties.length) { + emitLinePreservingList(node, properties, /* allowTrailingComma */ languageVersion >= 1 /* ES5 */, /* spacesBetweenBraces */ true); + } + else { + var multiLine = (node.flags & 2048 /* MultiLine */) !== 0; + if (!multiLine) { + write(" "); + } + else { + increaseIndent(); + } + emitList(properties, 0, numElements, /*multiLine*/ multiLine, /*trailingComma*/ false); + if (!multiLine) { + write(" "); + } + else { + decreaseIndent(); + } + } + } + write("}"); + } + function emitDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex) { + var multiLine = (node.flags & 2048 /* MultiLine */) !== 0; + var properties = node.properties; + write("("); + if (multiLine) { + increaseIndent(); + } + // For computed properties, we need to create a unique handle to the object + // literal so we can modify it without risking internal assignments tainting the object. + var tempVar = createAndRecordTempVariable(0 /* Auto */); + // Write out the first non-computed properties + // (or all properties if none of them are computed), + // then emit the rest through indexing on the temp variable. + emit(tempVar); + write(" = "); + emitObjectLiteralBody(node, firstComputedPropertyIndex); + for (var i = firstComputedPropertyIndex, n = properties.length; i < n; i++) { + writeComma(); + var property = properties[i]; + emitStart(property); + if (property.kind === 145 /* GetAccessor */ || property.kind === 146 /* SetAccessor */) { + // TODO (drosen): Reconcile with 'emitMemberFunctions'. + var accessors = ts.getAllAccessorDeclarations(node.properties, property); + if (property !== accessors.firstAccessor) { + continue; + } + write("Object.defineProperty("); + emit(tempVar); + write(", "); + emitStart(node.name); + emitExpressionForPropertyName(property.name); + emitEnd(property.name); + write(", {"); + increaseIndent(); + if (accessors.getAccessor) { + writeLine(); + emitLeadingComments(accessors.getAccessor); + write("get: "); + emitStart(accessors.getAccessor); + write("function "); + emitSignatureAndBody(accessors.getAccessor); + emitEnd(accessors.getAccessor); + emitTrailingComments(accessors.getAccessor); + write(","); + } + if (accessors.setAccessor) { + writeLine(); + emitLeadingComments(accessors.setAccessor); + write("set: "); + emitStart(accessors.setAccessor); + write("function "); + emitSignatureAndBody(accessors.setAccessor); + emitEnd(accessors.setAccessor); + emitTrailingComments(accessors.setAccessor); + write(","); + } + writeLine(); + write("enumerable: true,"); + writeLine(); + write("configurable: true"); + decreaseIndent(); + writeLine(); + write("})"); + emitEnd(property); + } + else { + emitLeadingComments(property); + emitStart(property.name); + emit(tempVar); + emitMemberAccessForPropertyName(property.name); + emitEnd(property.name); + write(" = "); + if (property.kind === 245 /* PropertyAssignment */) { + emit(property.initializer); + } + else if (property.kind === 246 /* ShorthandPropertyAssignment */) { + emitExpressionIdentifier(property.name); + } + else if (property.kind === 143 /* MethodDeclaration */) { + emitFunctionDeclaration(property); + } + else { + ts.Debug.fail("ObjectLiteralElement type not accounted for: " + property.kind); + } + } + emitEnd(property); + } + writeComma(); + emit(tempVar); + if (multiLine) { + decreaseIndent(); + writeLine(); + } + write(")"); + function writeComma() { + if (multiLine) { + write(","); + writeLine(); + } + else { + write(", "); + } + } + } + function emitObjectLiteral(node) { + var properties = node.properties; + if (languageVersion < 2 /* ES6 */) { + var numProperties = properties.length; + // Find the first computed property. + // Everything until that point can be emitted as part of the initial object literal. + var numInitialNonComputedProperties = numProperties; + for (var i = 0, n = properties.length; i < n; i++) { + if (properties[i].name.kind === 136 /* ComputedPropertyName */) { + numInitialNonComputedProperties = i; + break; + } + } + var hasComputedProperty = numInitialNonComputedProperties !== properties.length; + if (hasComputedProperty) { + emitDownlevelObjectLiteralWithComputedProperties(node, numInitialNonComputedProperties); + return; + } + } + // Ordinary case: either the object has no computed properties + // or we're compiling with an ES6+ target. + emitObjectLiteralBody(node, properties.length); + } + function createBinaryExpression(left, operator, right, startsOnNewLine) { + var result = ts.createSynthesizedNode(181 /* BinaryExpression */, startsOnNewLine); + result.operatorToken = ts.createSynthesizedNode(operator); + result.left = left; + result.right = right; + return result; + } + function createPropertyAccessExpression(expression, name) { + var result = ts.createSynthesizedNode(166 /* PropertyAccessExpression */); + result.expression = parenthesizeForAccess(expression); + result.dotToken = ts.createSynthesizedNode(21 /* DotToken */); + result.name = name; + return result; + } + function createElementAccessExpression(expression, argumentExpression) { + var result = ts.createSynthesizedNode(167 /* ElementAccessExpression */); + result.expression = parenthesizeForAccess(expression); + result.argumentExpression = argumentExpression; + return result; + } + function parenthesizeForAccess(expr) { + // When diagnosing whether the expression needs parentheses, the decision should be based + // on the innermost expression in a chain of nested type assertions. + while (expr.kind === 171 /* TypeAssertionExpression */ || expr.kind === 189 /* AsExpression */) { + expr = expr.expression; + } + // isLeftHandSideExpression is almost the correct criterion for when it is not necessary + // to parenthesize the expression before a dot. The known exceptions are: + // + // NewExpression: + // new C.x -> not the same as (new C).x + // NumberLiteral + // 1.x -> not the same as (1).x + // + if (ts.isLeftHandSideExpression(expr) && + expr.kind !== 169 /* NewExpression */ && + expr.kind !== 8 /* NumericLiteral */) { + return expr; + } + var node = ts.createSynthesizedNode(172 /* ParenthesizedExpression */); + node.expression = expr; + return node; + } + function emitComputedPropertyName(node) { + write("["); + emitExpressionForPropertyName(node); + write("]"); + } + function emitMethod(node) { + if (languageVersion >= 2 /* ES6 */ && node.asteriskToken) { + write("*"); + } + emit(node.name); + if (languageVersion < 2 /* ES6 */) { + write(": function "); + } + emitSignatureAndBody(node); + } + function emitPropertyAssignment(node) { + emit(node.name); + write(": "); + // This is to ensure that we emit comment in the following case: + // For example: + // obj = { + // id: /*comment1*/ ()=>void + // } + // "comment1" is not considered to be leading comment for node.initializer + // but rather a trailing comment on the previous node. + emitTrailingCommentsOfPosition(node.initializer.pos); + emit(node.initializer); + } + // Return true if identifier resolves to an exported member of a namespace + function isNamespaceExportReference(node) { + var container = resolver.getReferencedExportContainer(node); + return container && container.kind !== 248 /* SourceFile */; + } + function emitShorthandPropertyAssignment(node) { + // The name property of a short-hand property assignment is considered an expression position, so here + // we manually emit the identifier to avoid rewriting. + writeTextOfNode(currentSourceFile, node.name); + // If emitting pre-ES6 code, or if the name requires rewriting when resolved as an expression identifier, + // we emit a normal property assignment. For example: + // module m { + // export let y; + // } + // module m { + // let obj = { y }; + // } + // Here we need to emit obj = { y : m.y } regardless of the output target. + if (languageVersion < 2 /* ES6 */ || isNamespaceExportReference(node.name)) { + // Emit identifier as an identifier + write(": "); + emit(node.name); + } + if (languageVersion >= 2 /* ES6 */ && node.objectAssignmentInitializer) { + write(" = "); + emit(node.objectAssignmentInitializer); + } + } + function tryEmitConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + write(constantValue.toString()); + if (!compilerOptions.removeComments) { + var propertyName = node.kind === 166 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); + write(" /* " + propertyName + " */"); + } + return true; + } + return false; + } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return node.kind === 166 /* PropertyAccessExpression */ || node.kind === 167 /* ElementAccessExpression */ + ? resolver.getConstantValue(node) + : undefined; + } + // Returns 'true' if the code was actually indented, false otherwise. + // If the code is not indented, an optional valueToWriteWhenNotIndenting will be + // emitted instead. + function indentIfOnDifferentLines(parent, node1, node2, valueToWriteWhenNotIndenting) { + var realNodesAreOnDifferentLines = !ts.nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2); + // Always use a newline for synthesized code if the synthesizer desires it. + var synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine(node2); + if (realNodesAreOnDifferentLines || synthesizedNodeIsOnDifferentLine) { + increaseIndent(); + writeLine(); + return true; + } + else { + if (valueToWriteWhenNotIndenting) { + write(valueToWriteWhenNotIndenting); + } + return false; + } + } + function emitPropertyAccess(node) { + if (tryEmitConstantValue(node)) { + return; + } + emit(node.expression); + var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); + // 1 .toString is a valid property access, emit a space after the literal + // Also emit a space if expression is a integer const enum value - it will appear in generated code as numeric literal + var shouldEmitSpace; + if (!indentedBeforeDot) { + if (node.expression.kind === 8 /* NumericLiteral */) { + // check if numeric literal was originally written with a dot + var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression); + shouldEmitSpace = text.indexOf(ts.tokenToString(21 /* DotToken */)) < 0; + } + else { + // check if constant enum value is integer + var constantValue = tryGetConstEnumValue(node.expression); + // isFinite handles cases when constantValue is undefined + shouldEmitSpace = isFinite(constantValue) && Math.floor(constantValue) === constantValue; + } + } + if (shouldEmitSpace) { + write(" ."); + } + else { + write("."); + } + var indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); + emit(node.name); + decreaseIndentIf(indentedBeforeDot, indentedAfterDot); + } + function emitQualifiedName(node) { + emit(node.left); + write("."); + emit(node.right); + } + function emitQualifiedNameAsExpression(node, useFallback) { + if (node.left.kind === 69 /* Identifier */) { + emitEntityNameAsExpression(node.left, useFallback); + } + else if (useFallback) { + var temp = createAndRecordTempVariable(0 /* Auto */); + write("("); + emitNodeWithoutSourceMap(temp); + write(" = "); + emitEntityNameAsExpression(node.left, /*useFallback*/ true); + write(") && "); + emitNodeWithoutSourceMap(temp); + } + else { + emitEntityNameAsExpression(node.left, /*useFallback*/ false); + } + write("."); + emit(node.right); + } + function emitEntityNameAsExpression(node, useFallback) { + switch (node.kind) { + case 69 /* Identifier */: + if (useFallback) { + write("typeof "); + emitExpressionIdentifier(node); + write(" !== 'undefined' && "); + } + emitExpressionIdentifier(node); + break; + case 135 /* QualifiedName */: + emitQualifiedNameAsExpression(node, useFallback); + break; + } + } + function emitIndexedAccess(node) { + if (tryEmitConstantValue(node)) { + return; + } + emit(node.expression); + write("["); + emit(node.argumentExpression); + write("]"); + } + function hasSpreadElement(elements) { + return ts.forEach(elements, function (e) { return e.kind === 185 /* SpreadElementExpression */; }); + } + function skipParentheses(node) { + while (node.kind === 172 /* ParenthesizedExpression */ || node.kind === 171 /* TypeAssertionExpression */ || node.kind === 189 /* AsExpression */) { + node = node.expression; + } + return node; + } + function emitCallTarget(node) { + if (node.kind === 69 /* Identifier */ || node.kind === 97 /* ThisKeyword */ || node.kind === 95 /* SuperKeyword */) { + emit(node); + return node; + } + var temp = createAndRecordTempVariable(0 /* Auto */); + write("("); + emit(temp); + write(" = "); + emit(node); + write(")"); + return temp; + } + function emitCallWithSpread(node) { + var target; + var expr = skipParentheses(node.expression); + if (expr.kind === 166 /* PropertyAccessExpression */) { + // Target will be emitted as "this" argument + target = emitCallTarget(expr.expression); + write("."); + emit(expr.name); + } + else if (expr.kind === 167 /* ElementAccessExpression */) { + // Target will be emitted as "this" argument + target = emitCallTarget(expr.expression); + write("["); + emit(expr.argumentExpression); + write("]"); + } + else if (expr.kind === 95 /* SuperKeyword */) { + target = expr; + write("_super"); + } + else { + emit(node.expression); + } + write(".apply("); + if (target) { + if (target.kind === 95 /* SuperKeyword */) { + // Calls of form super(...) and super.foo(...) + emitThis(target); + } + else { + // Calls of form obj.foo(...) + emit(target); + } + } + else { + // Calls of form foo(...) + write("void 0"); + } + write(", "); + emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*trailingComma*/ false, /*useConcat*/ true); + write(")"); + } + function emitCallExpression(node) { + if (languageVersion < 2 /* ES6 */ && hasSpreadElement(node.arguments)) { + emitCallWithSpread(node); + return; + } + var superCall = false; + if (node.expression.kind === 95 /* SuperKeyword */) { + emitSuper(node.expression); + superCall = true; + } + else { + emit(node.expression); + superCall = node.expression.kind === 166 /* PropertyAccessExpression */ && node.expression.expression.kind === 95 /* SuperKeyword */; + } + if (superCall && languageVersion < 2 /* ES6 */) { + write(".call("); + emitThis(node.expression); + if (node.arguments.length) { + write(", "); + emitCommaList(node.arguments); + } + write(")"); + } + else { + write("("); + emitCommaList(node.arguments); + write(")"); + } + } + function emitNewExpression(node) { + write("new "); + // Spread operator logic is supported in new expressions in ES5 using a combination + // of Function.prototype.bind() and Function.prototype.apply(). + // + // Example: + // + // var args = [1, 2, 3, 4, 5]; + // new Array(...args); + // + // is compiled into the following ES5: + // + // var args = [1, 2, 3, 4, 5]; + // new (Array.bind.apply(Array, [void 0].concat(args))); + // + // The 'thisArg' to 'bind' is ignored when invoking the result of 'bind' with 'new', + // Thus, we set it to undefined ('void 0'). + if (languageVersion === 1 /* ES5 */ && + node.arguments && + hasSpreadElement(node.arguments)) { + write("("); + var target = emitCallTarget(node.expression); + write(".bind.apply("); + emit(target); + write(", [void 0].concat("); + emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiline*/ false, /*trailingComma*/ false, /*useConcat*/ false); + write(")))"); + write("()"); + } + else { + emit(node.expression); + if (node.arguments) { + write("("); + emitCommaList(node.arguments); + write(")"); + } + } + } + function emitTaggedTemplateExpression(node) { + if (languageVersion >= 2 /* ES6 */) { + emit(node.tag); + write(" "); + emit(node.template); + } + else { + emitDownlevelTaggedTemplate(node); + } + } + function emitParenExpression(node) { + // If the node is synthesized, it means the emitter put the parentheses there, + // not the user. If we didn't want them, the emitter would not have put them + // there. + if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 174 /* ArrowFunction */) { + if (node.expression.kind === 171 /* TypeAssertionExpression */ || node.expression.kind === 189 /* AsExpression */) { + var operand = node.expression.expression; + // Make sure we consider all nested cast expressions, e.g.: + // (-A).x; + while (operand.kind === 171 /* TypeAssertionExpression */ || operand.kind === 189 /* AsExpression */) { + operand = operand.expression; + } + // We have an expression of the form: (SubExpr) + // Emitting this as (SubExpr) is really not desirable. We would like to emit the subexpr as is. + // Omitting the parentheses, however, could cause change in the semantics of the generated + // code if the casted expression has a lower precedence than the rest of the expression, e.g.: + // (new A).foo should be emitted as (new A).foo and not new A.foo + // (typeof A).toString() should be emitted as (typeof A).toString() and not typeof A.toString() + // new (A()) should be emitted as new (A()) and not new A() + // (function foo() { })() should be emitted as an IIF (function foo(){})() and not declaration function foo(){} () + if (operand.kind !== 179 /* PrefixUnaryExpression */ && + operand.kind !== 177 /* VoidExpression */ && + operand.kind !== 176 /* TypeOfExpression */ && + operand.kind !== 175 /* DeleteExpression */ && + operand.kind !== 180 /* PostfixUnaryExpression */ && + operand.kind !== 169 /* NewExpression */ && + !(operand.kind === 168 /* CallExpression */ && node.parent.kind === 169 /* NewExpression */) && + !(operand.kind === 173 /* FunctionExpression */ && node.parent.kind === 168 /* CallExpression */) && + !(operand.kind === 8 /* NumericLiteral */ && node.parent.kind === 166 /* PropertyAccessExpression */)) { + emit(operand); + return; + } + } + } + write("("); + emit(node.expression); + write(")"); + } + function emitDeleteExpression(node) { + write(ts.tokenToString(78 /* DeleteKeyword */)); + write(" "); + emit(node.expression); + } + function emitVoidExpression(node) { + write(ts.tokenToString(103 /* VoidKeyword */)); + write(" "); + emit(node.expression); + } + function emitTypeOfExpression(node) { + write(ts.tokenToString(101 /* TypeOfKeyword */)); + write(" "); + emit(node.expression); + } + function isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node) { + if (!isCurrentFileSystemExternalModule() || node.kind !== 69 /* Identifier */ || ts.nodeIsSynthesized(node)) { + return false; + } + var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 211 /* VariableDeclaration */ || node.parent.kind === 163 /* BindingElement */); + var targetDeclaration = isVariableDeclarationOrBindingElement + ? node.parent + : resolver.getReferencedValueDeclaration(node); + return isSourceFileLevelDeclarationInSystemJsModule(targetDeclaration, /*isExported*/ true); + } + function emitPrefixUnaryExpression(node) { + var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); + if (exportChanged) { + // emit + // ++x + // as + // exports('x', ++x) + write(exportFunctionForFile + "(\""); + emitNodeWithoutSourceMap(node.operand); + write("\", "); + } + write(ts.tokenToString(node.operator)); + // In some cases, we need to emit a space between the operator and the operand. One obvious case + // is when the operator is an identifier, like delete or typeof. We also need to do this for plus + // and minus expressions in certain cases. Specifically, consider the following two cases (parens + // are just for clarity of exposition, and not part of the source code): + // + // (+(+1)) + // (+(++1)) + // + // We need to emit a space in both cases. In the first case, the absence of a space will make + // the resulting expression a prefix increment operation. And in the second, it will make the resulting + // expression a prefix increment whose operand is a plus expression - (++(+x)) + // The same is true of minus of course. + if (node.operand.kind === 179 /* PrefixUnaryExpression */) { + var operand = node.operand; + if (node.operator === 35 /* PlusToken */ && (operand.operator === 35 /* PlusToken */ || operand.operator === 41 /* PlusPlusToken */)) { + write(" "); + } + else if (node.operator === 36 /* MinusToken */ && (operand.operator === 36 /* MinusToken */ || operand.operator === 42 /* MinusMinusToken */)) { + write(" "); + } + } + emit(node.operand); + if (exportChanged) { + write(")"); + } + } + function emitPostfixUnaryExpression(node) { + var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); + if (exportChanged) { + // export function returns the value that was passes as the second argument + // however for postfix unary expressions result value should be the value before modification. + // emit 'x++' as '(export('x', ++x) - 1)' and 'x--' as '(export('x', --x) + 1)' + write("(" + exportFunctionForFile + "(\""); + emitNodeWithoutSourceMap(node.operand); + write("\", "); + write(ts.tokenToString(node.operator)); + emit(node.operand); + if (node.operator === 41 /* PlusPlusToken */) { + write(") - 1)"); + } + else { + write(") + 1)"); + } + } + else { + emit(node.operand); + write(ts.tokenToString(node.operator)); + } + } + function shouldHoistDeclarationInSystemJsModule(node) { + return isSourceFileLevelDeclarationInSystemJsModule(node, /*isExported*/ false); + } + /* + * Checks if given node is a source file level declaration (not nested in module/function). + * If 'isExported' is true - then declaration must also be exported. + * This function is used in two cases: + * - check if node is a exported source file level value to determine + * if we should also export the value after its it changed + * - check if node is a source level declaration to emit it differently, + * i.e non-exported variable statement 'var x = 1' is hoisted so + * we we emit variable statement 'var' should be dropped. + */ + function isSourceFileLevelDeclarationInSystemJsModule(node, isExported) { + if (!node || languageVersion >= 2 /* ES6 */ || !isCurrentFileSystemExternalModule()) { + return false; + } + var current = node; + while (current) { + if (current.kind === 248 /* SourceFile */) { + return !isExported || ((ts.getCombinedNodeFlags(node) & 1 /* Export */) !== 0); + } + else if (ts.isFunctionLike(current) || current.kind === 219 /* ModuleBlock */) { + return false; + } + else { + current = current.parent; + } + } + } + /** + * Emit ES7 exponentiation operator downlevel using Math.pow + * @param node a binary expression node containing exponentiationOperator (**, **=) + */ + function emitExponentiationOperator(node) { + var leftHandSideExpression = node.left; + if (node.operatorToken.kind === 60 /* AsteriskAsteriskEqualsToken */) { + var synthesizedLHS; + var shouldEmitParentheses = false; + if (ts.isElementAccessExpression(leftHandSideExpression)) { + shouldEmitParentheses = true; + write("("); + synthesizedLHS = ts.createSynthesizedNode(167 /* ElementAccessExpression */, /*startsOnNewLine*/ false); + var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldEmitCommaBeforeAssignment*/ false); + synthesizedLHS.expression = identifier; + if (leftHandSideExpression.argumentExpression.kind !== 8 /* NumericLiteral */ && + leftHandSideExpression.argumentExpression.kind !== 9 /* StringLiteral */) { + var tempArgumentExpression = createAndRecordTempVariable(268435456 /* _i */); + synthesizedLHS.argumentExpression = tempArgumentExpression; + emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, /*shouldEmitCommaBeforeAssignment*/ true); + } + else { + synthesizedLHS.argumentExpression = leftHandSideExpression.argumentExpression; + } + write(", "); + } + else if (ts.isPropertyAccessExpression(leftHandSideExpression)) { + shouldEmitParentheses = true; + write("("); + synthesizedLHS = ts.createSynthesizedNode(166 /* PropertyAccessExpression */, /*startsOnNewLine*/ false); + var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldemitCommaBeforeAssignment*/ false); + synthesizedLHS.expression = identifier; + synthesizedLHS.dotToken = leftHandSideExpression.dotToken; + synthesizedLHS.name = leftHandSideExpression.name; + write(", "); + } + emit(synthesizedLHS || leftHandSideExpression); + write(" = "); + write("Math.pow("); + emit(synthesizedLHS || leftHandSideExpression); + write(", "); + emit(node.right); + write(")"); + if (shouldEmitParentheses) { + write(")"); + } + } + else { + write("Math.pow("); + emit(leftHandSideExpression); + write(", "); + emit(node.right); + write(")"); + } + } + function emitBinaryExpression(node) { + if (languageVersion < 2 /* ES6 */ && node.operatorToken.kind === 56 /* EqualsToken */ && + (node.left.kind === 165 /* ObjectLiteralExpression */ || node.left.kind === 164 /* ArrayLiteralExpression */)) { + emitDestructuring(node, node.parent.kind === 195 /* ExpressionStatement */); + } + else { + var exportChanged = node.operatorToken.kind >= 56 /* FirstAssignment */ && + node.operatorToken.kind <= 68 /* LastAssignment */ && + isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.left); + if (exportChanged) { + // emit assignment 'x y' as 'exports("x", x y)' + write(exportFunctionForFile + "(\""); + emitNodeWithoutSourceMap(node.left); + write("\", "); + } + if (node.operatorToken.kind === 38 /* AsteriskAsteriskToken */ || node.operatorToken.kind === 60 /* AsteriskAsteriskEqualsToken */) { + // Downleveled emit exponentiation operator using Math.pow + emitExponentiationOperator(node); + } + else { + emit(node.left); + // Add indentation before emit the operator if the operator is on different line + // For example: + // 3 + // + 2; + // emitted as + // 3 + // + 2; + var indentedBeforeOperator = indentIfOnDifferentLines(node, node.left, node.operatorToken, node.operatorToken.kind !== 24 /* CommaToken */ ? " " : undefined); + write(ts.tokenToString(node.operatorToken.kind)); + var indentedAfterOperator = indentIfOnDifferentLines(node, node.operatorToken, node.right, " "); + emit(node.right); + decreaseIndentIf(indentedBeforeOperator, indentedAfterOperator); + } + if (exportChanged) { + write(")"); + } + } + } + function synthesizedNodeStartsOnNewLine(node) { + return ts.nodeIsSynthesized(node) && node.startsOnNewLine; + } + function emitConditionalExpression(node) { + emit(node.condition); + var indentedBeforeQuestion = indentIfOnDifferentLines(node, node.condition, node.questionToken, " "); + write("?"); + var indentedAfterQuestion = indentIfOnDifferentLines(node, node.questionToken, node.whenTrue, " "); + emit(node.whenTrue); + decreaseIndentIf(indentedBeforeQuestion, indentedAfterQuestion); + var indentedBeforeColon = indentIfOnDifferentLines(node, node.whenTrue, node.colonToken, " "); + write(":"); + var indentedAfterColon = indentIfOnDifferentLines(node, node.colonToken, node.whenFalse, " "); + emit(node.whenFalse); + decreaseIndentIf(indentedBeforeColon, indentedAfterColon); + } + // Helper function to decrease the indent if we previously indented. Allows multiple + // previous indent values to be considered at a time. This also allows caller to just + // call this once, passing in all their appropriate indent values, instead of needing + // to call this helper function multiple times. + function decreaseIndentIf(value1, value2) { + if (value1) { + decreaseIndent(); + } + if (value2) { + decreaseIndent(); + } + } + function isSingleLineEmptyBlock(node) { + if (node && node.kind === 192 /* Block */) { + var block = node; + return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); + } + } + function emitBlock(node) { + if (isSingleLineEmptyBlock(node)) { + emitToken(15 /* OpenBraceToken */, node.pos); + write(" "); + emitToken(16 /* CloseBraceToken */, node.statements.end); + return; + } + emitToken(15 /* OpenBraceToken */, node.pos); + increaseIndent(); + scopeEmitStart(node.parent); + if (node.kind === 219 /* ModuleBlock */) { + ts.Debug.assert(node.parent.kind === 218 /* ModuleDeclaration */); + emitCaptureThisForNodeIfNecessary(node.parent); + } + emitLines(node.statements); + if (node.kind === 219 /* ModuleBlock */) { + emitTempDeclarations(/*newLine*/ true); + } + decreaseIndent(); + writeLine(); + emitToken(16 /* CloseBraceToken */, node.statements.end); + scopeEmitEnd(); + } + function emitEmbeddedStatement(node) { + if (node.kind === 192 /* Block */) { + write(" "); + emit(node); + } + else { + increaseIndent(); + writeLine(); + emit(node); + decreaseIndent(); + } + } + function emitExpressionStatement(node) { + emitParenthesizedIf(node.expression, /*parenthesized*/ node.expression.kind === 174 /* ArrowFunction */); + write(";"); + } + function emitIfStatement(node) { + var endPos = emitToken(88 /* IfKeyword */, node.pos); + write(" "); + endPos = emitToken(17 /* OpenParenToken */, endPos); + emit(node.expression); + emitToken(18 /* CloseParenToken */, node.expression.end); + emitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + writeLine(); + emitToken(80 /* ElseKeyword */, node.thenStatement.end); + if (node.elseStatement.kind === 196 /* IfStatement */) { + write(" "); + emit(node.elseStatement); + } + else { + emitEmbeddedStatement(node.elseStatement); + } + } + } + function emitDoStatement(node) { + write("do"); + emitEmbeddedStatement(node.statement); + if (node.statement.kind === 192 /* Block */) { + write(" "); + } + else { + writeLine(); + } + write("while ("); + emit(node.expression); + write(");"); + } + function emitWhileStatement(node) { + write("while ("); + emit(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + /** + * Returns true if start of variable declaration list was emitted. + * Returns false if nothing was written - this can happen for source file level variable declarations + * in system modules where such variable declarations are hoisted. + */ + function tryEmitStartOfVariableDeclarationList(decl, startPos) { + if (shouldHoistVariable(decl, /*checkIfSourceFileLevelDecl*/ true)) { + // variables in variable declaration list were already hoisted + return false; + } + var tokenKind = 102 /* VarKeyword */; + if (decl && languageVersion >= 2 /* ES6 */) { + if (ts.isLet(decl)) { + tokenKind = 108 /* LetKeyword */; + } + else if (ts.isConst(decl)) { + tokenKind = 74 /* ConstKeyword */; + } + } + if (startPos !== undefined) { + emitToken(tokenKind, startPos); + write(" "); + } + else { + switch (tokenKind) { + case 102 /* VarKeyword */: + write("var "); + break; + case 108 /* LetKeyword */: + write("let "); + break; + case 74 /* ConstKeyword */: + write("const "); + break; + } + } + return true; + } + function emitVariableDeclarationListSkippingUninitializedEntries(list) { + var started = false; + for (var _a = 0, _b = list.declarations; _a < _b.length; _a++) { + var decl = _b[_a]; + if (!decl.initializer) { + continue; + } + if (!started) { + started = true; + } + else { + write(", "); + } + emit(decl); + } + return started; + } + function emitForStatement(node) { + var endPos = emitToken(86 /* ForKeyword */, node.pos); + write(" "); + endPos = emitToken(17 /* OpenParenToken */, endPos); + if (node.initializer && node.initializer.kind === 212 /* VariableDeclarationList */) { + var variableDeclarationList = node.initializer; + var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); + if (startIsEmitted) { + emitCommaList(variableDeclarationList.declarations); + } + else { + emitVariableDeclarationListSkippingUninitializedEntries(variableDeclarationList); + } + } + else if (node.initializer) { + emit(node.initializer); + } + write(";"); + emitOptional(" ", node.condition); + write(";"); + emitOptional(" ", node.incrementor); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitForInOrForOfStatement(node) { + if (languageVersion < 2 /* ES6 */ && node.kind === 201 /* ForOfStatement */) { + return emitDownLevelForOfStatement(node); + } + var endPos = emitToken(86 /* ForKeyword */, node.pos); + write(" "); + endPos = emitToken(17 /* OpenParenToken */, endPos); + if (node.initializer.kind === 212 /* VariableDeclarationList */) { + var variableDeclarationList = node.initializer; + if (variableDeclarationList.declarations.length >= 1) { + tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); + emit(variableDeclarationList.declarations[0]); + } + } + else { + emit(node.initializer); + } + if (node.kind === 200 /* ForInStatement */) { + write(" in "); + } + else { + write(" of "); + } + emit(node.expression); + emitToken(18 /* CloseParenToken */, node.expression.end); + emitEmbeddedStatement(node.statement); + } + function emitDownLevelForOfStatement(node) { + // The following ES6 code: + // + // for (let v of expr) { } + // + // should be emitted as + // + // for (let _i = 0, _a = expr; _i < _a.length; _i++) { + // let v = _a[_i]; + // } + // + // where _a and _i are temps emitted to capture the RHS and the counter, + // respectively. + // When the left hand side is an expression instead of a let declaration, + // the "let v" is not emitted. + // When the left hand side is a let/const, the v is renamed if there is + // another v in scope. + // Note that all assignments to the LHS are emitted in the body, including + // all destructuring. + // Note also that because an extra statement is needed to assign to the LHS, + // for-of bodies are always emitted as blocks. + var endPos = emitToken(86 /* ForKeyword */, node.pos); + write(" "); + endPos = emitToken(17 /* OpenParenToken */, endPos); + // Do not emit the LHS let declaration yet, because it might contain destructuring. + // Do not call recordTempDeclaration because we are declaring the temps + // right here. Recording means they will be declared later. + // In the case where the user wrote an identifier as the RHS, like this: + // + // for (let v of arr) { } + // + // we don't want to emit a temporary variable for the RHS, just use it directly. + var rhsIsIdentifier = node.expression.kind === 69 /* Identifier */; + var counter = createTempVariable(268435456 /* _i */); + var rhsReference = rhsIsIdentifier ? node.expression : createTempVariable(0 /* Auto */); + // This is the let keyword for the counter and rhsReference. The let keyword for + // the LHS will be emitted inside the body. + emitStart(node.expression); + write("var "); + // _i = 0 + emitNodeWithoutSourceMap(counter); + write(" = 0"); + emitEnd(node.expression); + if (!rhsIsIdentifier) { + // , _a = expr + write(", "); + emitStart(node.expression); + emitNodeWithoutSourceMap(rhsReference); + write(" = "); + emitNodeWithoutSourceMap(node.expression); + emitEnd(node.expression); + } + write("; "); + // _i < _a.length; + emitStart(node.initializer); + emitNodeWithoutSourceMap(counter); + write(" < "); + emitNodeWithCommentsAndWithoutSourcemap(rhsReference); + write(".length"); + emitEnd(node.initializer); + write("; "); + // _i++) + emitStart(node.initializer); + emitNodeWithoutSourceMap(counter); + write("++"); + emitEnd(node.initializer); + emitToken(18 /* CloseParenToken */, node.expression.end); + // Body + write(" {"); + writeLine(); + increaseIndent(); + // Initialize LHS + // let v = _a[_i]; + var rhsIterationValue = createElementAccessExpression(rhsReference, counter); + emitStart(node.initializer); + if (node.initializer.kind === 212 /* VariableDeclarationList */) { + write("var "); + var variableDeclarationList = node.initializer; + if (variableDeclarationList.declarations.length > 0) { + var declaration = variableDeclarationList.declarations[0]; + if (ts.isBindingPattern(declaration.name)) { + // This works whether the declaration is a var, let, or const. + // It will use rhsIterationValue _a[_i] as the initializer. + emitDestructuring(declaration, /*isAssignmentExpressionStatement*/ false, rhsIterationValue); + } + else { + // The following call does not include the initializer, so we have + // to emit it separately. + emitNodeWithCommentsAndWithoutSourcemap(declaration); + write(" = "); + emitNodeWithoutSourceMap(rhsIterationValue); + } + } + else { + // It's an empty declaration list. This can only happen in an error case, if the user wrote + // for (let of []) {} + emitNodeWithoutSourceMap(createTempVariable(0 /* Auto */)); + write(" = "); + emitNodeWithoutSourceMap(rhsIterationValue); + } + } + else { + // Initializer is an expression. Emit the expression in the body, so that it's + // evaluated on every iteration. + var assignmentExpression = createBinaryExpression(node.initializer, 56 /* EqualsToken */, rhsIterationValue, /*startsOnNewLine*/ false); + if (node.initializer.kind === 164 /* ArrayLiteralExpression */ || node.initializer.kind === 165 /* ObjectLiteralExpression */) { + // This is a destructuring pattern, so call emitDestructuring instead of emit. Calling emit will not work, because it will cause + // the BinaryExpression to be passed in instead of the expression statement, which will cause emitDestructuring to crash. + emitDestructuring(assignmentExpression, /*isAssignmentExpressionStatement*/ true, /*value*/ undefined); + } + else { + emitNodeWithCommentsAndWithoutSourcemap(assignmentExpression); + } + } + emitEnd(node.initializer); + write(";"); + if (node.statement.kind === 192 /* Block */) { + emitLines(node.statement.statements); + } + else { + writeLine(); + emit(node.statement); + } + writeLine(); + decreaseIndent(); + write("}"); + } + function emitBreakOrContinueStatement(node) { + emitToken(node.kind === 203 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */, node.pos); + emitOptional(" ", node.label); + write(";"); + } + function emitReturnStatement(node) { + emitToken(94 /* ReturnKeyword */, node.pos); + emitOptional(" ", node.expression); + write(";"); + } + function emitWithStatement(node) { + write("with ("); + emit(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitSwitchStatement(node) { + var endPos = emitToken(96 /* SwitchKeyword */, node.pos); + write(" "); + emitToken(17 /* OpenParenToken */, endPos); + emit(node.expression); + endPos = emitToken(18 /* CloseParenToken */, node.expression.end); + write(" "); + emitCaseBlock(node.caseBlock, endPos); + } + function emitCaseBlock(node, startPos) { + emitToken(15 /* OpenBraceToken */, startPos); + increaseIndent(); + emitLines(node.clauses); + decreaseIndent(); + writeLine(); + emitToken(16 /* CloseBraceToken */, node.clauses.end); + } + function nodeStartPositionsAreOnSameLine(node1, node2) { + return ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node1.pos)) === + ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); + } + function nodeEndPositionsAreOnSameLine(node1, node2) { + return ts.getLineOfLocalPosition(currentSourceFile, node1.end) === + ts.getLineOfLocalPosition(currentSourceFile, node2.end); + } + function nodeEndIsOnSameLineAsNodeStart(node1, node2) { + return ts.getLineOfLocalPosition(currentSourceFile, node1.end) === + ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); + } + function emitCaseOrDefaultClause(node) { + if (node.kind === 241 /* CaseClause */) { + write("case "); + emit(node.expression); + write(":"); + } + else { + write("default:"); + } + if (node.statements.length === 1 && nodeStartPositionsAreOnSameLine(node, node.statements[0])) { + write(" "); + emit(node.statements[0]); + } + else { + increaseIndent(); + emitLines(node.statements); + decreaseIndent(); + } + } + function emitThrowStatement(node) { + write("throw "); + emit(node.expression); + write(";"); + } + function emitTryStatement(node) { + write("try "); + emit(node.tryBlock); + emit(node.catchClause); + if (node.finallyBlock) { + writeLine(); + write("finally "); + emit(node.finallyBlock); + } + } + function emitCatchClause(node) { + writeLine(); + var endPos = emitToken(72 /* CatchKeyword */, node.pos); + write(" "); + emitToken(17 /* OpenParenToken */, endPos); + emit(node.variableDeclaration); + emitToken(18 /* CloseParenToken */, node.variableDeclaration ? node.variableDeclaration.end : endPos); + write(" "); + emitBlock(node.block); + } + function emitDebuggerStatement(node) { + emitToken(76 /* DebuggerKeyword */, node.pos); + write(";"); + } + function emitLabelledStatement(node) { + emit(node.label); + write(": "); + emit(node.statement); + } + function getContainingModule(node) { + do { + node = node.parent; + } while (node && node.kind !== 218 /* ModuleDeclaration */); + return node; + } + function emitContainingModuleName(node) { + var container = getContainingModule(node); + write(container ? getGeneratedNameForNode(container) : "exports"); + } + function emitModuleMemberName(node) { + emitStart(node.name); + if (ts.getCombinedNodeFlags(node) & 1 /* Export */) { + var container = getContainingModule(node); + if (container) { + write(getGeneratedNameForNode(container)); + write("."); + } + else if (modulekind !== 5 /* ES6 */ && modulekind !== 4 /* System */) { + write("exports."); + } + } + emitNodeWithCommentsAndWithoutSourcemap(node.name); + emitEnd(node.name); + } + function createVoidZero() { + var zero = ts.createSynthesizedNode(8 /* NumericLiteral */); + zero.text = "0"; + var result = ts.createSynthesizedNode(177 /* VoidExpression */); + result.expression = zero; + return result; + } + function emitEs6ExportDefaultCompat(node) { + if (node.parent.kind === 248 /* SourceFile */) { + ts.Debug.assert(!!(node.flags & 1024 /* Default */) || node.kind === 227 /* ExportAssignment */); + // only allow export default at a source file level + if (modulekind === 1 /* CommonJS */ || modulekind === 2 /* AMD */ || modulekind === 3 /* UMD */) { + if (!currentSourceFile.symbol.exports["___esModule"]) { + if (languageVersion === 1 /* ES5 */) { + // default value of configurable, enumerable, writable are `false`. + write("Object.defineProperty(exports, \"__esModule\", { value: true });"); + writeLine(); + } + else if (languageVersion === 0 /* ES3 */) { + write("exports.__esModule = true;"); + writeLine(); + } + } + } + } + } + function emitExportMemberAssignment(node) { + if (node.flags & 1 /* Export */) { + writeLine(); + emitStart(node); + // emit call to exporter only for top level nodes + if (modulekind === 4 /* System */ && node.parent === currentSourceFile) { + // emit export default as + // export("default", ) + write(exportFunctionForFile + "(\""); + if (node.flags & 1024 /* Default */) { + write("default"); + } + else { + emitNodeWithCommentsAndWithoutSourcemap(node.name); + } + write("\", "); + emitDeclarationName(node); + write(")"); + } + else { + if (node.flags & 1024 /* Default */) { + emitEs6ExportDefaultCompat(node); + if (languageVersion === 0 /* ES3 */) { + write("exports[\"default\"]"); + } + else { + write("exports.default"); + } + } + else { + emitModuleMemberName(node); + } + write(" = "); + emitDeclarationName(node); + } + emitEnd(node); + write(";"); + } + } + function emitExportMemberAssignments(name) { + if (modulekind === 4 /* System */) { + return; + } + if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { + for (var _a = 0, _b = exportSpecifiers[name.text]; _a < _b.length; _a++) { + var specifier = _b[_a]; + writeLine(); + emitStart(specifier.name); + emitContainingModuleName(specifier); + write("."); + emitNodeWithCommentsAndWithoutSourcemap(specifier.name); + emitEnd(specifier.name); + write(" = "); + emitExpressionIdentifier(name); + write(";"); + } + } + } + function emitExportSpecifierInSystemModule(specifier) { + ts.Debug.assert(modulekind === 4 /* System */); + if (!resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) && !resolver.isValueAliasDeclaration(specifier)) { + return; + } + writeLine(); + emitStart(specifier.name); + write(exportFunctionForFile + "(\""); + emitNodeWithCommentsAndWithoutSourcemap(specifier.name); + write("\", "); + emitExpressionIdentifier(specifier.propertyName || specifier.name); + write(")"); + emitEnd(specifier.name); + write(";"); + } + /** + * Emit an assignment to a given identifier, 'name', with a given expression, 'value'. + * @param name an identifier as a left-hand-side operand of the assignment + * @param value an expression as a right-hand-side operand of the assignment + * @param shouldEmitCommaBeforeAssignment a boolean indicating whether to prefix an assignment with comma + */ + function emitAssignment(name, value, shouldEmitCommaBeforeAssignment) { + if (shouldEmitCommaBeforeAssignment) { + write(", "); + } + var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(name); + if (exportChanged) { + write(exportFunctionForFile + "(\""); + emitNodeWithCommentsAndWithoutSourcemap(name); + write("\", "); + } + var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 211 /* VariableDeclaration */ || name.parent.kind === 163 /* BindingElement */); + if (isVariableDeclarationOrBindingElement) { + emitModuleMemberName(name.parent); + } + else { + emit(name); + } + write(" = "); + emit(value); + if (exportChanged) { + write(")"); + } + } + /** + * Create temporary variable, emit an assignment of the variable the given expression + * @param expression an expression to assign to the newly created temporary variable + * @param canDefineTempVariablesInPlace a boolean indicating whether you can define the temporary variable at an assignment location + * @param shouldEmitCommaBeforeAssignment a boolean indicating whether an assignment should prefix with comma + */ + function emitTempVariableAssignment(expression, canDefineTempVariablesInPlace, shouldEmitCommaBeforeAssignment) { + var identifier = createTempVariable(0 /* Auto */); + if (!canDefineTempVariablesInPlace) { + recordTempDeclaration(identifier); + } + emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment); + return identifier; + } + function emitDestructuring(root, isAssignmentExpressionStatement, value) { + var emitCount = 0; + // An exported declaration is actually emitted as an assignment (to a property on the module object), so + // temporary variables in an exported declaration need to have real declarations elsewhere + // Also temporary variables should be explicitly allocated for source level declarations when module target is system + // because actual variable declarations are hoisted + var canDefineTempVariablesInPlace = false; + if (root.kind === 211 /* VariableDeclaration */) { + var isExported = ts.getCombinedNodeFlags(root) & 1 /* Export */; + var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); + canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; + } + else if (root.kind === 138 /* Parameter */) { + canDefineTempVariablesInPlace = true; + } + if (root.kind === 181 /* BinaryExpression */) { + emitAssignmentExpression(root); + } + else { + ts.Debug.assert(!isAssignmentExpressionStatement); + emitBindingElement(root, value); + } + /** + * Ensures that there exists a declared identifier whose value holds the given expression. + * This function is useful to ensure that the expression's value can be read from in subsequent expressions. + * Unless 'reuseIdentifierExpressions' is false, 'expr' will be returned if it is just an identifier. + * + * @param expr the expression whose value needs to be bound. + * @param reuseIdentifierExpressions true if identifier expressions can simply be returned; + * false if it is necessary to always emit an identifier. + */ + function ensureIdentifier(expr, reuseIdentifierExpressions) { + if (expr.kind === 69 /* Identifier */ && reuseIdentifierExpressions) { + return expr; + } + var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0); + emitCount++; + return identifier; + } + function createDefaultValueCheck(value, defaultValue) { + // The value expression will be evaluated twice, so for anything but a simple identifier + // we need to generate a temporary variable + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); + // Return the expression 'value === void 0 ? defaultValue : value' + var equals = ts.createSynthesizedNode(181 /* BinaryExpression */); + equals.left = value; + equals.operatorToken = ts.createSynthesizedNode(32 /* EqualsEqualsEqualsToken */); + equals.right = createVoidZero(); + return createConditionalExpression(equals, defaultValue, value); + } + function createConditionalExpression(condition, whenTrue, whenFalse) { + var cond = ts.createSynthesizedNode(182 /* ConditionalExpression */); + cond.condition = condition; + cond.questionToken = ts.createSynthesizedNode(53 /* QuestionToken */); + cond.whenTrue = whenTrue; + cond.colonToken = ts.createSynthesizedNode(54 /* ColonToken */); + cond.whenFalse = whenFalse; + return cond; + } + function createNumericLiteral(value) { + var node = ts.createSynthesizedNode(8 /* NumericLiteral */); + node.text = "" + value; + return node; + } + function createPropertyAccessForDestructuringProperty(object, propName) { + // We create a synthetic copy of the identifier in order to avoid the rewriting that might + // otherwise occur when the identifier is emitted. + var syntheticName = ts.createSynthesizedNode(propName.kind); + syntheticName.text = propName.text; + if (syntheticName.kind !== 69 /* Identifier */) { + return createElementAccessExpression(object, syntheticName); + } + return createPropertyAccessExpression(object, syntheticName); + } + function createSliceCall(value, sliceIndex) { + var call = ts.createSynthesizedNode(168 /* CallExpression */); + var sliceIdentifier = ts.createSynthesizedNode(69 /* Identifier */); + sliceIdentifier.text = "slice"; + call.expression = createPropertyAccessExpression(value, sliceIdentifier); + call.arguments = ts.createSynthesizedNodeArray(); + call.arguments[0] = createNumericLiteral(sliceIndex); + return call; + } + function emitObjectLiteralAssignment(target, value) { + var properties = target.properties; + if (properties.length !== 1) { + // For anything but a single element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); + } + for (var _a = 0; _a < properties.length; _a++) { + var p = properties[_a]; + if (p.kind === 245 /* PropertyAssignment */ || p.kind === 246 /* ShorthandPropertyAssignment */) { + var propName = p.name; + var target_1 = p.kind === 246 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName; + emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName)); + } + } + } + function emitArrayLiteralAssignment(target, value) { + var elements = target.elements; + if (elements.length !== 1) { + // For anything but a single element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); + } + for (var i = 0; i < elements.length; i++) { + var e = elements[i]; + if (e.kind !== 187 /* OmittedExpression */) { + if (e.kind !== 185 /* SpreadElementExpression */) { + emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i))); + } + else if (i === elements.length - 1) { + emitDestructuringAssignment(e.expression, createSliceCall(value, i)); + } + } + } + } + function emitDestructuringAssignment(target, value) { + if (target.kind === 246 /* ShorthandPropertyAssignment */) { + if (target.objectAssignmentInitializer) { + value = createDefaultValueCheck(value, target.objectAssignmentInitializer); + } + target = target.name; + } + else if (target.kind === 181 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { + value = createDefaultValueCheck(value, target.right); + target = target.left; + } + if (target.kind === 165 /* ObjectLiteralExpression */) { + emitObjectLiteralAssignment(target, value); + } + else if (target.kind === 164 /* ArrayLiteralExpression */) { + emitArrayLiteralAssignment(target, value); + } + else { + emitAssignment(target, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0); + emitCount++; + } + } + function emitAssignmentExpression(root) { + var target = root.left; + var value = root.right; + if (ts.isEmptyObjectLiteralOrArrayLiteral(target)) { + emit(value); + } + else if (isAssignmentExpressionStatement) { + emitDestructuringAssignment(target, value); + } + else { + if (root.parent.kind !== 172 /* ParenthesizedExpression */) { + write("("); + } + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); + emitDestructuringAssignment(target, value); + write(", "); + emit(value); + if (root.parent.kind !== 172 /* ParenthesizedExpression */) { + write(")"); + } + } + } + function emitBindingElement(target, value) { + if (target.initializer) { + // Combine value and initializer + value = value ? createDefaultValueCheck(value, target.initializer) : target.initializer; + } + else if (!value) { + // Use 'void 0' in absence of value and initializer + value = createVoidZero(); + } + if (ts.isBindingPattern(target.name)) { + var pattern = target.name; + var elements = pattern.elements; + var numElements = elements.length; + if (numElements !== 1) { + // For anything other than a single-element destructuring we need to generate a temporary + // to ensure value is evaluated exactly once. Additionally, if we have zero elements + // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, + // so in that case, we'll intentionally create that temporary. + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ numElements !== 0); + } + for (var i = 0; i < numElements; i++) { + var element = elements[i]; + if (pattern.kind === 161 /* ObjectBindingPattern */) { + // Rewrite element to a declaration with an initializer that fetches property + var propName = element.propertyName || element.name; + emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName)); + } + else if (element.kind !== 187 /* OmittedExpression */) { + if (!element.dotDotDotToken) { + // Rewrite element to a declaration that accesses array element at index i + emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); + } + else if (i === numElements - 1) { + emitBindingElement(element, createSliceCall(value, i)); + } + } + } + } + else { + emitAssignment(target.name, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0); + emitCount++; + } + } + } + function emitVariableDeclaration(node) { + if (ts.isBindingPattern(node.name)) { + if (languageVersion < 2 /* ES6 */) { + emitDestructuring(node, /*isAssignmentExpressionStatement*/ false); + } + else { + emit(node.name); + emitOptional(" = ", node.initializer); + } + } + else { + var initializer = node.initializer; + if (!initializer && languageVersion < 2 /* ES6 */) { + // downlevel emit for non-initialized let bindings defined in loops + // for (...) { let x; } + // should be + // for (...) { var = void 0; } + // this is necessary to preserve ES6 semantic in scenarios like + // for (...) { let x; console.log(x); x = 1 } // assignment on one iteration should not affect other iterations + var isUninitializedLet = (resolver.getNodeCheckFlags(node) & 16384 /* BlockScopedBindingInLoop */) && + (getCombinedFlagsForIdentifier(node.name) & 16384 /* Let */); + // NOTE: default initialization should not be added to let bindings in for-in\for-of statements + if (isUninitializedLet && + node.parent.parent.kind !== 200 /* ForInStatement */ && + node.parent.parent.kind !== 201 /* ForOfStatement */) { + initializer = createVoidZero(); + } + } + var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.name); + if (exportChanged) { + write(exportFunctionForFile + "(\""); + emitNodeWithCommentsAndWithoutSourcemap(node.name); + write("\", "); + } + emitModuleMemberName(node); + emitOptional(" = ", initializer); + if (exportChanged) { + write(")"); + } + } + } + function emitExportVariableAssignments(node) { + if (node.kind === 187 /* OmittedExpression */) { + return; + } + var name = node.name; + if (name.kind === 69 /* Identifier */) { + emitExportMemberAssignments(name); + } + else if (ts.isBindingPattern(name)) { + ts.forEach(name.elements, emitExportVariableAssignments); + } + } + function getCombinedFlagsForIdentifier(node) { + if (!node.parent || (node.parent.kind !== 211 /* VariableDeclaration */ && node.parent.kind !== 163 /* BindingElement */)) { + return 0; + } + return ts.getCombinedNodeFlags(node.parent); + } + function isES6ExportedDeclaration(node) { + return !!(node.flags & 1 /* Export */) && + modulekind === 5 /* ES6 */ && + node.parent.kind === 248 /* SourceFile */; + } + function emitVariableStatement(node) { + var startIsEmitted = false; + if (node.flags & 1 /* Export */) { + if (isES6ExportedDeclaration(node)) { + // Exported ES6 module member + write("export "); + startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList); + } + } + else { + startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList); + } + if (startIsEmitted) { + emitCommaList(node.declarationList.declarations); + write(";"); + } + else { + var atLeastOneItem = emitVariableDeclarationListSkippingUninitializedEntries(node.declarationList); + if (atLeastOneItem) { + write(";"); + } + } + if (modulekind !== 5 /* ES6 */ && node.parent === currentSourceFile) { + ts.forEach(node.declarationList.declarations, emitExportVariableAssignments); + } + } + function shouldEmitLeadingAndTrailingCommentsForVariableStatement(node) { + // If we're not exporting the variables, there's nothing special here. + // Always emit comments for these nodes. + if (!(node.flags & 1 /* Export */)) { + return true; + } + // If we are exporting, but it's a top-level ES6 module exports, + // we'll emit the declaration list verbatim, so emit comments too. + if (isES6ExportedDeclaration(node)) { + return true; + } + // Otherwise, only emit if we have at least one initializer present. + for (var _a = 0, _b = node.declarationList.declarations; _a < _b.length; _a++) { + var declaration = _b[_a]; + if (declaration.initializer) { + return true; + } + } + return false; + } + function emitParameter(node) { + if (languageVersion < 2 /* ES6 */) { + if (ts.isBindingPattern(node.name)) { + var name_24 = createTempVariable(0 /* Auto */); + if (!tempParameters) { + tempParameters = []; + } + tempParameters.push(name_24); + emit(name_24); + } + else { + emit(node.name); + } + } + else { + if (node.dotDotDotToken) { + write("..."); + } + emit(node.name); + emitOptional(" = ", node.initializer); + } + } + function emitDefaultValueAssignments(node) { + if (languageVersion < 2 /* ES6 */) { + var tempIndex = 0; + ts.forEach(node.parameters, function (parameter) { + // A rest parameter cannot have a binding pattern or an initializer, + // so let's just ignore it. + if (parameter.dotDotDotToken) { + return; + } + var paramName = parameter.name, initializer = parameter.initializer; + if (ts.isBindingPattern(paramName)) { + // In cases where a binding pattern is simply '[]' or '{}', + // we usually don't want to emit a var declaration; however, in the presence + // of an initializer, we must emit that expression to preserve side effects. + var hasBindingElements = paramName.elements.length > 0; + if (hasBindingElements || initializer) { + writeLine(); + write("var "); + if (hasBindingElements) { + emitDestructuring(parameter, /*isAssignmentExpressionStatement*/ false, tempParameters[tempIndex]); + } + else { + emit(tempParameters[tempIndex]); + write(" = "); + emit(initializer); + } + write(";"); + tempIndex++; + } + } + else if (initializer) { + writeLine(); + emitStart(parameter); + write("if ("); + emitNodeWithoutSourceMap(paramName); + write(" === void 0)"); + emitEnd(parameter); + write(" { "); + emitStart(parameter); + emitNodeWithCommentsAndWithoutSourcemap(paramName); + write(" = "); + emitNodeWithCommentsAndWithoutSourcemap(initializer); + emitEnd(parameter); + write("; }"); + } + }); + } + } + function emitRestParameter(node) { + if (languageVersion < 2 /* ES6 */ && ts.hasRestParameter(node)) { + var restIndex = node.parameters.length - 1; + var restParam = node.parameters[restIndex]; + // A rest parameter cannot have a binding pattern, so let's just ignore it if it does. + if (ts.isBindingPattern(restParam.name)) { + return; + } + var tempName = createTempVariable(268435456 /* _i */).text; + writeLine(); + emitLeadingComments(restParam); + emitStart(restParam); + write("var "); + emitNodeWithCommentsAndWithoutSourcemap(restParam.name); + write(" = [];"); + emitEnd(restParam); + emitTrailingComments(restParam); + writeLine(); + write("for ("); + emitStart(restParam); + write("var " + tempName + " = " + restIndex + ";"); + emitEnd(restParam); + write(" "); + emitStart(restParam); + write(tempName + " < arguments.length;"); + emitEnd(restParam); + write(" "); + emitStart(restParam); + write(tempName + "++"); + emitEnd(restParam); + write(") {"); + increaseIndent(); + writeLine(); + emitStart(restParam); + emitNodeWithCommentsAndWithoutSourcemap(restParam.name); + write("[" + tempName + " - " + restIndex + "] = arguments[" + tempName + "];"); + emitEnd(restParam); + decreaseIndent(); + writeLine(); + write("}"); + } + } + function emitAccessor(node) { + write(node.kind === 145 /* GetAccessor */ ? "get " : "set "); + emit(node.name); + emitSignatureAndBody(node); + } + function shouldEmitAsArrowFunction(node) { + return node.kind === 174 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */; + } + function emitDeclarationName(node) { + if (node.name) { + emitNodeWithCommentsAndWithoutSourcemap(node.name); + } + else { + write(getGeneratedNameForNode(node)); + } + } + function shouldEmitFunctionName(node) { + if (node.kind === 173 /* FunctionExpression */) { + // Emit name if one is present + return !!node.name; + } + if (node.kind === 213 /* FunctionDeclaration */) { + // Emit name if one is present, or emit generated name in down-level case (for export default case) + return !!node.name || languageVersion < 2 /* ES6 */; + } + } + function emitFunctionDeclaration(node) { + if (ts.nodeIsMissing(node.body)) { + return emitCommentsOnNotEmittedNode(node); + } + // TODO (yuisu) : we should not have special cases to condition emitting comments + // but have one place to fix check for these conditions. + if (node.kind !== 143 /* MethodDeclaration */ && node.kind !== 142 /* MethodSignature */ && + node.parent && node.parent.kind !== 245 /* PropertyAssignment */ && + node.parent.kind !== 168 /* CallExpression */) { + // 1. Methods will emit the comments as part of emitting method declaration + // 2. If the function is a property of object literal, emitting leading-comments + // is done by emitNodeWithoutSourceMap which then call this function. + // In particular, we would like to avoid emit comments twice in following case: + // For example: + // var obj = { + // id: + // /*comment*/ () => void + // } + // 3. If the function is an argument in call expression, emitting of comments will be + // taken care of in emit list of arguments inside of emitCallexpression + emitLeadingComments(node); + } + emitStart(node); + // For targeting below es6, emit functions-like declaration including arrow function using function keyword. + // When targeting ES6, emit arrow function natively in ES6 by omitting function keyword and using fat arrow instead + if (!shouldEmitAsArrowFunction(node)) { + if (isES6ExportedDeclaration(node)) { + write("export "); + if (node.flags & 1024 /* Default */) { + write("default "); + } + } + write("function"); + if (languageVersion >= 2 /* ES6 */ && node.asteriskToken) { + write("*"); + } + write(" "); + } + if (shouldEmitFunctionName(node)) { + emitDeclarationName(node); + } + emitSignatureAndBody(node); + if (modulekind !== 5 /* ES6 */ && node.kind === 213 /* FunctionDeclaration */ && node.parent === currentSourceFile && node.name) { + emitExportMemberAssignments(node.name); + } + emitEnd(node); + if (node.kind !== 143 /* MethodDeclaration */ && node.kind !== 142 /* MethodSignature */) { + emitTrailingComments(node); + } + } + function emitCaptureThisForNodeIfNecessary(node) { + if (resolver.getNodeCheckFlags(node) & 4 /* CaptureThis */) { + writeLine(); + emitStart(node); + write("var _this = this;"); + emitEnd(node); + } + } + function emitSignatureParameters(node) { + increaseIndent(); + write("("); + if (node) { + var parameters = node.parameters; + var omitCount = languageVersion < 2 /* ES6 */ && ts.hasRestParameter(node) ? 1 : 0; + emitList(parameters, 0, parameters.length - omitCount, /*multiLine*/ false, /*trailingComma*/ false); + } + write(")"); + decreaseIndent(); + } + function emitSignatureParametersForArrow(node) { + // Check whether the parameter list needs parentheses and preserve no-parenthesis + if (node.parameters.length === 1 && node.pos === node.parameters[0].pos) { + emit(node.parameters[0]); + return; + } + emitSignatureParameters(node); + } + function emitAsyncFunctionBodyForES6(node) { + var promiseConstructor = ts.getEntityNameFromTypeNode(node.type); + var isArrowFunction = node.kind === 174 /* ArrowFunction */; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 4096 /* CaptureArguments */) !== 0; + var args; + // An async function is emit as an outer function that calls an inner + // generator function. To preserve lexical bindings, we pass the current + // `this` and `arguments` objects to `__awaiter`. The generator function + // passed to `__awaiter` is executed inside of the callback to the + // promise constructor. + // + // The emit for an async arrow without a lexical `arguments` binding might be: + // + // // input + // let a = async (b) => { await b; } + // + // // output + // let a = (b) => __awaiter(this, void 0, void 0, function* () { + // yield b; + // }); + // + // The emit for an async arrow with a lexical `arguments` binding might be: + // + // // input + // let a = async (b) => { await arguments[0]; } + // + // // output + // let a = (b) => __awaiter(this, arguments, void 0, function* (arguments) { + // yield arguments[0]; + // }); + // + // The emit for an async function expression without a lexical `arguments` binding + // might be: + // + // // input + // let a = async function (b) { + // await b; + // } + // + // // output + // let a = function (b) { + // return __awaiter(this, void 0, void 0, function* () { + // yield b; + // }); + // } + // + // The emit for an async function expression with a lexical `arguments` binding + // might be: + // + // // input + // let a = async function (b) { + // await arguments[0]; + // } + // + // // output + // let a = function (b) { + // return __awaiter(this, arguments, void 0, function* (_arguments) { + // yield _arguments[0]; + // }); + // } + // + // The emit for an async function expression with a lexical `arguments` binding + // and a return type annotation might be: + // + // // input + // let a = async function (b): MyPromise { + // await arguments[0]; + // } + // + // // output + // let a = function (b) { + // return __awaiter(this, arguments, MyPromise, function* (_arguments) { + // yield _arguments[0]; + // }); + // } + // + // If this is not an async arrow, emit the opening brace of the function body + // and the start of the return statement. + if (!isArrowFunction) { + write(" {"); + increaseIndent(); + writeLine(); + write("return"); + } + write(" __awaiter(this"); + if (hasLexicalArguments) { + write(", arguments"); + } + else { + write(", void 0"); + } + if (promiseConstructor) { + write(", "); + emitNodeWithoutSourceMap(promiseConstructor); + } + else { + write(", Promise"); + } + // Emit the call to __awaiter. + if (hasLexicalArguments) { + write(", function* (_arguments)"); + } + else { + write(", function* ()"); + } + // Emit the signature and body for the inner generator function. + emitFunctionBody(node); + write(")"); + // If this is not an async arrow, emit the closing brace of the outer function body. + if (!isArrowFunction) { + write(";"); + decreaseIndent(); + writeLine(); + write("}"); + } + } + function emitFunctionBody(node) { + if (!node.body) { + // There can be no body when there are parse errors. Just emit an empty block + // in that case. + write(" { }"); + } + else { + if (node.body.kind === 192 /* Block */) { + emitBlockFunctionBody(node, node.body); + } + else { + emitExpressionFunctionBody(node, node.body); + } + } + } + function emitSignatureAndBody(node) { + var saveTempFlags = tempFlags; + var saveTempVariables = tempVariables; + var saveTempParameters = tempParameters; + tempFlags = 0; + tempVariables = undefined; + tempParameters = undefined; + // When targeting ES6, emit arrow function natively in ES6 + if (shouldEmitAsArrowFunction(node)) { + emitSignatureParametersForArrow(node); + write(" =>"); + } + else { + emitSignatureParameters(node); + } + var isAsync = ts.isAsyncFunctionLike(node); + if (isAsync && languageVersion === 2 /* ES6 */) { + emitAsyncFunctionBodyForES6(node); + } + else { + emitFunctionBody(node); + } + if (!isES6ExportedDeclaration(node)) { + emitExportMemberAssignment(node); + } + tempFlags = saveTempFlags; + tempVariables = saveTempVariables; + tempParameters = saveTempParameters; + } + // Returns true if any preamble code was emitted. + function emitFunctionBodyPreamble(node) { + emitCaptureThisForNodeIfNecessary(node); + emitDefaultValueAssignments(node); + emitRestParameter(node); + } + function emitExpressionFunctionBody(node, body) { + if (languageVersion < 2 /* ES6 */ || node.flags & 512 /* Async */) { + emitDownLevelExpressionFunctionBody(node, body); + return; + } + // For es6 and higher we can emit the expression as is. However, in the case + // where the expression might end up looking like a block when emitted, we'll + // also wrap it in parentheses first. For example if you have: a => {} + // then we need to generate: a => ({}) + write(" "); + // Unwrap all type assertions. + var current = body; + while (current.kind === 171 /* TypeAssertionExpression */) { + current = current.expression; + } + emitParenthesizedIf(body, current.kind === 165 /* ObjectLiteralExpression */); + } + function emitDownLevelExpressionFunctionBody(node, body) { + write(" {"); + scopeEmitStart(node); + increaseIndent(); + var outPos = writer.getTextPos(); + emitDetachedComments(node.body); + emitFunctionBodyPreamble(node); + var preambleEmitted = writer.getTextPos() !== outPos; + decreaseIndent(); + // If we didn't have to emit any preamble code, then attempt to keep the arrow + // function on one line. + if (!preambleEmitted && nodeStartPositionsAreOnSameLine(node, body)) { + write(" "); + emitStart(body); + write("return "); + emit(body); + emitEnd(body); + write(";"); + emitTempDeclarations(/*newLine*/ false); + write(" "); + } + else { + increaseIndent(); + writeLine(); + emitLeadingComments(node.body); + write("return "); + emit(body); + write(";"); + emitTrailingComments(node.body); + emitTempDeclarations(/*newLine*/ true); + decreaseIndent(); + writeLine(); + } + emitStart(node.body); + write("}"); + emitEnd(node.body); + scopeEmitEnd(); + } + function emitBlockFunctionBody(node, body) { + write(" {"); + scopeEmitStart(node); + var initialTextPos = writer.getTextPos(); + increaseIndent(); + emitDetachedComments(body.statements); + // Emit all the directive prologues (like "use strict"). These have to come before + // any other preamble code we write (like parameter initializers). + var startIndex = emitDirectivePrologues(body.statements, /*startWithNewLine*/ true); + emitFunctionBodyPreamble(node); + decreaseIndent(); + var preambleEmitted = writer.getTextPos() !== initialTextPos; + if (!preambleEmitted && nodeEndIsOnSameLineAsNodeStart(body, body)) { + for (var _a = 0, _b = body.statements; _a < _b.length; _a++) { + var statement = _b[_a]; + write(" "); + emit(statement); + } + emitTempDeclarations(/*newLine*/ false); + write(" "); + emitLeadingCommentsOfPosition(body.statements.end); + } + else { + increaseIndent(); + emitLinesStartingAt(body.statements, startIndex); + emitTempDeclarations(/*newLine*/ true); + writeLine(); + emitLeadingCommentsOfPosition(body.statements.end); + decreaseIndent(); + } + emitToken(16 /* CloseBraceToken */, body.statements.end); + scopeEmitEnd(); + } + function findInitialSuperCall(ctor) { + if (ctor.body) { + var statement = ctor.body.statements[0]; + if (statement && statement.kind === 195 /* ExpressionStatement */) { + var expr = statement.expression; + if (expr && expr.kind === 168 /* CallExpression */) { + var func = expr.expression; + if (func && func.kind === 95 /* SuperKeyword */) { + return statement; + } + } + } + } + } + function emitParameterPropertyAssignments(node) { + ts.forEach(node.parameters, function (param) { + if (param.flags & 112 /* AccessibilityModifier */) { + writeLine(); + emitStart(param); + emitStart(param.name); + write("this."); + emitNodeWithoutSourceMap(param.name); + emitEnd(param.name); + write(" = "); + emit(param.name); + write(";"); + emitEnd(param); + } + }); + } + function emitMemberAccessForPropertyName(memberName) { + // This does not emit source map because it is emitted by caller as caller + // is aware how the property name changes to the property access + // eg. public x = 10; becomes this.x and static x = 10 becomes className.x + if (memberName.kind === 9 /* StringLiteral */ || memberName.kind === 8 /* NumericLiteral */) { + write("["); + emitNodeWithCommentsAndWithoutSourcemap(memberName); + write("]"); + } + else if (memberName.kind === 136 /* ComputedPropertyName */) { + emitComputedPropertyName(memberName); + } + else { + write("."); + emitNodeWithCommentsAndWithoutSourcemap(memberName); + } + } + function getInitializedProperties(node, isStatic) { + var properties = []; + for (var _a = 0, _b = node.members; _a < _b.length; _a++) { + var member = _b[_a]; + if (member.kind === 141 /* PropertyDeclaration */ && isStatic === ((member.flags & 128 /* Static */) !== 0) && member.initializer) { + properties.push(member); + } + } + return properties; + } + function emitPropertyDeclarations(node, properties) { + for (var _a = 0; _a < properties.length; _a++) { + var property = properties[_a]; + emitPropertyDeclaration(node, property); + } + } + function emitPropertyDeclaration(node, property, receiver, isExpression) { + writeLine(); + emitLeadingComments(property); + emitStart(property); + emitStart(property.name); + if (receiver) { + emit(receiver); + } + else { + if (property.flags & 128 /* Static */) { + emitDeclarationName(node); + } + else { + write("this"); + } + } + emitMemberAccessForPropertyName(property.name); + emitEnd(property.name); + write(" = "); + emit(property.initializer); + if (!isExpression) { + write(";"); + } + emitEnd(property); + emitTrailingComments(property); + } + function emitMemberFunctionsForES5AndLower(node) { + ts.forEach(node.members, function (member) { + if (member.kind === 191 /* SemicolonClassElement */) { + writeLine(); + write(";"); + } + else if (member.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */) { + if (!member.body) { + return emitCommentsOnNotEmittedNode(member); + } + writeLine(); + emitLeadingComments(member); + emitStart(member); + emitStart(member.name); + emitClassMemberPrefix(node, member); + emitMemberAccessForPropertyName(member.name); + emitEnd(member.name); + write(" = "); + emitFunctionDeclaration(member); + emitEnd(member); + write(";"); + emitTrailingComments(member); + } + else if (member.kind === 145 /* GetAccessor */ || member.kind === 146 /* SetAccessor */) { + var accessors = ts.getAllAccessorDeclarations(node.members, member); + if (member === accessors.firstAccessor) { + writeLine(); + emitStart(member); + write("Object.defineProperty("); + emitStart(member.name); + emitClassMemberPrefix(node, member); + write(", "); + emitExpressionForPropertyName(member.name); + emitEnd(member.name); + write(", {"); + increaseIndent(); + if (accessors.getAccessor) { + writeLine(); + emitLeadingComments(accessors.getAccessor); + write("get: "); + emitStart(accessors.getAccessor); + write("function "); + emitSignatureAndBody(accessors.getAccessor); + emitEnd(accessors.getAccessor); + emitTrailingComments(accessors.getAccessor); + write(","); + } + if (accessors.setAccessor) { + writeLine(); + emitLeadingComments(accessors.setAccessor); + write("set: "); + emitStart(accessors.setAccessor); + write("function "); + emitSignatureAndBody(accessors.setAccessor); + emitEnd(accessors.setAccessor); + emitTrailingComments(accessors.setAccessor); + write(","); + } + writeLine(); + write("enumerable: true,"); + writeLine(); + write("configurable: true"); + decreaseIndent(); + writeLine(); + write("});"); + emitEnd(member); + } + } + }); + } + function emitMemberFunctionsForES6AndHigher(node) { + for (var _a = 0, _b = node.members; _a < _b.length; _a++) { + var member = _b[_a]; + if ((member.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */) && !member.body) { + emitCommentsOnNotEmittedNode(member); + } + else if (member.kind === 143 /* MethodDeclaration */ || + member.kind === 145 /* GetAccessor */ || + member.kind === 146 /* SetAccessor */) { + writeLine(); + emitLeadingComments(member); + emitStart(member); + if (member.flags & 128 /* Static */) { + write("static "); + } + if (member.kind === 145 /* GetAccessor */) { + write("get "); + } + else if (member.kind === 146 /* SetAccessor */) { + write("set "); + } + if (member.asteriskToken) { + write("*"); + } + emit(member.name); + emitSignatureAndBody(member); + emitEnd(member); + emitTrailingComments(member); + } + else if (member.kind === 191 /* SemicolonClassElement */) { + writeLine(); + write(";"); + } + } + } + function emitConstructor(node, baseTypeElement) { + var saveTempFlags = tempFlags; + var saveTempVariables = tempVariables; + var saveTempParameters = tempParameters; + tempFlags = 0; + tempVariables = undefined; + tempParameters = undefined; + emitConstructorWorker(node, baseTypeElement); + tempFlags = saveTempFlags; + tempVariables = saveTempVariables; + tempParameters = saveTempParameters; + } + function emitConstructorWorker(node, baseTypeElement) { + // Check if we have property assignment inside class declaration. + // If there is property assignment, we need to emit constructor whether users define it or not + // If there is no property assignment, we can omit constructor if users do not define it + var hasInstancePropertyWithInitializer = false; + // Emit the constructor overload pinned comments + ts.forEach(node.members, function (member) { + if (member.kind === 144 /* Constructor */ && !member.body) { + emitCommentsOnNotEmittedNode(member); + } + // Check if there is any non-static property assignment + if (member.kind === 141 /* PropertyDeclaration */ && member.initializer && (member.flags & 128 /* Static */) === 0) { + hasInstancePropertyWithInitializer = true; + } + }); + var ctor = ts.getFirstConstructorWithBody(node); + // For target ES6 and above, if there is no user-defined constructor and there is no property assignment + // do not emit constructor in class declaration. + if (languageVersion >= 2 /* ES6 */ && !ctor && !hasInstancePropertyWithInitializer) { + return; + } + if (ctor) { + emitLeadingComments(ctor); + } + emitStart(ctor || node); + if (languageVersion < 2 /* ES6 */) { + write("function "); + emitDeclarationName(node); + emitSignatureParameters(ctor); + } + else { + write("constructor"); + if (ctor) { + emitSignatureParameters(ctor); + } + else { + // Based on EcmaScript6 section 14.5.14: Runtime Semantics: ClassDefinitionEvaluation. + // If constructor is empty, then, + // If ClassHeritageopt is present, then + // Let constructor be the result of parsing the String "constructor(... args){ super (...args);}" using the syntactic grammar with the goal symbol MethodDefinition. + // Else, + // Let constructor be the result of parsing the String "constructor( ){ }" using the syntactic grammar with the goal symbol MethodDefinition + if (baseTypeElement) { + write("(...args)"); + } + else { + write("()"); + } + } + } + var startIndex = 0; + write(" {"); + scopeEmitStart(node, "constructor"); + increaseIndent(); + if (ctor) { + // Emit all the directive prologues (like "use strict"). These have to come before + // any other preamble code we write (like parameter initializers). + startIndex = emitDirectivePrologues(ctor.body.statements, /*startWithNewLine*/ true); + emitDetachedComments(ctor.body.statements); + } + emitCaptureThisForNodeIfNecessary(node); + var superCall; + if (ctor) { + emitDefaultValueAssignments(ctor); + emitRestParameter(ctor); + if (baseTypeElement) { + superCall = findInitialSuperCall(ctor); + if (superCall) { + writeLine(); + emit(superCall); + } + } + emitParameterPropertyAssignments(ctor); + } + else { + if (baseTypeElement) { + writeLine(); + emitStart(baseTypeElement); + if (languageVersion < 2 /* ES6 */) { + write("_super.apply(this, arguments);"); + } + else { + write("super(...args);"); + } + emitEnd(baseTypeElement); + } + } + emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ false)); + if (ctor) { + var statements = ctor.body.statements; + if (superCall) { + statements = statements.slice(1); + } + emitLinesStartingAt(statements, startIndex); + } + emitTempDeclarations(/*newLine*/ true); + writeLine(); + if (ctor) { + emitLeadingCommentsOfPosition(ctor.body.statements.end); + } + decreaseIndent(); + emitToken(16 /* CloseBraceToken */, ctor ? ctor.body.statements.end : node.members.end); + scopeEmitEnd(); + emitEnd(ctor || node); + if (ctor) { + emitTrailingComments(ctor); + } + } + function emitClassExpression(node) { + return emitClassLikeDeclaration(node); + } + function emitClassDeclaration(node) { + return emitClassLikeDeclaration(node); + } + function emitClassLikeDeclaration(node) { + if (languageVersion < 2 /* ES6 */) { + emitClassLikeDeclarationBelowES6(node); + } + else { + emitClassLikeDeclarationForES6AndHigher(node); + } + if (modulekind !== 5 /* ES6 */ && node.parent === currentSourceFile && node.name) { + emitExportMemberAssignments(node.name); + } + } + function emitClassLikeDeclarationForES6AndHigher(node) { + var thisNodeIsDecorated = ts.nodeIsDecorated(node); + if (node.kind === 214 /* ClassDeclaration */) { + if (thisNodeIsDecorated) { + // To preserve the correct runtime semantics when decorators are applied to the class, + // the emit needs to follow one of the following rules: + // + // * For a local class declaration: + // + // @dec class C { + // } + // + // The emit should be: + // + // let C = class { + // }; + // C = __decorate([dec], C); + // + // * For an exported class declaration: + // + // @dec export class C { + // } + // + // The emit should be: + // + // export let C = class { + // }; + // C = __decorate([dec], C); + // + // * For a default export of a class declaration with a name: + // + // @dec default export class C { + // } + // + // The emit should be: + // + // let C = class { + // } + // C = __decorate([dec], C); + // export default C; + // + // * For a default export of a class declaration without a name: + // + // @dec default export class { + // } + // + // The emit should be: + // + // let _default = class { + // } + // _default = __decorate([dec], _default); + // export default _default; + // + if (isES6ExportedDeclaration(node) && !(node.flags & 1024 /* Default */)) { + write("export "); + } + write("let "); + emitDeclarationName(node); + write(" = "); + } + else if (isES6ExportedDeclaration(node)) { + write("export "); + if (node.flags & 1024 /* Default */) { + write("default "); + } + } + } + // If the class has static properties, and it's a class expression, then we'll need + // to specialize the emit a bit. for a class expression of the form: + // + // class C { static a = 1; static b = 2; ... } + // + // We'll emit: + // + // (_temp = class C { ... }, _temp.a = 1, _temp.b = 2, _temp) + // + // This keeps the expression as an expression, while ensuring that the static parts + // of it have been initialized by the time it is used. + var staticProperties = getInitializedProperties(node, /*static:*/ true); + var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 186 /* ClassExpression */; + var tempVariable; + if (isClassExpressionWithStaticProperties) { + tempVariable = createAndRecordTempVariable(0 /* Auto */); + write("("); + increaseIndent(); + emit(tempVariable); + write(" = "); + } + write("class"); + // emit name if + // - node has a name + // - this is default export with static initializers + if ((node.name || (node.flags & 1024 /* Default */ && staticProperties.length > 0)) && !thisNodeIsDecorated) { + write(" "); + emitDeclarationName(node); + } + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + if (baseTypeNode) { + write(" extends "); + emit(baseTypeNode.expression); + } + write(" {"); + increaseIndent(); + scopeEmitStart(node); + writeLine(); + emitConstructor(node, baseTypeNode); + emitMemberFunctionsForES6AndHigher(node); + decreaseIndent(); + writeLine(); + emitToken(16 /* CloseBraceToken */, node.members.end); + scopeEmitEnd(); + // TODO(rbuckton): Need to go back to `let _a = class C {}` approach, removing the defineProperty call for now. + // For a decorated class, we need to assign its name (if it has one). This is because we emit + // the class as a class expression to avoid the double-binding of the identifier: + // + // let C = class { + // } + // Object.defineProperty(C, "name", { value: "C", configurable: true }); + // + if (thisNodeIsDecorated) { + write(";"); + } + // Emit static property assignment. Because classDeclaration is lexically evaluated, + // it is safe to emit static property assignment after classDeclaration + // From ES6 specification: + // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using + // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. + if (isClassExpressionWithStaticProperties) { + for (var _a = 0; _a < staticProperties.length; _a++) { + var property = staticProperties[_a]; + write(","); + writeLine(); + emitPropertyDeclaration(node, property, /*receiver:*/ tempVariable, /*isExpression:*/ true); + } + write(","); + writeLine(); + emit(tempVariable); + decreaseIndent(); + write(")"); + } + else { + writeLine(); + emitPropertyDeclarations(node, staticProperties); + emitDecoratorsOfClass(node); + } + // If this is an exported class, but not on the top level (i.e. on an internal + // module), export it + if (!isES6ExportedDeclaration(node) && (node.flags & 1 /* Export */)) { + writeLine(); + emitStart(node); + emitModuleMemberName(node); + write(" = "); + emitDeclarationName(node); + emitEnd(node); + write(";"); + } + else if (isES6ExportedDeclaration(node) && (node.flags & 1024 /* Default */) && thisNodeIsDecorated) { + // if this is a top level default export of decorated class, write the export after the declaration. + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } + } + function emitClassLikeDeclarationBelowES6(node) { + if (node.kind === 214 /* ClassDeclaration */) { + // source file level classes in system modules are hoisted so 'var's for them are already defined + if (!shouldHoistDeclarationInSystemJsModule(node)) { + write("var "); + } + emitDeclarationName(node); + write(" = "); + } + write("(function ("); + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + if (baseTypeNode) { + write("_super"); + } + write(") {"); + var saveTempFlags = tempFlags; + var saveTempVariables = tempVariables; + var saveTempParameters = tempParameters; + var saveComputedPropertyNamesToGeneratedNames = computedPropertyNamesToGeneratedNames; + tempFlags = 0; + tempVariables = undefined; + tempParameters = undefined; + computedPropertyNamesToGeneratedNames = undefined; + increaseIndent(); + scopeEmitStart(node); + if (baseTypeNode) { + writeLine(); + emitStart(baseTypeNode); + write("__extends("); + emitDeclarationName(node); + write(", _super);"); + emitEnd(baseTypeNode); + } + writeLine(); + emitConstructor(node, baseTypeNode); + emitMemberFunctionsForES5AndLower(node); + emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ true)); + writeLine(); + emitDecoratorsOfClass(node); + writeLine(); + emitToken(16 /* CloseBraceToken */, node.members.end, function () { + write("return "); + emitDeclarationName(node); + }); + write(";"); + emitTempDeclarations(/*newLine*/ true); + tempFlags = saveTempFlags; + tempVariables = saveTempVariables; + tempParameters = saveTempParameters; + computedPropertyNamesToGeneratedNames = saveComputedPropertyNamesToGeneratedNames; + decreaseIndent(); + writeLine(); + emitToken(16 /* CloseBraceToken */, node.members.end); + scopeEmitEnd(); + emitStart(node); + write(")("); + if (baseTypeNode) { + emit(baseTypeNode.expression); + } + write(")"); + if (node.kind === 214 /* ClassDeclaration */) { + write(";"); + } + emitEnd(node); + if (node.kind === 214 /* ClassDeclaration */) { + emitExportMemberAssignment(node); + } + } + function emitClassMemberPrefix(node, member) { + emitDeclarationName(node); + if (!(member.flags & 128 /* Static */)) { + write(".prototype"); + } + } + function emitDecoratorsOfClass(node) { + emitDecoratorsOfMembers(node, /*staticFlag*/ 0); + emitDecoratorsOfMembers(node, 128 /* Static */); + emitDecoratorsOfConstructor(node); + } + function emitDecoratorsOfConstructor(node) { + var decorators = node.decorators; + var constructor = ts.getFirstConstructorWithBody(node); + var hasDecoratedParameters = constructor && ts.forEach(constructor.parameters, ts.nodeIsDecorated); + // skip decoration of the constructor if neither it nor its parameters are decorated + if (!decorators && !hasDecoratedParameters) { + return; + } + // Emit the call to __decorate. Given the class: + // + // @dec + // class C { + // } + // + // The emit for the class is: + // + // C = __decorate([dec], C); + // + writeLine(); + emitStart(node); + emitDeclarationName(node); + write(" = __decorate(["); + increaseIndent(); + writeLine(); + var decoratorCount = decorators ? decorators.length : 0; + var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { + emitStart(decorator); + emit(decorator.expression); + emitEnd(decorator); + }); + argumentsWritten += emitDecoratorsOfParameters(constructor, /*leadingComma*/ argumentsWritten > 0); + emitSerializedTypeMetadata(node, /*leadingComma*/ argumentsWritten >= 0); + decreaseIndent(); + writeLine(); + write("], "); + emitDeclarationName(node); + write(");"); + emitEnd(node); + writeLine(); + } + function emitDecoratorsOfMembers(node, staticFlag) { + for (var _a = 0, _b = node.members; _a < _b.length; _a++) { + var member = _b[_a]; + // only emit members in the correct group + if ((member.flags & 128 /* Static */) !== staticFlag) { + continue; + } + // skip members that cannot be decorated (such as the constructor) + if (!ts.nodeCanBeDecorated(member)) { + continue; + } + // skip a member if it or any of its parameters are not decorated + if (!ts.nodeOrChildIsDecorated(member)) { + continue; + } + // skip an accessor declaration if it is not the first accessor + var decorators = void 0; + var functionLikeMember = void 0; + if (ts.isAccessor(member)) { + var accessors = ts.getAllAccessorDeclarations(node.members, member); + if (member !== accessors.firstAccessor) { + continue; + } + // get the decorators from the first accessor with decorators + decorators = accessors.firstAccessor.decorators; + if (!decorators && accessors.secondAccessor) { + decorators = accessors.secondAccessor.decorators; + } + // we only decorate parameters of the set accessor + functionLikeMember = accessors.setAccessor; + } + else { + decorators = member.decorators; + // we only decorate the parameters here if this is a method + if (member.kind === 143 /* MethodDeclaration */) { + functionLikeMember = member; + } + } + // Emit the call to __decorate. Given the following: + // + // class C { + // @dec method(@dec2 x) {} + // @dec get accessor() {} + // @dec prop; + // } + // + // The emit for a method is: + // + // __decorate([ + // dec, + // __param(0, dec2), + // __metadata("design:type", Function), + // __metadata("design:paramtypes", [Object]), + // __metadata("design:returntype", void 0) + // ], C.prototype, "method", undefined); + // + // The emit for an accessor is: + // + // __decorate([ + // dec + // ], C.prototype, "accessor", undefined); + // + // The emit for a property is: + // + // __decorate([ + // dec + // ], C.prototype, "prop"); + // + writeLine(); + emitStart(member); + write("__decorate(["); + increaseIndent(); + writeLine(); + var decoratorCount = decorators ? decorators.length : 0; + var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { + emitStart(decorator); + emit(decorator.expression); + emitEnd(decorator); + }); + argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); + emitSerializedTypeMetadata(member, argumentsWritten > 0); + decreaseIndent(); + writeLine(); + write("], "); + emitStart(member.name); + emitClassMemberPrefix(node, member); + write(", "); + emitExpressionForPropertyName(member.name); + emitEnd(member.name); + if (languageVersion > 0 /* ES3 */) { + if (member.kind !== 141 /* PropertyDeclaration */) { + // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly. + // We have this extra argument here so that we can inject an explicit property descriptor at a later date. + write(", null"); + } + else { + // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it + // should not invoke `Object.getOwnPropertyDescriptor`. + write(", void 0"); + } + } + write(");"); + emitEnd(member); + writeLine(); + } + } + function emitDecoratorsOfParameters(node, leadingComma) { + var argumentsWritten = 0; + if (node) { + var parameterIndex = 0; + for (var _a = 0, _b = node.parameters; _a < _b.length; _a++) { + var parameter = _b[_a]; + if (ts.nodeIsDecorated(parameter)) { + var decorators = parameter.decorators; + argumentsWritten += emitList(decorators, 0, decorators.length, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ leadingComma, /*noTrailingNewLine*/ true, function (decorator) { + emitStart(decorator); + write("__param(" + parameterIndex + ", "); + emit(decorator.expression); + write(")"); + emitEnd(decorator); + }); + leadingComma = true; + } + ++parameterIndex; + } + } + return argumentsWritten; + } + function shouldEmitTypeMetadata(node) { + // This method determines whether to emit the "design:type" metadata based on the node's kind. + // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata + // compiler option is set. + switch (node.kind) { + case 143 /* MethodDeclaration */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 141 /* PropertyDeclaration */: + return true; + } + return false; + } + function shouldEmitReturnTypeMetadata(node) { + // This method determines whether to emit the "design:returntype" metadata based on the node's kind. + // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata + // compiler option is set. + switch (node.kind) { + case 143 /* MethodDeclaration */: + return true; + } + return false; + } + function shouldEmitParamTypesMetadata(node) { + // This method determines whether to emit the "design:paramtypes" metadata based on the node's kind. + // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata + // compiler option is set. + switch (node.kind) { + case 214 /* ClassDeclaration */: + case 143 /* MethodDeclaration */: + case 146 /* SetAccessor */: + return true; + } + return false; + } + /** Serializes the type of a declaration to an appropriate JS constructor value. Used by the __metadata decorator for a class member. */ + function emitSerializedTypeOfNode(node) { + // serialization of the type of a declaration uses the following rules: + // + // * The serialized type of a ClassDeclaration is "Function" + // * The serialized type of a ParameterDeclaration is the serialized type of its type annotation. + // * The serialized type of a PropertyDeclaration is the serialized type of its type annotation. + // * The serialized type of an AccessorDeclaration is the serialized type of the return type annotation of its getter or parameter type annotation of its setter. + // * The serialized type of any other FunctionLikeDeclaration is "Function". + // * The serialized type of any other node is "void 0". + // + // For rules on serializing type annotations, see `serializeTypeNode`. + switch (node.kind) { + case 214 /* ClassDeclaration */: + write("Function"); + return; + case 141 /* PropertyDeclaration */: + emitSerializedTypeNode(node.type); + return; + case 138 /* Parameter */: + emitSerializedTypeNode(node.type); + return; + case 145 /* GetAccessor */: + emitSerializedTypeNode(node.type); + return; + case 146 /* SetAccessor */: + emitSerializedTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); + return; + } + if (ts.isFunctionLike(node)) { + write("Function"); + return; + } + write("void 0"); + } + function emitSerializedTypeNode(node) { + if (node) { + switch (node.kind) { + case 103 /* VoidKeyword */: + write("void 0"); + return; + case 160 /* ParenthesizedType */: + emitSerializedTypeNode(node.type); + return; + case 152 /* FunctionType */: + case 153 /* ConstructorType */: + write("Function"); + return; + case 156 /* ArrayType */: + case 157 /* TupleType */: + write("Array"); + return; + case 150 /* TypePredicate */: + case 120 /* BooleanKeyword */: + write("Boolean"); + return; + case 130 /* StringKeyword */: + case 9 /* StringLiteral */: + write("String"); + return; + case 128 /* NumberKeyword */: + write("Number"); + return; + case 131 /* SymbolKeyword */: + write("Symbol"); + return; + case 151 /* TypeReference */: + emitSerializedTypeReferenceNode(node); + return; + case 154 /* TypeQuery */: + case 155 /* TypeLiteral */: + case 158 /* UnionType */: + case 159 /* IntersectionType */: + case 117 /* AnyKeyword */: + break; + default: + ts.Debug.fail("Cannot serialize unexpected type node."); + break; + } + } + write("Object"); + } + /** Serializes a TypeReferenceNode to an appropriate JS constructor value. Used by the __metadata decorator. */ + function emitSerializedTypeReferenceNode(node) { + var location = node.parent; + while (ts.isDeclaration(location) || ts.isTypeNode(location)) { + location = location.parent; + } + // Clone the type name and parent it to a location outside of the current declaration. + var typeName = ts.cloneEntityName(node.typeName); + typeName.parent = location; + var result = resolver.getTypeReferenceSerializationKind(typeName); + switch (result) { + case ts.TypeReferenceSerializationKind.Unknown: + var temp = createAndRecordTempVariable(0 /* Auto */); + write("(typeof ("); + emitNodeWithoutSourceMap(temp); + write(" = "); + emitEntityNameAsExpression(typeName, /*useFallback*/ true); + write(") === 'function' && "); + emitNodeWithoutSourceMap(temp); + write(") || Object"); + break; + case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: + emitEntityNameAsExpression(typeName, /*useFallback*/ false); + break; + case ts.TypeReferenceSerializationKind.VoidType: + write("void 0"); + break; + case ts.TypeReferenceSerializationKind.BooleanType: + write("Boolean"); + break; + case ts.TypeReferenceSerializationKind.NumberLikeType: + write("Number"); + break; + case ts.TypeReferenceSerializationKind.StringLikeType: + write("String"); + break; + case ts.TypeReferenceSerializationKind.ArrayLikeType: + write("Array"); + break; + case ts.TypeReferenceSerializationKind.ESSymbolType: + if (languageVersion < 2 /* ES6 */) { + write("typeof Symbol === 'function' ? Symbol : Object"); + } + else { + write("Symbol"); + } + break; + case ts.TypeReferenceSerializationKind.TypeWithCallSignature: + write("Function"); + break; + case ts.TypeReferenceSerializationKind.ObjectType: + write("Object"); + break; + } + } + /** Serializes the parameter types of a function or the constructor of a class. Used by the __metadata decorator for a method or set accessor. */ + function emitSerializedParameterTypesOfNode(node) { + // serialization of parameter types uses the following rules: + // + // * If the declaration is a class, the parameters of the first constructor with a body are used. + // * If the declaration is function-like and has a body, the parameters of the function are used. + // + // For the rules on serializing the type of each parameter declaration, see `serializeTypeOfDeclaration`. + if (node) { + var valueDeclaration; + if (node.kind === 214 /* ClassDeclaration */) { + valueDeclaration = ts.getFirstConstructorWithBody(node); + } + else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) { + valueDeclaration = node; + } + if (valueDeclaration) { + var parameters = valueDeclaration.parameters; + var parameterCount = parameters.length; + if (parameterCount > 0) { + for (var i = 0; i < parameterCount; i++) { + if (i > 0) { + write(", "); + } + if (parameters[i].dotDotDotToken) { + var parameterType = parameters[i].type; + if (parameterType.kind === 156 /* ArrayType */) { + parameterType = parameterType.elementType; + } + else if (parameterType.kind === 151 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + parameterType = parameterType.typeArguments[0]; + } + else { + parameterType = undefined; + } + emitSerializedTypeNode(parameterType); + } + else { + emitSerializedTypeOfNode(parameters[i]); + } + } + } + } + } + } + /** Serializes the return type of function. Used by the __metadata decorator for a method. */ + function emitSerializedReturnTypeOfNode(node) { + if (node && ts.isFunctionLike(node) && node.type) { + emitSerializedTypeNode(node.type); + return; + } + write("void 0"); + } + function emitSerializedTypeMetadata(node, writeComma) { + // This method emits the serialized type metadata for a decorator target. + // The caller should have already tested whether the node has decorators. + var argumentsWritten = 0; + if (compilerOptions.emitDecoratorMetadata) { + if (shouldEmitTypeMetadata(node)) { + if (writeComma) { + write(", "); + } + writeLine(); + write("__metadata('design:type', "); + emitSerializedTypeOfNode(node); + write(")"); + argumentsWritten++; + } + if (shouldEmitParamTypesMetadata(node)) { + if (writeComma || argumentsWritten) { + write(", "); + } + writeLine(); + write("__metadata('design:paramtypes', ["); + emitSerializedParameterTypesOfNode(node); + write("])"); + argumentsWritten++; + } + if (shouldEmitReturnTypeMetadata(node)) { + if (writeComma || argumentsWritten) { + write(", "); + } + writeLine(); + write("__metadata('design:returntype', "); + emitSerializedReturnTypeOfNode(node); + write(")"); + argumentsWritten++; + } + } + return argumentsWritten; + } + function emitInterfaceDeclaration(node) { + emitCommentsOnNotEmittedNode(node); + } + function shouldEmitEnumDeclaration(node) { + var isConstEnum = ts.isConst(node); + return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; + } + function emitEnumDeclaration(node) { + // const enums are completely erased during compilation. + if (!shouldEmitEnumDeclaration(node)) { + return; + } + if (!shouldHoistDeclarationInSystemJsModule(node)) { + // do not emit var if variable was already hoisted + if (!(node.flags & 1 /* Export */) || isES6ExportedDeclaration(node)) { + emitStart(node); + if (isES6ExportedDeclaration(node)) { + write("export "); + } + write("var "); + emit(node.name); + emitEnd(node); + write(";"); + } + } + writeLine(); + emitStart(node); + write("(function ("); + emitStart(node.name); + write(getGeneratedNameForNode(node)); + emitEnd(node.name); + write(") {"); + increaseIndent(); + scopeEmitStart(node); + emitLines(node.members); + decreaseIndent(); + writeLine(); + emitToken(16 /* CloseBraceToken */, node.members.end); + scopeEmitEnd(); + write(")("); + emitModuleMemberName(node); + write(" || ("); + emitModuleMemberName(node); + write(" = {}));"); + emitEnd(node); + if (!isES6ExportedDeclaration(node) && node.flags & 1 /* Export */ && !shouldHoistDeclarationInSystemJsModule(node)) { + // do not emit var if variable was already hoisted + writeLine(); + emitStart(node); + write("var "); + emit(node.name); + write(" = "); + emitModuleMemberName(node); + emitEnd(node); + write(";"); + } + if (modulekind !== 5 /* ES6 */ && node.parent === currentSourceFile) { + if (modulekind === 4 /* System */ && (node.flags & 1 /* Export */)) { + // write the call to exporter for enum + writeLine(); + write(exportFunctionForFile + "(\""); + emitDeclarationName(node); + write("\", "); + emitDeclarationName(node); + write(");"); + } + emitExportMemberAssignments(node.name); + } + } + function emitEnumMember(node) { + var enumParent = node.parent; + emitStart(node); + write(getGeneratedNameForNode(enumParent)); + write("["); + write(getGeneratedNameForNode(enumParent)); + write("["); + emitExpressionForPropertyName(node.name); + write("] = "); + writeEnumMemberDeclarationValue(node); + write("] = "); + emitExpressionForPropertyName(node.name); + emitEnd(node); + write(";"); + } + function writeEnumMemberDeclarationValue(member) { + var value = resolver.getConstantValue(member); + if (value !== undefined) { + write(value.toString()); + return; + } + else if (member.initializer) { + emit(member.initializer); + } + else { + write("undefined"); + } + } + function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { + if (moduleDeclaration.body.kind === 218 /* ModuleDeclaration */) { + var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); + return recursiveInnerModule || moduleDeclaration.body; + } + } + function shouldEmitModuleDeclaration(node) { + return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + } + function isModuleMergedWithES6Class(node) { + return languageVersion === 2 /* ES6 */ && !!(resolver.getNodeCheckFlags(node) & 32768 /* LexicalModuleMergesWithClass */); + } + function emitModuleDeclaration(node) { + // Emit only if this module is non-ambient. + var shouldEmit = shouldEmitModuleDeclaration(node); + if (!shouldEmit) { + return emitCommentsOnNotEmittedNode(node); + } + var hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node); + var emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); + if (emitVarForModule) { + emitStart(node); + if (isES6ExportedDeclaration(node)) { + write("export "); + } + write("var "); + emit(node.name); + write(";"); + emitEnd(node); + writeLine(); + } + emitStart(node); + write("(function ("); + emitStart(node.name); + write(getGeneratedNameForNode(node)); + emitEnd(node.name); + write(") "); + if (node.body.kind === 219 /* ModuleBlock */) { + var saveTempFlags = tempFlags; + var saveTempVariables = tempVariables; + tempFlags = 0; + tempVariables = undefined; + emit(node.body); + tempFlags = saveTempFlags; + tempVariables = saveTempVariables; + } + else { + write("{"); + increaseIndent(); + scopeEmitStart(node); + emitCaptureThisForNodeIfNecessary(node); + writeLine(); + emit(node.body); + decreaseIndent(); + writeLine(); + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + emitToken(16 /* CloseBraceToken */, moduleBlock.statements.end); + scopeEmitEnd(); + } + write(")("); + // write moduleDecl = containingModule.m only if it is not exported es6 module member + if ((node.flags & 1 /* Export */) && !isES6ExportedDeclaration(node)) { + emit(node.name); + write(" = "); + } + emitModuleMemberName(node); + write(" || ("); + emitModuleMemberName(node); + write(" = {}));"); + emitEnd(node); + if (!isES6ExportedDeclaration(node) && node.name.kind === 69 /* Identifier */ && node.parent === currentSourceFile) { + if (modulekind === 4 /* System */ && (node.flags & 1 /* Export */)) { + writeLine(); + write(exportFunctionForFile + "(\""); + emitDeclarationName(node); + write("\", "); + emitDeclarationName(node); + write(");"); + } + emitExportMemberAssignments(node.name); + } + } + /* + * Some bundlers (SystemJS builder) sometimes want to rename dependencies. + * Here we check if alternative name was provided for a given moduleName and return it if possible. + */ + function tryRenameExternalModule(moduleName) { + if (currentSourceFile.renamedDependencies && ts.hasProperty(currentSourceFile.renamedDependencies, moduleName.text)) { + return "\"" + currentSourceFile.renamedDependencies[moduleName.text] + "\""; + } + return undefined; + } + function emitRequire(moduleName) { + if (moduleName.kind === 9 /* StringLiteral */) { + write("require("); + var text = tryRenameExternalModule(moduleName); + if (text) { + write(text); + } + else { + emitStart(moduleName); + emitLiteral(moduleName); + emitEnd(moduleName); + } + emitToken(18 /* CloseParenToken */, moduleName.end); + } + else { + write("require()"); + } + } + function getNamespaceDeclarationNode(node) { + if (node.kind === 221 /* ImportEqualsDeclaration */) { + return node; + } + var importClause = node.importClause; + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 224 /* NamespaceImport */) { + return importClause.namedBindings; + } + } + function isDefaultImport(node) { + return node.kind === 222 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; + } + function emitExportImportAssignments(node) { + if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { + emitExportMemberAssignments(node.name); + } + ts.forEachChild(node, emitExportImportAssignments); + } + function emitImportDeclaration(node) { + if (modulekind !== 5 /* ES6 */) { + return emitExternalImportDeclaration(node); + } + // ES6 import + if (node.importClause) { + var shouldEmitDefaultBindings = resolver.isReferencedAliasDeclaration(node.importClause); + var shouldEmitNamedBindings = node.importClause.namedBindings && resolver.isReferencedAliasDeclaration(node.importClause.namedBindings, /* checkChildren */ true); + if (shouldEmitDefaultBindings || shouldEmitNamedBindings) { + write("import "); + emitStart(node.importClause); + if (shouldEmitDefaultBindings) { + emit(node.importClause.name); + if (shouldEmitNamedBindings) { + write(", "); + } + } + if (shouldEmitNamedBindings) { + emitLeadingComments(node.importClause.namedBindings); + emitStart(node.importClause.namedBindings); + if (node.importClause.namedBindings.kind === 224 /* NamespaceImport */) { + write("* as "); + emit(node.importClause.namedBindings.name); + } + else { + write("{ "); + emitExportOrImportSpecifierList(node.importClause.namedBindings.elements, resolver.isReferencedAliasDeclaration); + write(" }"); + } + emitEnd(node.importClause.namedBindings); + emitTrailingComments(node.importClause.namedBindings); + } + emitEnd(node.importClause); + write(" from "); + emit(node.moduleSpecifier); + write(";"); + } + } + else { + write("import "); + emit(node.moduleSpecifier); + write(";"); + } + } + function emitExternalImportDeclaration(node) { + if (ts.contains(externalImports, node)) { + var isExportedImport = node.kind === 221 /* ImportEqualsDeclaration */ && (node.flags & 1 /* Export */) !== 0; + var namespaceDeclaration = getNamespaceDeclarationNode(node); + if (modulekind !== 2 /* AMD */) { + emitLeadingComments(node); + emitStart(node); + if (namespaceDeclaration && !isDefaultImport(node)) { + // import x = require("foo") + // import * as x from "foo" + if (!isExportedImport) + write("var "); + emitModuleMemberName(namespaceDeclaration); + write(" = "); + } + else { + // import "foo" + // import x from "foo" + // import { x, y } from "foo" + // import d, * as x from "foo" + // import d, { x, y } from "foo" + var isNakedImport = 222 /* ImportDeclaration */ && !node.importClause; + if (!isNakedImport) { + write("var "); + write(getGeneratedNameForNode(node)); + write(" = "); + } + } + emitRequire(ts.getExternalModuleName(node)); + if (namespaceDeclaration && isDefaultImport(node)) { + // import d, * as x from "foo" + write(", "); + emitModuleMemberName(namespaceDeclaration); + write(" = "); + write(getGeneratedNameForNode(node)); + } + write(";"); + emitEnd(node); + emitExportImportAssignments(node); + emitTrailingComments(node); + } + else { + if (isExportedImport) { + emitModuleMemberName(namespaceDeclaration); + write(" = "); + emit(namespaceDeclaration.name); + write(";"); + } + else if (namespaceDeclaration && isDefaultImport(node)) { + // import d, * as x from "foo" + write("var "); + emitModuleMemberName(namespaceDeclaration); + write(" = "); + write(getGeneratedNameForNode(node)); + write(";"); + } + emitExportImportAssignments(node); + } + } + } + function emitImportEqualsDeclaration(node) { + if (ts.isExternalModuleImportEqualsDeclaration(node)) { + emitExternalImportDeclaration(node); + return; + } + // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when + // - current file is not external module + // - import declaration is top level and target is value imported by entity name + if (resolver.isReferencedAliasDeclaration(node) || + (!ts.isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportEqualsWithEntityName(node))) { + emitLeadingComments(node); + emitStart(node); + // variable declaration for import-equals declaration can be hoisted in system modules + // in this case 'var' should be omitted and emit should contain only initialization + var variableDeclarationIsHoisted = shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ true); + // is it top level export import v = a.b.c in system module? + // if yes - it needs to be rewritten as exporter('v', v = a.b.c) + var isExported = isSourceFileLevelDeclarationInSystemJsModule(node, /*isExported*/ true); + if (!variableDeclarationIsHoisted) { + ts.Debug.assert(!isExported); + if (isES6ExportedDeclaration(node)) { + write("export "); + write("var "); + } + else if (!(node.flags & 1 /* Export */)) { + write("var "); + } + } + if (isExported) { + write(exportFunctionForFile + "(\""); + emitNodeWithoutSourceMap(node.name); + write("\", "); + } + emitModuleMemberName(node); + write(" = "); + emit(node.moduleReference); + if (isExported) { + write(")"); + } + write(";"); + emitEnd(node); + emitExportImportAssignments(node); + emitTrailingComments(node); + } + } + function emitExportDeclaration(node) { + ts.Debug.assert(modulekind !== 4 /* System */); + if (modulekind !== 5 /* ES6 */) { + if (node.moduleSpecifier && (!node.exportClause || resolver.isValueAliasDeclaration(node))) { + emitStart(node); + var generatedName = getGeneratedNameForNode(node); + if (node.exportClause) { + // export { x, y, ... } from "foo" + if (modulekind !== 2 /* AMD */) { + write("var "); + write(generatedName); + write(" = "); + emitRequire(ts.getExternalModuleName(node)); + write(";"); + } + for (var _a = 0, _b = node.exportClause.elements; _a < _b.length; _a++) { + var specifier = _b[_a]; + if (resolver.isValueAliasDeclaration(specifier)) { + writeLine(); + emitStart(specifier); + emitContainingModuleName(specifier); + write("."); + emitNodeWithCommentsAndWithoutSourcemap(specifier.name); + write(" = "); + write(generatedName); + write("."); + emitNodeWithCommentsAndWithoutSourcemap(specifier.propertyName || specifier.name); + write(";"); + emitEnd(specifier); + } + } + } + else { + // export * from "foo" + writeLine(); + write("__export("); + if (modulekind !== 2 /* AMD */) { + emitRequire(ts.getExternalModuleName(node)); + } + else { + write(generatedName); + } + write(");"); + } + emitEnd(node); + } + } + else { + if (!node.exportClause || resolver.isValueAliasDeclaration(node)) { + write("export "); + if (node.exportClause) { + // export { x, y, ... } + write("{ "); + emitExportOrImportSpecifierList(node.exportClause.elements, resolver.isValueAliasDeclaration); + write(" }"); + } + else { + write("*"); + } + if (node.moduleSpecifier) { + write(" from "); + emit(node.moduleSpecifier); + } + write(";"); + } + } + } + function emitExportOrImportSpecifierList(specifiers, shouldEmit) { + ts.Debug.assert(modulekind === 5 /* ES6 */); + var needsComma = false; + for (var _a = 0; _a < specifiers.length; _a++) { + var specifier = specifiers[_a]; + if (shouldEmit(specifier)) { + if (needsComma) { + write(", "); + } + if (specifier.propertyName) { + emit(specifier.propertyName); + write(" as "); + } + emit(specifier.name); + needsComma = true; + } + } + } + function emitExportAssignment(node) { + if (!node.isExportEquals && resolver.isValueAliasDeclaration(node)) { + if (modulekind === 5 /* ES6 */) { + writeLine(); + emitStart(node); + write("export default "); + var expression = node.expression; + emit(expression); + if (expression.kind !== 213 /* FunctionDeclaration */ && + expression.kind !== 214 /* ClassDeclaration */) { + write(";"); + } + emitEnd(node); + } + else { + writeLine(); + emitStart(node); + if (modulekind === 4 /* System */) { + write(exportFunctionForFile + "(\"default\","); + emit(node.expression); + write(")"); + } + else { + emitEs6ExportDefaultCompat(node); + emitContainingModuleName(node); + if (languageVersion === 0 /* ES3 */) { + write("[\"default\"] = "); + } + else { + write(".default = "); + } + emit(node.expression); + } + write(";"); + emitEnd(node); + } + } + } + function collectExternalModuleInfo(sourceFile) { + externalImports = []; + exportSpecifiers = {}; + exportEquals = undefined; + hasExportStars = false; + for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { + var node = _b[_a]; + switch (node.kind) { + case 222 /* ImportDeclaration */: + if (!node.importClause || + resolver.isReferencedAliasDeclaration(node.importClause, /*checkChildren*/ true)) { + // import "mod" + // import x from "mod" where x is referenced + // import * as x from "mod" where x is referenced + // import { x, y } from "mod" where at least one import is referenced + externalImports.push(node); + } + break; + case 221 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 232 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { + // import x = require("mod") where x is referenced + externalImports.push(node); + } + break; + case 228 /* ExportDeclaration */: + if (node.moduleSpecifier) { + if (!node.exportClause) { + // export * from "mod" + externalImports.push(node); + hasExportStars = true; + } + else if (resolver.isValueAliasDeclaration(node)) { + // export { x, y } from "mod" where at least one export is a value symbol + externalImports.push(node); + } + } + else { + // export { x, y } + for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { + var specifier = _d[_c]; + var name_25 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_25] || (exportSpecifiers[name_25] = [])).push(specifier); + } + } + break; + case 227 /* ExportAssignment */: + if (node.isExportEquals && !exportEquals) { + // export = x + exportEquals = node; + } + break; + } + } + } + function emitExportStarHelper() { + if (hasExportStars) { + writeLine(); + write("function __export(m) {"); + increaseIndent(); + writeLine(); + write("for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];"); + decreaseIndent(); + writeLine(); + write("}"); + } + } + function getLocalNameForExternalImport(node) { + var namespaceDeclaration = getNamespaceDeclarationNode(node); + if (namespaceDeclaration && !isDefaultImport(node)) { + return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name); + } + if (node.kind === 222 /* ImportDeclaration */ && node.importClause) { + return getGeneratedNameForNode(node); + } + if (node.kind === 228 /* ExportDeclaration */ && node.moduleSpecifier) { + return getGeneratedNameForNode(node); + } + } + function getExternalModuleNameText(importNode) { + var moduleName = ts.getExternalModuleName(importNode); + if (moduleName.kind === 9 /* StringLiteral */) { + return tryRenameExternalModule(moduleName) || getLiteralText(moduleName); + } + return undefined; + } + function emitVariableDeclarationsForImports() { + if (externalImports.length === 0) { + return; + } + writeLine(); + var started = false; + for (var _a = 0; _a < externalImports.length; _a++) { + var importNode = externalImports[_a]; + // do not create variable declaration for exports and imports that lack import clause + var skipNode = importNode.kind === 228 /* ExportDeclaration */ || + (importNode.kind === 222 /* ImportDeclaration */ && !importNode.importClause); + if (skipNode) { + continue; + } + if (!started) { + write("var "); + started = true; + } + else { + write(", "); + } + write(getLocalNameForExternalImport(importNode)); + } + if (started) { + write(";"); + } + } + function emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations) { + // when resolving exports local exported entries/indirect exported entries in the module + // should always win over entries with similar names that were added via star exports + // to support this we store names of local/indirect exported entries in a set. + // this set is used to filter names brought by star expors. + if (!hasExportStars) { + // local names set is needed only in presence of star exports + return undefined; + } + // local names set should only be added if we have anything exported + if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { + // no exported declarations (export var ...) or export specifiers (export {x}) + // check if we have any non star export declarations. + var hasExportDeclarationWithExportClause = false; + for (var _a = 0; _a < externalImports.length; _a++) { + var externalImport = externalImports[_a]; + if (externalImport.kind === 228 /* ExportDeclaration */ && externalImport.exportClause) { + hasExportDeclarationWithExportClause = true; + break; + } + } + if (!hasExportDeclarationWithExportClause) { + // we still need to emit exportStar helper + return emitExportStarFunction(/*localNames*/ undefined); + } + } + var exportedNamesStorageRef = makeUniqueName("exportedNames"); + writeLine(); + write("var " + exportedNamesStorageRef + " = {"); + increaseIndent(); + var started = false; + if (exportedDeclarations) { + for (var i = 0; i < exportedDeclarations.length; ++i) { + // write name of exported declaration, i.e 'export var x...' + writeExportedName(exportedDeclarations[i]); + } + } + if (exportSpecifiers) { + for (var n in exportSpecifiers) { + for (var _b = 0, _c = exportSpecifiers[n]; _b < _c.length; _b++) { + var specifier = _c[_b]; + // write name of export specified, i.e. 'export {x}' + writeExportedName(specifier.name); + } + } + } + for (var _d = 0; _d < externalImports.length; _d++) { + var externalImport = externalImports[_d]; + if (externalImport.kind !== 228 /* ExportDeclaration */) { + continue; + } + var exportDecl = externalImport; + if (!exportDecl.exportClause) { + // export * from ... + continue; + } + for (var _e = 0, _f = exportDecl.exportClause.elements; _e < _f.length; _e++) { + var element = _f[_e]; + // write name of indirectly exported entry, i.e. 'export {x} from ...' + writeExportedName(element.name || element.propertyName); + } + } + decreaseIndent(); + writeLine(); + write("};"); + return emitExportStarFunction(exportedNamesStorageRef); + function emitExportStarFunction(localNames) { + var exportStarFunction = makeUniqueName("exportStar"); + writeLine(); + // define an export star helper function + write("function " + exportStarFunction + "(m) {"); + increaseIndent(); + writeLine(); + write("var exports = {};"); + writeLine(); + write("for(var n in m) {"); + increaseIndent(); + writeLine(); + write("if (n !== \"default\""); + if (localNames) { + write("&& !" + localNames + ".hasOwnProperty(n)"); + } + write(") exports[n] = m[n];"); + decreaseIndent(); + writeLine(); + write("}"); + writeLine(); + write(exportFunctionForFile + "(exports);"); + decreaseIndent(); + writeLine(); + write("}"); + return exportStarFunction; + } + function writeExportedName(node) { + // do not record default exports + // they are local to module and never overwritten (explicitly skipped) by star export + if (node.kind !== 69 /* Identifier */ && node.flags & 1024 /* Default */) { + return; + } + if (started) { + write(","); + } + else { + started = true; + } + writeLine(); + write("'"); + if (node.kind === 69 /* Identifier */) { + emitNodeWithCommentsAndWithoutSourcemap(node); + } + else { + emitDeclarationName(node); + } + write("': true"); + } + } + function processTopLevelVariableAndFunctionDeclarations(node) { + // per ES6 spec: + // 15.2.1.16.4 ModuleDeclarationInstantiation() Concrete Method + // - var declarations are initialized to undefined - 14.a.ii + // - function/generator declarations are instantiated - 16.a.iv + // this means that after module is instantiated but before its evaluation + // exported functions are already accessible at import sites + // in theory we should hoist only exported functions and its dependencies + // in practice to simplify things we'll hoist all source level functions and variable declaration + // including variables declarations for module and class declarations + var hoistedVars; + var hoistedFunctionDeclarations; + var exportedDeclarations; + visit(node); + if (hoistedVars) { + writeLine(); + write("var "); + var seen = {}; + for (var i = 0; i < hoistedVars.length; ++i) { + var local = hoistedVars[i]; + var name_26 = local.kind === 69 /* Identifier */ + ? local + : local.name; + if (name_26) { + // do not emit duplicate entries (in case of declaration merging) in the list of hoisted variables + var text = ts.unescapeIdentifier(name_26.text); + if (ts.hasProperty(seen, text)) { + continue; + } + else { + seen[text] = text; + } + } + if (i !== 0) { + write(", "); + } + if (local.kind === 214 /* ClassDeclaration */ || local.kind === 218 /* ModuleDeclaration */ || local.kind === 217 /* EnumDeclaration */) { + emitDeclarationName(local); + } + else { + emit(local); + } + var flags = ts.getCombinedNodeFlags(local.kind === 69 /* Identifier */ ? local.parent : local); + if (flags & 1 /* Export */) { + if (!exportedDeclarations) { + exportedDeclarations = []; + } + exportedDeclarations.push(local); + } + } + write(";"); + } + if (hoistedFunctionDeclarations) { + for (var _a = 0; _a < hoistedFunctionDeclarations.length; _a++) { + var f = hoistedFunctionDeclarations[_a]; + writeLine(); + emit(f); + if (f.flags & 1 /* Export */) { + if (!exportedDeclarations) { + exportedDeclarations = []; + } + exportedDeclarations.push(f); + } + } + } + return exportedDeclarations; + function visit(node) { + if (node.flags & 2 /* Ambient */) { + return; + } + if (node.kind === 213 /* FunctionDeclaration */) { + if (!hoistedFunctionDeclarations) { + hoistedFunctionDeclarations = []; + } + hoistedFunctionDeclarations.push(node); + return; + } + if (node.kind === 214 /* ClassDeclaration */) { + if (!hoistedVars) { + hoistedVars = []; + } + hoistedVars.push(node); + return; + } + if (node.kind === 217 /* EnumDeclaration */) { + if (shouldEmitEnumDeclaration(node)) { + if (!hoistedVars) { + hoistedVars = []; + } + hoistedVars.push(node); + } + return; + } + if (node.kind === 218 /* ModuleDeclaration */) { + if (shouldEmitModuleDeclaration(node)) { + if (!hoistedVars) { + hoistedVars = []; + } + hoistedVars.push(node); + } + return; + } + if (node.kind === 211 /* VariableDeclaration */ || node.kind === 163 /* BindingElement */) { + if (shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ false)) { + var name_27 = node.name; + if (name_27.kind === 69 /* Identifier */) { + if (!hoistedVars) { + hoistedVars = []; + } + hoistedVars.push(name_27); + } + else { + ts.forEachChild(name_27, visit); + } + } + return; + } + if (ts.isInternalModuleImportEqualsDeclaration(node) && resolver.isValueAliasDeclaration(node)) { + if (!hoistedVars) { + hoistedVars = []; + } + hoistedVars.push(node.name); + return; + } + if (ts.isBindingPattern(node)) { + ts.forEach(node.elements, visit); + return; + } + if (!ts.isDeclaration(node)) { + ts.forEachChild(node, visit); + } + } + } + function shouldHoistVariable(node, checkIfSourceFileLevelDecl) { + if (checkIfSourceFileLevelDecl && !shouldHoistDeclarationInSystemJsModule(node)) { + return false; + } + // hoist variable if + // - it is not block scoped + // - it is top level block scoped + // if block scoped variables are nested in some another block then + // no other functions can use them except ones that are defined at least in the same block + return (ts.getCombinedNodeFlags(node) & 49152 /* BlockScoped */) === 0 || + ts.getEnclosingBlockScopeContainer(node).kind === 248 /* SourceFile */; + } + function isCurrentFileSystemExternalModule() { + return modulekind === 4 /* System */ && ts.isExternalModule(currentSourceFile); + } + function emitSystemModuleBody(node, dependencyGroups, startIndex) { + // shape of the body in system modules: + // function (exports) { + // + // + // + // return { + // setters: [ + // + // ], + // execute: function() { + // + // } + // } + // + // } + // I.e: + // import {x} from 'file1' + // var y = 1; + // export function foo() { return y + x(); } + // console.log(y); + // will be transformed to + // function(exports) { + // var file1; // local alias + // var y; + // function foo() { return y + file1.x(); } + // exports("foo", foo); + // return { + // setters: [ + // function(v) { file1 = v } + // ], + // execute(): function() { + // y = 1; + // console.log(y); + // } + // }; + // } + emitVariableDeclarationsForImports(); + writeLine(); + var exportedDeclarations = processTopLevelVariableAndFunctionDeclarations(node); + var exportStarFunction = emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations); + writeLine(); + write("return {"); + increaseIndent(); + writeLine(); + emitSetters(exportStarFunction, dependencyGroups); + writeLine(); + emitExecute(node, startIndex); + decreaseIndent(); + writeLine(); + write("}"); // return + emitTempDeclarations(/*newLine*/ true); + } + function emitSetters(exportStarFunction, dependencyGroups) { + write("setters:["); + for (var i = 0; i < dependencyGroups.length; ++i) { + if (i !== 0) { + write(","); + } + writeLine(); + increaseIndent(); + var group = dependencyGroups[i]; + // derive a unique name for parameter from the first named entry in the group + var parameterName = makeUniqueName(ts.forEach(group, getLocalNameForExternalImport) || ""); + write("function (" + parameterName + ") {"); + increaseIndent(); + for (var _a = 0; _a < group.length; _a++) { + var entry = group[_a]; + var importVariableName = getLocalNameForExternalImport(entry) || ""; + switch (entry.kind) { + case 222 /* ImportDeclaration */: + if (!entry.importClause) { + // 'import "..."' case + // module is imported only for side-effects, no emit required + break; + } + // fall-through + case 221 /* ImportEqualsDeclaration */: + ts.Debug.assert(importVariableName !== ""); + writeLine(); + // save import into the local + write(importVariableName + " = " + parameterName + ";"); + writeLine(); + break; + case 228 /* ExportDeclaration */: + ts.Debug.assert(importVariableName !== ""); + if (entry.exportClause) { + // export {a, b as c} from 'foo' + // emit as: + // exports_({ + // "a": _["a"], + // "c": _["b"] + // }); + writeLine(); + write(exportFunctionForFile + "({"); + writeLine(); + increaseIndent(); + for (var i_2 = 0, len = entry.exportClause.elements.length; i_2 < len; ++i_2) { + if (i_2 !== 0) { + write(","); + writeLine(); + } + var e = entry.exportClause.elements[i_2]; + write("\""); + emitNodeWithCommentsAndWithoutSourcemap(e.name); + write("\": " + parameterName + "[\""); + emitNodeWithCommentsAndWithoutSourcemap(e.propertyName || e.name); + write("\"]"); + } + decreaseIndent(); + writeLine(); + write("});"); + } + else { + writeLine(); + // export * from 'foo' + // emit as: + // exportStar(_foo); + write(exportStarFunction + "(" + parameterName + ");"); + } + writeLine(); + break; + } + } + decreaseIndent(); + write("}"); + decreaseIndent(); + } + write("],"); + } + function emitExecute(node, startIndex) { + write("execute: function() {"); + increaseIndent(); + writeLine(); + for (var i = startIndex; i < node.statements.length; ++i) { + var statement = node.statements[i]; + switch (statement.kind) { + // - function declarations are not emitted because they were already hoisted + // - import declarations are not emitted since they are already handled in setters + // - export declarations with module specifiers are not emitted since they were already written in setters + // - export declarations without module specifiers are emitted preserving the order + case 213 /* FunctionDeclaration */: + case 222 /* ImportDeclaration */: + continue; + case 228 /* ExportDeclaration */: + if (!statement.moduleSpecifier) { + for (var _a = 0, _b = statement.exportClause.elements; _a < _b.length; _a++) { + var element = _b[_a]; + // write call to exporter function for every export specifier in exports list + emitExportSpecifierInSystemModule(element); + } + } + continue; + case 221 /* ImportEqualsDeclaration */: + if (!ts.isInternalModuleImportEqualsDeclaration(statement)) { + // - import equals declarations that import external modules are not emitted + continue; + } + // fall-though for import declarations that import internal modules + default: + writeLine(); + emit(statement); + } + } + decreaseIndent(); + writeLine(); + write("}"); // execute + } + function emitSystemModule(node) { + collectExternalModuleInfo(node); + // System modules has the following shape + // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) + // 'exports' here is a function 'exports(name: string, value: T): T' that is used to publish exported values. + // 'exports' returns its 'value' argument so in most cases expressions + // that mutate exported values can be rewritten as: + // expr -> exports('name', expr). + // The only exception in this rule is postfix unary operators, + // see comment to 'emitPostfixUnaryExpression' for more details + ts.Debug.assert(!exportFunctionForFile); + // make sure that name of 'exports' function does not conflict with existing identifiers + exportFunctionForFile = makeUniqueName("exports"); + writeLine(); + write("System.register("); + if (node.moduleName) { + write("\"" + node.moduleName + "\", "); + } + write("["); + var groupIndices = {}; + var dependencyGroups = []; + for (var i = 0; i < externalImports.length; ++i) { + var text = getExternalModuleNameText(externalImports[i]); + if (ts.hasProperty(groupIndices, text)) { + // deduplicate/group entries in dependency list by the dependency name + var groupIndex = groupIndices[text]; + dependencyGroups[groupIndex].push(externalImports[i]); + continue; + } + else { + groupIndices[text] = dependencyGroups.length; + dependencyGroups.push([externalImports[i]]); + } + if (i !== 0) { + write(", "); + } + write(text); + } + write("], function(" + exportFunctionForFile + ") {"); + writeLine(); + increaseIndent(); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + emitEmitHelpers(node); + emitCaptureThisForNodeIfNecessary(node); + emitSystemModuleBody(node, dependencyGroups, startIndex); + decreaseIndent(); + writeLine(); + write("});"); + } + function getAMDDependencyNames(node, includeNonAmdDependencies) { + // names of modules with corresponding parameter in the factory function + var aliasedModuleNames = []; + // names of modules with no corresponding parameters in factory function + var unaliasedModuleNames = []; + var importAliasNames = []; // names of the parameters in the factory function; these + // parameters need to match the indexes of the corresponding + // module names in aliasedModuleNames. + // Fill in amd-dependency tags + for (var _a = 0, _b = node.amdDependencies; _a < _b.length; _a++) { + var amdDependency = _b[_a]; + if (amdDependency.name) { + aliasedModuleNames.push("\"" + amdDependency.path + "\""); + importAliasNames.push(amdDependency.name); + } + else { + unaliasedModuleNames.push("\"" + amdDependency.path + "\""); + } + } + for (var _c = 0; _c < externalImports.length; _c++) { + var importNode = externalImports[_c]; + // Find the name of the external module + var externalModuleName = getExternalModuleNameText(importNode); + // Find the name of the module alias, if there is one + var importAliasName = getLocalNameForExternalImport(importNode); + if (includeNonAmdDependencies && importAliasName) { + aliasedModuleNames.push(externalModuleName); + importAliasNames.push(importAliasName); + } + else { + unaliasedModuleNames.push(externalModuleName); + } + } + return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; + } + function emitAMDDependencies(node, includeNonAmdDependencies) { + // An AMD define function has the following shape: + // define(id?, dependencies?, factory); + // + // This has the shape of + // define(name, ["module1", "module2"], function (module1Alias) { + // The location of the alias in the parameter list in the factory function needs to + // match the position of the module name in the dependency list. + // + // To ensure this is true in cases of modules with no aliases, e.g.: + // `import "module"` or `` + // we need to add modules without alias names to the end of the dependencies list + var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies); + emitAMDDependencyList(dependencyNames); + write(", "); + emitAMDFactoryHeader(dependencyNames); + } + function emitAMDDependencyList(_a) { + var aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames; + write("[\"require\", \"exports\""); + if (aliasedModuleNames.length) { + write(", "); + write(aliasedModuleNames.join(", ")); + } + if (unaliasedModuleNames.length) { + write(", "); + write(unaliasedModuleNames.join(", ")); + } + write("]"); + } + function emitAMDFactoryHeader(_a) { + var importAliasNames = _a.importAliasNames; + write("function (require, exports"); + if (importAliasNames.length) { + write(", "); + write(importAliasNames.join(", ")); + } + write(") {"); + } + function emitAMDModule(node) { + emitEmitHelpers(node); + collectExternalModuleInfo(node); + writeLine(); + write("define("); + if (node.moduleName) { + write("\"" + node.moduleName + "\", "); + } + emitAMDDependencies(node, /*includeNonAmdDependencies*/ true); + increaseIndent(); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + emitExportStarHelper(); + emitCaptureThisForNodeIfNecessary(node); + emitLinesStartingAt(node.statements, startIndex); + emitTempDeclarations(/*newLine*/ true); + emitExportEquals(/*emitAsReturn*/ true); + decreaseIndent(); + writeLine(); + write("});"); + } + function emitCommonJSModule(node) { + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); + emitEmitHelpers(node); + collectExternalModuleInfo(node); + emitExportStarHelper(); + emitCaptureThisForNodeIfNecessary(node); + emitLinesStartingAt(node.statements, startIndex); + emitTempDeclarations(/*newLine*/ true); + emitExportEquals(/*emitAsReturn*/ false); + } + function emitUMDModule(node) { + emitEmitHelpers(node); + collectExternalModuleInfo(node); + var dependencyNames = getAMDDependencyNames(node, /*includeNonAmdDependencies*/ false); + // Module is detected first to support Browserify users that load into a browser with an AMD loader + writeLines("(function (factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define("); + emitAMDDependencyList(dependencyNames); + write(", factory);"); + writeLines(" }\n})("); + emitAMDFactoryHeader(dependencyNames); + increaseIndent(); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + emitExportStarHelper(); + emitCaptureThisForNodeIfNecessary(node); + emitLinesStartingAt(node.statements, startIndex); + emitTempDeclarations(/*newLine*/ true); + emitExportEquals(/*emitAsReturn*/ true); + decreaseIndent(); + writeLine(); + write("});"); + } + function emitES6Module(node) { + externalImports = undefined; + exportSpecifiers = undefined; + exportEquals = undefined; + hasExportStars = false; + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); + emitEmitHelpers(node); + emitCaptureThisForNodeIfNecessary(node); + emitLinesStartingAt(node.statements, startIndex); + emitTempDeclarations(/*newLine*/ true); + // Emit exportDefault if it exists will happen as part + // or normal statement emit. + } + function emitExportEquals(emitAsReturn) { + if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { + writeLine(); + emitStart(exportEquals); + write(emitAsReturn ? "return " : "module.exports = "); + emit(exportEquals.expression); + write(";"); + emitEnd(exportEquals); + } + } + function emitJsxElement(node) { + switch (compilerOptions.jsx) { + case 2 /* React */: + jsxEmitReact(node); + break; + case 1 /* Preserve */: + // Fall back to preserve if None was specified (we'll error earlier) + default: + jsxEmitPreserve(node); + break; + } + } + function trimReactWhitespaceAndApplyEntities(node) { + var result = undefined; + var text = ts.getTextOfNode(node, /*includeTrivia*/ true); + var firstNonWhitespace = 0; + var lastNonWhitespace = -1; + // JSX trims whitespace at the end and beginning of lines, except that the + // start/end of a tag is considered a start/end of a line only if that line is + // on the same line as the closing tag. See examples in tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx + for (var i = 0; i < text.length; i++) { + var c = text.charCodeAt(i); + if (ts.isLineBreak(c)) { + if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) { + var part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1); + result = (result ? result + "\" + ' ' + \"" : "") + ts.escapeString(part); + } + firstNonWhitespace = -1; + } + else if (!ts.isWhiteSpace(c)) { + lastNonWhitespace = i; + if (firstNonWhitespace === -1) { + firstNonWhitespace = i; + } + } + } + if (firstNonWhitespace !== -1) { + var part = text.substr(firstNonWhitespace); + result = (result ? result + "\" + ' ' + \"" : "") + ts.escapeString(part); + } + if (result) { + // Replace entities like   + result = result.replace(/&(\w+);/g, function (s, m) { + if (entities[m] !== undefined) { + return String.fromCharCode(entities[m]); + } + else { + return s; + } + }); + } + return result; + } + function getTextToEmit(node) { + switch (compilerOptions.jsx) { + case 2 /* React */: + var text = trimReactWhitespaceAndApplyEntities(node); + if (text === undefined || text.length === 0) { + return undefined; + } + else { + return text; + } + case 1 /* Preserve */: + default: + return ts.getTextOfNode(node, /*includeTrivia*/ true); + } + } + function emitJsxText(node) { + switch (compilerOptions.jsx) { + case 2 /* React */: + write("\""); + write(trimReactWhitespaceAndApplyEntities(node)); + write("\""); + break; + case 1 /* Preserve */: + default: + writer.writeLiteral(ts.getTextOfNode(node, /*includeTrivia*/ true)); + break; + } + } + function emitJsxExpression(node) { + if (node.expression) { + switch (compilerOptions.jsx) { + case 1 /* Preserve */: + default: + write("{"); + emit(node.expression); + write("}"); + break; + case 2 /* React */: + emit(node.expression); + break; + } + } + } + function emitDirectivePrologues(statements, startWithNewLine) { + for (var i = 0; i < statements.length; ++i) { + if (ts.isPrologueDirective(statements[i])) { + if (startWithNewLine || i > 0) { + writeLine(); + } + emit(statements[i]); + } + else { + // return index of the first non prologue directive + return i; + } + } + return statements.length; + } + function writeLines(text) { + var lines = text.split(/\r\n|\r|\n/g); + for (var i = 0; i < lines.length; ++i) { + var line = lines[i]; + if (line.length) { + writeLine(); + write(line); + } + } + } + function emitEmitHelpers(node) { + // Only emit helpers if the user did not say otherwise. + if (!compilerOptions.noEmitHelpers) { + // Only Emit __extends function when target ES5. + // For target ES6 and above, we can emit classDeclaration as is. + if ((languageVersion < 2 /* ES6 */) && (!extendsEmitted && resolver.getNodeCheckFlags(node) & 8 /* EmitExtends */)) { + writeLines(extendsHelper); + extendsEmitted = true; + } + if (!decorateEmitted && resolver.getNodeCheckFlags(node) & 16 /* EmitDecorate */) { + writeLines(decorateHelper); + if (compilerOptions.emitDecoratorMetadata) { + writeLines(metadataHelper); + } + decorateEmitted = true; + } + if (!paramEmitted && resolver.getNodeCheckFlags(node) & 32 /* EmitParam */) { + writeLines(paramHelper); + paramEmitted = true; + } + if (!awaiterEmitted && resolver.getNodeCheckFlags(node) & 64 /* EmitAwaiter */) { + writeLines(awaiterHelper); + awaiterEmitted = true; + } + } + } + function emitSourceFileNode(node) { + // Start new file on new line + writeLine(); + emitShebang(); + emitDetachedComments(node); + if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { + var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1 /* CommonJS */]; + emitModule(node); + } + else { + // emit prologue directives prior to __extends + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); + externalImports = undefined; + exportSpecifiers = undefined; + exportEquals = undefined; + hasExportStars = false; + emitEmitHelpers(node); + emitCaptureThisForNodeIfNecessary(node); + emitLinesStartingAt(node.statements, startIndex); + emitTempDeclarations(/*newLine*/ true); + } + emitLeadingComments(node.endOfFileToken); + } + function emitNodeWithCommentsAndWithoutSourcemap(node) { + emitNodeConsideringCommentsOption(node, emitNodeWithoutSourceMap); + } + function emitNodeConsideringCommentsOption(node, emitNodeConsideringSourcemap) { + if (node) { + if (node.flags & 2 /* Ambient */) { + return emitCommentsOnNotEmittedNode(node); + } + if (isSpecializedCommentHandling(node)) { + // This is the node that will handle its own comments and sourcemap + return emitNodeWithoutSourceMap(node); + } + var emitComments_1 = shouldEmitLeadingAndTrailingComments(node); + if (emitComments_1) { + emitLeadingComments(node); + } + emitNodeConsideringSourcemap(node); + if (emitComments_1) { + emitTrailingComments(node); + } + } + } + function emitNodeWithoutSourceMap(node) { + if (node) { + emitJavaScriptWorker(node); + } + } + function isSpecializedCommentHandling(node) { + switch (node.kind) { + // All of these entities are emitted in a specialized fashion. As such, we allow + // the specialized methods for each to handle the comments on the nodes. + case 215 /* InterfaceDeclaration */: + case 213 /* FunctionDeclaration */: + case 222 /* ImportDeclaration */: + case 221 /* ImportEqualsDeclaration */: + case 216 /* TypeAliasDeclaration */: + case 227 /* ExportAssignment */: + return true; + } + } + function shouldEmitLeadingAndTrailingComments(node) { + switch (node.kind) { + case 193 /* VariableStatement */: + return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node); + case 218 /* ModuleDeclaration */: + // Only emit the leading/trailing comments for a module if we're actually + // emitting the module as well. + return shouldEmitModuleDeclaration(node); + case 217 /* EnumDeclaration */: + // Only emit the leading/trailing comments for an enum if we're actually + // emitting the module as well. + return shouldEmitEnumDeclaration(node); + } + // If the node is emitted in specialized fashion, dont emit comments as this node will handle + // emitting comments when emitting itself + ts.Debug.assert(!isSpecializedCommentHandling(node)); + // If this is the expression body of an arrow function that we're down-leveling, + // then we don't want to emit comments when we emit the body. It will have already + // been taken care of when we emitted the 'return' statement for the function + // expression body. + if (node.kind !== 192 /* Block */ && + node.parent && + node.parent.kind === 174 /* ArrowFunction */ && + node.parent.body === node && + compilerOptions.target <= 1 /* ES5 */) { + return false; + } + // Emit comments for everything else. + return true; + } + function emitJavaScriptWorker(node) { + // Check if the node can be emitted regardless of the ScriptTarget + switch (node.kind) { + case 69 /* Identifier */: + return emitIdentifier(node); + case 138 /* Parameter */: + return emitParameter(node); + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + return emitMethod(node); + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + return emitAccessor(node); + case 97 /* ThisKeyword */: + return emitThis(node); + case 95 /* SuperKeyword */: + return emitSuper(node); + case 93 /* NullKeyword */: + return write("null"); + case 99 /* TrueKeyword */: + return write("true"); + case 84 /* FalseKeyword */: + return write("false"); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 10 /* RegularExpressionLiteral */: + case 11 /* NoSubstitutionTemplateLiteral */: + case 12 /* TemplateHead */: + case 13 /* TemplateMiddle */: + case 14 /* TemplateTail */: + return emitLiteral(node); + case 183 /* TemplateExpression */: + return emitTemplateExpression(node); + case 190 /* TemplateSpan */: + return emitTemplateSpan(node); + case 233 /* JsxElement */: + case 234 /* JsxSelfClosingElement */: + return emitJsxElement(node); + case 236 /* JsxText */: + return emitJsxText(node); + case 240 /* JsxExpression */: + return emitJsxExpression(node); + case 135 /* QualifiedName */: + return emitQualifiedName(node); + case 161 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 162 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 163 /* BindingElement */: + return emitBindingElement(node); + case 164 /* ArrayLiteralExpression */: + return emitArrayLiteral(node); + case 165 /* ObjectLiteralExpression */: + return emitObjectLiteral(node); + case 245 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 246 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 136 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + case 166 /* PropertyAccessExpression */: + return emitPropertyAccess(node); + case 167 /* ElementAccessExpression */: + return emitIndexedAccess(node); + case 168 /* CallExpression */: + return emitCallExpression(node); + case 169 /* NewExpression */: + return emitNewExpression(node); + case 170 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 171 /* TypeAssertionExpression */: + return emit(node.expression); + case 189 /* AsExpression */: + return emit(node.expression); + case 172 /* ParenthesizedExpression */: + return emitParenExpression(node); + case 213 /* FunctionDeclaration */: + case 173 /* FunctionExpression */: + case 174 /* ArrowFunction */: + return emitFunctionDeclaration(node); + case 175 /* DeleteExpression */: + return emitDeleteExpression(node); + case 176 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 177 /* VoidExpression */: + return emitVoidExpression(node); + case 178 /* AwaitExpression */: + return emitAwaitExpression(node); + case 179 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 180 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 181 /* BinaryExpression */: + return emitBinaryExpression(node); + case 182 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 185 /* SpreadElementExpression */: + return emitSpreadElementExpression(node); + case 184 /* YieldExpression */: + return emitYieldExpression(node); + case 187 /* OmittedExpression */: + return; + case 192 /* Block */: + case 219 /* ModuleBlock */: + return emitBlock(node); + case 193 /* VariableStatement */: + return emitVariableStatement(node); + case 194 /* EmptyStatement */: + return write(";"); + case 195 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 196 /* IfStatement */: + return emitIfStatement(node); + case 197 /* DoStatement */: + return emitDoStatement(node); + case 198 /* WhileStatement */: + return emitWhileStatement(node); + case 199 /* ForStatement */: + return emitForStatement(node); + case 201 /* ForOfStatement */: + case 200 /* ForInStatement */: + return emitForInOrForOfStatement(node); + case 202 /* ContinueStatement */: + case 203 /* BreakStatement */: + return emitBreakOrContinueStatement(node); + case 204 /* ReturnStatement */: + return emitReturnStatement(node); + case 205 /* WithStatement */: + return emitWithStatement(node); + case 206 /* SwitchStatement */: + return emitSwitchStatement(node); + case 241 /* CaseClause */: + case 242 /* DefaultClause */: + return emitCaseOrDefaultClause(node); + case 207 /* LabeledStatement */: + return emitLabelledStatement(node); + case 208 /* ThrowStatement */: + return emitThrowStatement(node); + case 209 /* TryStatement */: + return emitTryStatement(node); + case 244 /* CatchClause */: + return emitCatchClause(node); + case 210 /* DebuggerStatement */: + return emitDebuggerStatement(node); + case 211 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 186 /* ClassExpression */: + return emitClassExpression(node); + case 214 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 215 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 217 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 247 /* EnumMember */: + return emitEnumMember(node); + case 218 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 222 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 221 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 228 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 227 /* ExportAssignment */: + return emitExportAssignment(node); + case 248 /* SourceFile */: + return emitSourceFileNode(node); + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; + } + function getLeadingCommentsWithoutDetachedComments() { + // get the leading comments from detachedPos + var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + return leadingComments; + } + function isPinnedComments(comment) { + return currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && + currentSourceFile.text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; + } + /** + * Determine if the given comment is a triple-slash + * + * @return true if the comment is a triple-slash comment else false + **/ + function isTripleSlashComment(comment) { + // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text + // so that we don't end up computing comment string and doing match for all // comments + if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 47 /* slash */ && + comment.pos + 2 < comment.end && + currentSourceFile.text.charCodeAt(comment.pos + 2) === 47 /* slash */) { + var textSubStr = currentSourceFile.text.substring(comment.pos, comment.end); + return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || + textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? + true : false; + } + return false; + } + function getLeadingCommentsToEmit(node) { + // Emit the leading comments only if the parent's pos doesn't match because parent should take care of emitting these comments + if (node.parent) { + if (node.parent.kind === 248 /* SourceFile */ || node.pos !== node.parent.pos) { + if (hasDetachedComments(node.pos)) { + // get comments without detached comments + return getLeadingCommentsWithoutDetachedComments(); + } + else { + // get the leading comments from the node + return ts.getLeadingCommentRangesOfNode(node, currentSourceFile); + } + } + } + } + function getTrailingCommentsToEmit(node) { + // Emit the trailing comments only if the parent's pos doesn't match because parent should take care of emitting these comments + if (node.parent) { + if (node.parent.kind === 248 /* SourceFile */ || node.end !== node.parent.end) { + return ts.getTrailingCommentRanges(currentSourceFile.text, node.end); + } + } + } + /** + * Emit comments associated with node that will not be emitted into JS file + */ + function emitCommentsOnNotEmittedNode(node) { + emitLeadingCommentsWorker(node, /*isEmittedNode:*/ false); + } + function emitLeadingComments(node) { + return emitLeadingCommentsWorker(node, /*isEmittedNode:*/ true); + } + function emitLeadingCommentsWorker(node, isEmittedNode) { + if (compilerOptions.removeComments) { + return; + } + var leadingComments; + if (isEmittedNode) { + leadingComments = getLeadingCommentsToEmit(node); + } + else { + // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node, + // unless it is a triple slash comment at the top of the file. + // For Example: + // /// + // declare var x; + // /// + // interface F {} + // The first /// will NOT be removed while the second one will be removed eventhough both node will not be emitted + if (node.pos === 0) { + leadingComments = ts.filter(getLeadingCommentsToEmit(node), isTripleSlashComment); + } + } + ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); + // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space + ts.emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator:*/ true, newLine, writeComment); + } + function emitTrailingComments(node) { + if (compilerOptions.removeComments) { + return; + } + // Emit the trailing comments only if the parent's end doesn't match + var trailingComments = getTrailingCommentsToEmit(node); + // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ + ts.emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment); + } + /** + * Emit trailing comments at the position. The term trailing comment is used here to describe following comment: + * x, /comment1/ y + * ^ => pos; the function will emit "comment1" in the emitJS + */ + function emitTrailingCommentsOfPosition(pos) { + if (compilerOptions.removeComments) { + return; + } + var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, pos); + // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ + ts.emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment); + } + function emitLeadingCommentsOfPositionWorker(pos) { + if (compilerOptions.removeComments) { + return; + } + var leadingComments; + if (hasDetachedComments(pos)) { + // get comments without detached comments + leadingComments = getLeadingCommentsWithoutDetachedComments(); + } + else { + // get the leading comments from the node + leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, pos); + } + ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments); + // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space + ts.emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment); + } + function emitDetachedComments(node) { + var leadingComments; + if (compilerOptions.removeComments) { + // removeComments is true, only reserve pinned comment at the top of file + // For example: + // /*! Pinned Comment */ + // + // var x = 10; + if (node.pos === 0) { + leadingComments = ts.filter(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComments); + } + } + else { + // removeComments is false, just get detached as normal and bypass the process to filter comment + leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); + } + if (leadingComments) { + var detachedComments = []; + var lastComment; + ts.forEach(leadingComments, function (comment) { + if (lastComment) { + var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, lastComment.end); + var commentLine = ts.getLineOfLocalPosition(currentSourceFile, comment.pos); + if (commentLine >= lastCommentLine + 2) { + // There was a blank line between the last comment and this comment. This + // comment is not part of the copyright comments. Return what we have so + // far. + return detachedComments; + } + } + detachedComments.push(comment); + lastComment = comment; + }); + if (detachedComments.length) { + // All comments look like they could have been part of the copyright header. Make + // sure there is at least one blank line between it and the node. If not, it's not + // a copyright header. + var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end); + var nodeLine = ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); + if (nodeLine >= lastCommentLine + 2) { + // Valid detachedComments + ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); + ts.emitComments(currentSourceFile, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment); + var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + } + } + function emitShebang() { + var shebang = ts.getShebang(currentSourceFile.text); + if (shebang) { + write(shebang); + } + } + var _a; + } + function emitFile(jsFilePath, sourceFile) { + emitJavaScript(jsFilePath, sourceFile); + if (compilerOptions.declaration) { + ts.writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics); + } + } + } + ts.emitFiles = emitFiles; +})(ts || (ts = {})); +/// +/// +/// +var ts; +(function (ts) { + /* @internal */ ts.programTime = 0; + /* @internal */ ts.emitTime = 0; + /* @internal */ ts.ioReadTime = 0; + /* @internal */ ts.ioWriteTime = 0; + /** The version of the TypeScript compiler release */ + var emptyArray = []; + ts.version = "1.7.5"; + function findConfigFile(searchPath) { + var fileName = "tsconfig.json"; + while (true) { + if (ts.sys.fileExists(fileName)) { + return fileName; + } + var parentPath = ts.getDirectoryPath(searchPath); + if (parentPath === searchPath) { + break; + } + searchPath = parentPath; + fileName = "../" + fileName; + } + return undefined; + } + ts.findConfigFile = findConfigFile; + function resolveTripleslashReference(moduleName, containingFile) { + var basePath = ts.getDirectoryPath(containingFile); + var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName); + return ts.normalizePath(referencedFileName); + } + ts.resolveTripleslashReference = resolveTripleslashReference; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var moduleResolution = compilerOptions.moduleResolution !== undefined + ? compilerOptions.moduleResolution + : compilerOptions.module === 1 /* CommonJS */ ? 2 /* NodeJs */ : 1 /* Classic */; + switch (moduleResolution) { + case 2 /* NodeJs */: return nodeModuleNameResolver(moduleName, containingFile, host); + case 1 /* Classic */: return classicNameResolver(moduleName, containingFile, compilerOptions, host); + } + } + ts.resolveModuleName = resolveModuleName; + function nodeModuleNameResolver(moduleName, containingFile, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + if (ts.getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) { + var failedLookupLocations = []; + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var resolvedFileName = loadNodeModuleFromFile(candidate, failedLookupLocations, host); + if (resolvedFileName) { + return { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations }; + } + resolvedFileName = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host); + return resolvedFileName + ? { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations } + : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + } + else { + return loadModuleFromNodeModules(moduleName, containingDirectory, host); + } + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function loadNodeModuleFromFile(candidate, failedLookupLocation, host) { + return ts.forEach(ts.moduleFileExtensions, tryLoad); + function tryLoad(ext) { + var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; + if (host.fileExists(fileName)) { + return fileName; + } + else { + failedLookupLocation.push(fileName); + return undefined; + } + } + } + function loadNodeModuleFromDirectory(candidate, failedLookupLocation, host) { + var packageJsonPath = ts.combinePaths(candidate, "package.json"); + if (host.fileExists(packageJsonPath)) { + var jsonContent; + try { + var jsonText = host.readFile(packageJsonPath); + jsonContent = jsonText ? JSON.parse(jsonText) : { typings: undefined }; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + jsonContent = { typings: undefined }; + } + if (jsonContent.typings) { + var result = loadNodeModuleFromFile(ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host); + if (result) { + return result; + } + } + } + else { + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results + failedLookupLocation.push(packageJsonPath); + } + return loadNodeModuleFromFile(ts.combinePaths(candidate, "index"), failedLookupLocation, host); + } + function loadModuleFromNodeModules(moduleName, directory, host) { + var failedLookupLocations = []; + directory = ts.normalizeSlashes(directory); + while (true) { + var baseName = ts.getBaseFileName(directory); + if (baseName !== "node_modules") { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + var result = loadNodeModuleFromFile(candidate, failedLookupLocations, host); + if (result) { + return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; + } + result = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host); + if (result) { + return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; + } + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + break; + } + directory = parentPath; + } + return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + } + function nameStartsWithDotSlashOrDotDotSlash(name) { + var i = name.lastIndexOf("./", 1); + return i === 0 || (i === 1 && name.charCodeAt(0) === 46 /* dot */); + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + // module names that contain '!' are used to reference resources and are not resolved to actual files on disk + if (moduleName.indexOf("!") != -1) { + return { resolvedModule: undefined, failedLookupLocations: [] }; + } + var searchPath = ts.getDirectoryPath(containingFile); + var searchName; + var failedLookupLocations = []; + var referencedSourceFile; + while (true) { + searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName)); + referencedSourceFile = ts.forEach(ts.supportedExtensions, function (extension) { + if (extension === ".tsx" && !compilerOptions.jsx) { + // resolve .tsx files only if jsx support is enabled + // 'logical not' handles both undefined and None cases + return undefined; + } + var candidate = searchName + extension; + if (host.fileExists(candidate)) { + return candidate; + } + else { + failedLookupLocations.push(candidate); + } + }); + if (referencedSourceFile) { + break; + } + var parentPath = ts.getDirectoryPath(searchPath); + if (parentPath === searchPath) { + break; + } + searchPath = parentPath; + } + return referencedSourceFile + ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } + : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + } + ts.classicNameResolver = classicNameResolver; + /* @internal */ + ts.defaultInitCompilerOptions = { + module: 1 /* CommonJS */, + target: 0 /* ES3 */, + noImplicitAny: false, + outDir: "built", + rootDir: ".", + sourceMap: false + }; + function createCompilerHost(options, setParentNodes) { + var currentDirectory; + var existingDirectories = {}; + function getCanonicalFileName(fileName) { + // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. + // otherwise use toLowerCase as a canonical form. + return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + } + // returned by CScript sys environment + var unsupportedFileEncodingErrorCode = -2147024809; + function getSourceFile(fileName, languageVersion, onError) { + var text; + try { + var start = new Date().getTime(); + text = ts.sys.readFile(fileName, options.charset); + ts.ioReadTime += new Date().getTime() - start; + } + catch (e) { + if (onError) { + onError(e.number === unsupportedFileEncodingErrorCode + ? ts.createCompilerDiagnostic(ts.Diagnostics.Unsupported_file_encoding).messageText + : e.message); + } + text = ""; + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; + } + function directoryExists(directoryPath) { + if (ts.hasProperty(existingDirectories, directoryPath)) { + return true; + } + if (ts.sys.directoryExists(directoryPath)) { + existingDirectories[directoryPath] = true; + return true; + } + return false; + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + ts.sys.createDirectory(directoryPath); + } + } + function writeFile(fileName, data, writeByteOrderMark, onError) { + try { + var start = new Date().getTime(); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + ts.sys.writeFile(fileName, data, writeByteOrderMark); + ts.ioWriteTime += new Date().getTime() - start; + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + var newLine = ts.getNewLineCharacter(options); + return { + getSourceFile: getSourceFile, + getDefaultLibFileName: function (options) { return ts.combinePaths(ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())), ts.getDefaultLibFileName(options)); }, + writeFile: writeFile, + getCurrentDirectory: function () { return currentDirectory || (currentDirectory = ts.sys.getCurrentDirectory()); }, + useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, + readFile: function (fileName) { return ts.sys.readFile(fileName); } + }; + } + ts.createCompilerHost = createCompilerHost; + function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (program.getCompilerOptions().declaration) { + diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + } + return ts.sortAndDeduplicateDiagnostics(diagnostics); + } + ts.getPreEmitDiagnostics = getPreEmitDiagnostics; + function flattenDiagnosticMessageText(messageText, newLine) { + if (typeof messageText === "string") { + return messageText; + } + else { + var diagnosticChain = messageText; + var result = ""; + var indent = 0; + while (diagnosticChain) { + if (indent) { + result += newLine; + for (var i = 0; i < indent; i++) { + result += " "; + } + } + result += diagnosticChain.messageText; + indent++; + diagnosticChain = diagnosticChain.next; + } + return result; + } + } + ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; + function createProgram(rootNames, options, host, oldProgram) { + var program; + var files = []; + var fileProcessingDiagnostics = ts.createDiagnosticCollection(); + var programDiagnostics = ts.createDiagnosticCollection(); + var commonSourceDirectory; + var diagnosticsProducingTypeChecker; + var noDiagnosticsTypeChecker; + var classifiableNames; + var skipDefaultLib = options.noLib; + var start = new Date().getTime(); + host = host || createCompilerHost(options); + var resolveModuleNamesWorker = host.resolveModuleNames + ? (function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }) + : (function (moduleNames, containingFile) { return ts.map(moduleNames, function (moduleName) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }); }); + var filesByName = ts.createFileMap(function (fileName) { return host.getCanonicalFileName(fileName); }); + if (oldProgram) { + // check properties that can affect structure of the program or module resolution strategy + // if any of these properties has changed - structure cannot be reused + var oldOptions = oldProgram.getCompilerOptions(); + if ((oldOptions.module !== options.module) || + (oldOptions.noResolve !== options.noResolve) || + (oldOptions.target !== options.target) || + (oldOptions.noLib !== options.noLib) || + (oldOptions.jsx !== options.jsx)) { + oldProgram = undefined; + } + } + if (!tryReuseStructureFromOldProgram()) { + ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); + // Do not process the default library if: + // - The '--noLib' flag is used. + // - A 'no-default-lib' reference comment is encountered in + // processing the root files. + if (!skipDefaultLib) { + processRootFile(host.getDefaultLibFileName(options), true); + } + } + verifyCompilerOptions(); + // unconditionally set oldProgram to undefined to prevent it from being captured in closure + oldProgram = undefined; + ts.programTime += new Date().getTime() - start; + program = { + getRootFileNames: function () { return rootNames; }, + getSourceFile: getSourceFile, + getSourceFiles: function () { return files; }, + getCompilerOptions: function () { return options; }, + getSyntacticDiagnostics: getSyntacticDiagnostics, + getOptionsDiagnostics: getOptionsDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getSemanticDiagnostics: getSemanticDiagnostics, + getDeclarationDiagnostics: getDeclarationDiagnostics, + getTypeChecker: getTypeChecker, + getClassifiableNames: getClassifiableNames, + getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, + getCommonSourceDirectory: function () { return commonSourceDirectory; }, + emit: emit, + getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, + getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); }, + getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, + getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, + getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; } + }; + return program; + function getClassifiableNames() { + if (!classifiableNames) { + // Initialize a checker so that all our files are bound. + getTypeChecker(); + classifiableNames = {}; + for (var _i = 0; _i < files.length; _i++) { + var sourceFile = files[_i]; + ts.copyMap(sourceFile.classifiableNames, classifiableNames); + } + } + return classifiableNames; + } + function tryReuseStructureFromOldProgram() { + if (!oldProgram) { + return false; + } + ts.Debug.assert(!oldProgram.structureIsReused); + // there is an old program, check if we can reuse its structure + var oldRootNames = oldProgram.getRootFileNames(); + if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { + return false; + } + // check if program source files has changed in the way that can affect structure of the program + var newSourceFiles = []; + var modifiedSourceFiles = []; + for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { + var oldSourceFile = _a[_i]; + var newSourceFile = host.getSourceFile(oldSourceFile.fileName, options.target); + if (!newSourceFile) { + return false; + } + if (oldSourceFile !== newSourceFile) { + if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { + // value of no-default-lib has changed + // this will affect if default library is injected into the list of files + return false; + } + // check tripleslash references + if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { + // tripleslash references has changed + return false; + } + // check imports + collectExternalModuleReferences(newSourceFile); + if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { + // imports has changed + return false; + } + if (resolveModuleNamesWorker) { + var moduleNames = ts.map(newSourceFile.imports, function (name) { return name.text; }); + var resolutions = resolveModuleNamesWorker(moduleNames, newSourceFile.fileName); + // ensure that module resolution results are still correct + for (var i = 0; i < moduleNames.length; ++i) { + var newResolution = resolutions[i]; + var oldResolution = ts.getResolvedModule(oldSourceFile, moduleNames[i]); + var resolutionChanged = oldResolution + ? !newResolution || + oldResolution.resolvedFileName !== newResolution.resolvedFileName || + !!oldResolution.isExternalLibraryImport !== !!newResolution.isExternalLibraryImport + : newResolution; + if (resolutionChanged) { + return false; + } + } + } + // pass the cache of module resolutions from the old source file + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; + modifiedSourceFiles.push(newSourceFile); + } + else { + // file has no changes - use it as is + newSourceFile = oldSourceFile; + } + // if file has passed all checks it should be safe to reuse it + newSourceFiles.push(newSourceFile); + } + // update fileName -> file mapping + for (var _b = 0; _b < newSourceFiles.length; _b++) { + var file = newSourceFiles[_b]; + filesByName.set(file.fileName, file); + } + files = newSourceFiles; + fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); + for (var _c = 0; _c < modifiedSourceFiles.length; _c++) { + var modifiedFile = modifiedSourceFiles[_c]; + fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile); + } + oldProgram.structureIsReused = true; + return true; + } + function getEmitHost(writeFileCallback) { + return { + getCanonicalFileName: function (fileName) { return host.getCanonicalFileName(fileName); }, + getCommonSourceDirectory: program.getCommonSourceDirectory, + getCompilerOptions: program.getCompilerOptions, + getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + getNewLine: function () { return host.getNewLine(); }, + getSourceFile: program.getSourceFile, + getSourceFiles: program.getSourceFiles, + writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); }) + }; + } + function getDiagnosticsProducingTypeChecker() { + return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); + } + function getTypeChecker() { + return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); + } + function emit(sourceFile, writeFileCallback, cancellationToken) { + var _this = this; + return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); + } + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { + // If the noEmitOnError flag is set, then check if we have any errors so far. If so, + // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we + // get any preEmit diagnostics, not just the ones + if (options.noEmitOnError && getPreEmitDiagnostics(program, /*sourceFile:*/ undefined, cancellationToken).length > 0) { + return { diagnostics: [], sourceMaps: undefined, emitSkipped: true }; + } + // Create the emit resolver outside of the "emitTime" tracking code below. That way + // any cost associated with it (like type checking) are appropriate associated with + // the type-checking counter. + // + // If the -out option is specified, we should not pass the source file to getEmitResolver. + // This is because in the -out scenario all files need to be emitted, and therefore all + // files need to be type checked. And the way to specify that all files need to be type + // checked is to not pass the file to getEmitResolver. + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); + var start = new Date().getTime(); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + ts.emitTime += new Date().getTime() - start; + return emitResult; + } + function getSourceFile(fileName) { + // first try to use file name as is to find file + // then try to convert relative file name to absolute and use it to retrieve source file + return filesByName.get(fileName) || filesByName.get(ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory())); + } + function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { + if (sourceFile) { + return getDiagnostics(sourceFile, cancellationToken); + } + var allDiagnostics = []; + ts.forEach(program.getSourceFiles(), function (sourceFile) { + if (cancellationToken) { + cancellationToken.throwIfCancellationRequested(); + } + ts.addRange(allDiagnostics, getDiagnostics(sourceFile, cancellationToken)); + }); + return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + } + function getSyntacticDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); + } + function getSemanticDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken); + } + function getDeclarationDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); + } + function getSyntacticDiagnosticsForFile(sourceFile, cancellationToken) { + return sourceFile.parseDiagnostics; + } + function runWithCancellationToken(func) { + try { + return func(); + } + catch (e) { + if (e instanceof ts.OperationCanceledException) { + // We were canceled while performing the operation. Because our type checker + // might be a bad state, we need to throw it away. + // + // Note: we are overly agressive here. We do not actually *have* to throw away + // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep + // the lifetimes of these two TypeCheckers the same. Also, we generally only + // cancel when the user has made a change anyways. And, in that case, we (the + // program instance) will get thrown away anyways. So trying to keep one of + // these type checkers alive doesn't serve much purpose. + noDiagnosticsTypeChecker = undefined; + diagnosticsProducingTypeChecker = undefined; + } + throw e; + } + } + function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + var typeChecker = getDiagnosticsProducingTypeChecker(); + ts.Debug.assert(!!sourceFile.bindDiagnostics); + var bindDiagnostics = sourceFile.bindDiagnostics; + var checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken); + var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); + var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); + return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); + }); + } + function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + if (!ts.isDeclarationFile(sourceFile)) { + var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); + // Don't actually write any files since we're just getting diagnostics. + var writeFile_1 = function () { }; + return ts.getDeclarationDiagnostics(getEmitHost(writeFile_1), resolver, sourceFile); + } + }); + } + function getOptionsDiagnostics() { + var allDiagnostics = []; + ts.addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics()); + ts.addRange(allDiagnostics, programDiagnostics.getGlobalDiagnostics()); + return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + } + function getGlobalDiagnostics() { + var allDiagnostics = []; + ts.addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); + return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + } + function hasExtension(fileName) { + return ts.getBaseFileName(fileName).indexOf(".") >= 0; + } + function processRootFile(fileName, isDefaultLib) { + processSourceFile(ts.normalizePath(fileName), isDefaultLib); + } + function fileReferenceIsEqualTo(a, b) { + return a.fileName === b.fileName; + } + function moduleNameIsEqualTo(a, b) { + return a.text === b.text; + } + function collectExternalModuleReferences(file) { + if (file.imports) { + return; + } + var imports; + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var node = _a[_i]; + collect(node, /* allowRelativeModuleNames */ true); + } + file.imports = imports || emptyArray; + function collect(node, allowRelativeModuleNames) { + switch (node.kind) { + case 222 /* ImportDeclaration */: + case 221 /* ImportEqualsDeclaration */: + case 228 /* ExportDeclaration */: + var moduleNameExpr = ts.getExternalModuleName(node); + if (!moduleNameExpr || moduleNameExpr.kind !== 9 /* StringLiteral */) { + break; + } + if (!moduleNameExpr.text) { + break; + } + if (allowRelativeModuleNames || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) { + (imports || (imports = [])).push(moduleNameExpr); + } + break; + case 218 /* ModuleDeclaration */: + if (node.name.kind === 9 /* StringLiteral */ && (node.flags & 2 /* Ambient */ || ts.isDeclarationFile(file))) { + // TypeScript 1.0 spec (April 2014): 12.1.6 + // An AmbientExternalModuleDeclaration declares an external module. + // This type of declaration is permitted only in the global module. + // The StringLiteral must specify a top - level external module name. + // Relative external module names are not permitted + ts.forEachChild(node.body, function (node) { + // TypeScript 1.0 spec (April 2014): 12.1.6 + // An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules + // only through top - level external module names. Relative external module names are not permitted. + collect(node, /* allowRelativeModuleNames */ false); + }); + } + break; + } + } + } + function processSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { + var diagnosticArgument; + var diagnostic; + if (hasExtension(fileName)) { + if (!options.allowNonTsExtensions && !ts.forEach(ts.supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; + diagnosticArgument = [fileName, "'" + ts.supportedExtensions.join("', '") + "'"]; + } + else if (!findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd)) { + diagnostic = ts.Diagnostics.File_0_not_found; + diagnosticArgument = [fileName]; + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; + diagnosticArgument = [fileName]; + } + } + else { + var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd); + if (!nonTsFile) { + if (options.allowNonTsExtensions) { + diagnostic = ts.Diagnostics.File_0_not_found; + diagnosticArgument = [fileName]; + } + else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, isDefaultLib, refFile, refPos, refEnd); })) { + diagnostic = ts.Diagnostics.File_0_not_found; + fileName += ".ts"; + diagnosticArgument = [fileName]; + } + } + } + if (diagnostic) { + if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) { + fileProcessingDiagnostics.add(ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(diagnosticArgument))); + } + else { + fileProcessingDiagnostics.add(ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(diagnosticArgument))); + } + } + } + // Get source file from normalized fileName + function findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd) { + if (filesByName.contains(fileName)) { + // We've already looked for this file, use cached result + return getSourceFileFromCache(fileName, /*useAbsolutePath*/ false); + } + var normalizedAbsolutePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); + if (filesByName.contains(normalizedAbsolutePath)) { + var file_1 = getSourceFileFromCache(normalizedAbsolutePath, /*useAbsolutePath*/ true); + // we don't have resolution for this relative file name but the match was found by absolute file name + // store resolution for relative name as well + filesByName.set(fileName, file_1); + return file_1; + } + // We haven't looked for this file, do so now and cache result + var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { + if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { + fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); + } + else { + fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); + } + }); + filesByName.set(fileName, file); + if (file) { + skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; + // Set the source file for normalized absolute path + filesByName.set(normalizedAbsolutePath, file); + var basePath = ts.getDirectoryPath(fileName); + if (!options.noResolve) { + processReferencedFiles(file, basePath); + } + // always process imported modules to record module name resolutions + processImportedModules(file, basePath); + if (isDefaultLib) { + file.isDefaultLib = true; + files.unshift(file); + } + else { + files.push(file); + } + } + return file; + function getSourceFileFromCache(fileName, useAbsolutePath) { + var file = filesByName.get(fileName); + if (file && host.useCaseSensitiveFileNames()) { + var sourceFileName = useAbsolutePath ? ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()) : file.fileName; + if (ts.normalizeSlashes(fileName) !== ts.normalizeSlashes(sourceFileName)) { + if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { + fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, sourceFileName)); + } + else { + fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, sourceFileName)); + } + } + } + return file; + } + } + function processReferencedFiles(file, basePath) { + ts.forEach(file.referencedFiles, function (ref) { + var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + processSourceFile(referencedFileName, /* isDefaultLib */ false, file, ref.pos, ref.end); + }); + } + function processImportedModules(file, basePath) { + collectExternalModuleReferences(file); + if (file.imports.length) { + file.resolvedModules = {}; + var moduleNames = ts.map(file.imports, function (name) { return name.text; }); + var resolutions = resolveModuleNamesWorker(moduleNames, file.fileName); + for (var i = 0; i < file.imports.length; ++i) { + var resolution = resolutions[i]; + ts.setResolvedModule(file, moduleNames[i], resolution); + if (resolution && !options.noResolve) { + var importedFile = findModuleSourceFile(resolution.resolvedFileName, file.imports[i]); + if (importedFile && resolution.isExternalLibraryImport) { + if (!ts.isExternalModule(importedFile)) { + var start_2 = ts.getTokenPosOfNode(file.imports[i], file); + fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_2, file.imports[i].end - start_2, ts.Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); + } + else if (importedFile.referencedFiles.length) { + var firstRef = importedFile.referencedFiles[0]; + fileProcessingDiagnostics.add(ts.createFileDiagnostic(importedFile, firstRef.pos, firstRef.end - firstRef.pos, ts.Diagnostics.Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition)); + } + } + } + } + } + else { + // no imports - drop cached module resolutions + file.resolvedModules = undefined; + } + return; + function findModuleSourceFile(fileName, nameLiteral) { + return findSourceFile(fileName, /* isDefaultLib */ false, file, ts.skipTrivia(file.text, nameLiteral.pos), nameLiteral.end); + } + } + function computeCommonSourceDirectory(sourceFiles) { + var commonPathComponents; + var currentDirectory = host.getCurrentDirectory(); + ts.forEach(files, function (sourceFile) { + // Each file contributes into common source file path + if (ts.isDeclarationFile(sourceFile)) { + return; + } + var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile.fileName, currentDirectory); + sourcePathComponents.pop(); // The base file name is not part of the common directory path + if (!commonPathComponents) { + // first file + commonPathComponents = sourcePathComponents; + return; + } + for (var i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) { + if (commonPathComponents[i] !== sourcePathComponents[i]) { + if (i === 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); + return; + } + // New common path found that is 0 -> i-1 + commonPathComponents.length = i; + break; + } + } + // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents + if (sourcePathComponents.length < commonPathComponents.length) { + commonPathComponents.length = sourcePathComponents.length; + } + }); + return ts.getNormalizedPathFromPathComponents(commonPathComponents); + } + function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { + var allFilesBelongToPath = true; + if (sourceFiles) { + var currentDirectory = host.getCurrentDirectory(); + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0; _i < sourceFiles.length; _i++) { + var sourceFile = sourceFiles[_i]; + if (!ts.isDeclarationFile(sourceFile)) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); + allFilesBelongToPath = false; + } + } + } + } + return allFilesBelongToPath; + } + function verifyCompilerOptions() { + if (options.isolatedModules) { + if (options.declaration) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules")); + } + if (options.noEmitOnError) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules")); + } + if (options.out) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules")); + } + if (options.outFile) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules")); + } + } + if (options.inlineSourceMap) { + if (options.sourceMap) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap")); + } + if (options.mapRoot) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap")); + } + if (options.sourceRoot) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSourceMap")); + } + } + if (options.inlineSources) { + if (!options.sourceMap && !options.inlineSourceMap) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided)); + } + } + if (options.out && options.outFile) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile")); + } + if (!options.sourceMap && (options.mapRoot || options.sourceRoot)) { + // Error to specify --mapRoot or --sourceRoot without mapSourceFiles + if (options.mapRoot) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap")); + } + if (options.sourceRoot) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap")); + } + return; + } + var languageVersion = options.target || 0 /* ES3 */; + var outFile = options.outFile || options.out; + var firstExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); + if (options.isolatedModules) { + if (!options.module && languageVersion < 2 /* ES6 */) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher)); + } + var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); + if (firstNonExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); + } + } + else if (firstExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && !options.module) { + // We cannot use createDiagnosticFromNode because nodes do not have parents yet + var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided)); + } + // Cannot specify module gen target of es6 when below es6 + if (options.module === 5 /* ES6 */ && languageVersion < 2 /* ES6 */) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es6_when_targeting_ES5_or_lower)); + } + // there has to be common source directory if user specified --outdir || --sourceRoot + // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted + if (options.outDir || + options.sourceRoot || + (options.mapRoot && + (!outFile || firstExternalModuleSourceFile !== undefined))) { + if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) { + // If a rootDir is specified and is valid use it as the commonSourceDirectory + commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, host.getCurrentDirectory()); + } + else { + // Compute the commonSourceDirectory from the input files + commonSourceDirectory = computeCommonSourceDirectory(files); + } + if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { + // Make sure directory path ends with directory separator so this string can directly + // used to replace with "" to get the relative path of the source file and the relative path doesn't + // start with / making it rooted path + commonSourceDirectory += ts.directorySeparator; + } + } + if (options.noEmit) { + if (options.out) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "out")); + } + if (options.outFile) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outFile")); + } + if (options.outDir) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outDir")); + } + if (options.declaration) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration")); + } + } + if (options.emitDecoratorMetadata && + !options.experimentalDecorators) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); + } + } + } + ts.createProgram = createProgram; +})(ts || (ts = {})); +/// +/// +/// +/// +var ts; +(function (ts) { + /* @internal */ + ts.optionDeclarations = [ + { + name: "charset", + type: "string" + }, + { + name: "declaration", + shortName: "d", + type: "boolean", + description: ts.Diagnostics.Generates_corresponding_d_ts_file + }, + { + name: "diagnostics", + type: "boolean" + }, + { + name: "emitBOM", + type: "boolean" + }, + { + name: "help", + shortName: "h", + type: "boolean", + description: ts.Diagnostics.Print_this_message + }, + { + name: "init", + type: "boolean", + description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file + }, + { + name: "inlineSourceMap", + type: "boolean" + }, + { + name: "inlineSources", + type: "boolean" + }, + { + name: "jsx", + type: { + "preserve": 1 /* Preserve */, + "react": 2 /* React */ + }, + paramType: ts.Diagnostics.KIND, + description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react, + error: ts.Diagnostics.Argument_for_jsx_must_be_preserve_or_react + }, + { + name: "listFiles", + type: "boolean" + }, + { + name: "locale", + type: "string" + }, + { + name: "mapRoot", + type: "string", + isFilePath: true, + description: ts.Diagnostics.Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, + paramType: ts.Diagnostics.LOCATION + }, + { + name: "module", + shortName: "m", + type: { + "commonjs": 1 /* CommonJS */, + "amd": 2 /* AMD */, + "system": 4 /* System */, + "umd": 3 /* UMD */, + "es6": 5 /* ES6 */, + "es2015": 5 /* ES2015 */ + }, + description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es6, + paramType: ts.Diagnostics.KIND, + error: ts.Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es6 + }, + { + name: "newLine", + type: { + "crlf": 0 /* CarriageReturnLineFeed */, + "lf": 1 /* LineFeed */ + }, + description: ts.Diagnostics.Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, + paramType: ts.Diagnostics.NEWLINE, + error: ts.Diagnostics.Argument_for_newLine_option_must_be_CRLF_or_LF + }, + { + name: "noEmit", + type: "boolean", + description: ts.Diagnostics.Do_not_emit_outputs + }, + { + name: "noEmitHelpers", + type: "boolean" + }, + { + name: "noEmitOnError", + type: "boolean", + description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported + }, + { + name: "noImplicitAny", + type: "boolean", + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type + }, + { + name: "noLib", + type: "boolean" + }, + { + name: "noResolve", + type: "boolean" + }, + { + name: "skipDefaultLibCheck", + type: "boolean" + }, + { + name: "out", + type: "string", + isFilePath: false, + // for correct behaviour, please use outFile + paramType: ts.Diagnostics.FILE + }, + { + name: "outFile", + type: "string", + isFilePath: true, + description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, + paramType: ts.Diagnostics.FILE + }, + { + name: "outDir", + type: "string", + isFilePath: true, + description: ts.Diagnostics.Redirect_output_structure_to_the_directory, + paramType: ts.Diagnostics.DIRECTORY + }, + { + name: "preserveConstEnums", + type: "boolean", + description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code + }, + { + name: "project", + shortName: "p", + type: "string", + isFilePath: true, + description: ts.Diagnostics.Compile_the_project_in_the_given_directory, + paramType: ts.Diagnostics.DIRECTORY + }, + { + name: "removeComments", + type: "boolean", + description: ts.Diagnostics.Do_not_emit_comments_to_output + }, + { + name: "rootDir", + type: "string", + isFilePath: true, + description: ts.Diagnostics.Specifies_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, + paramType: ts.Diagnostics.LOCATION + }, + { + name: "isolatedModules", + type: "boolean" + }, + { + name: "sourceMap", + type: "boolean", + description: ts.Diagnostics.Generates_corresponding_map_file + }, + { + name: "sourceRoot", + type: "string", + isFilePath: true, + description: ts.Diagnostics.Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, + paramType: ts.Diagnostics.LOCATION + }, + { + name: "suppressExcessPropertyErrors", + type: "boolean", + description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals, + experimental: true + }, + { + name: "suppressImplicitAnyIndexErrors", + type: "boolean", + description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures + }, + { + name: "stripInternal", + type: "boolean", + description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation, + experimental: true + }, + { + name: "target", + shortName: "t", + type: { + "es3": 0 /* ES3 */, + "es5": 1 /* ES5 */, + "es6": 2 /* ES6 */, + "es2015": 2 /* ES2015 */ + }, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES6_experimental, + paramType: ts.Diagnostics.VERSION, + error: ts.Diagnostics.Argument_for_target_option_must_be_ES3_ES5_or_ES6 + }, + { + name: "version", + shortName: "v", + type: "boolean", + description: ts.Diagnostics.Print_the_compiler_s_version + }, + { + name: "watch", + shortName: "w", + type: "boolean", + description: ts.Diagnostics.Watch_input_files + }, + { + name: "experimentalDecorators", + type: "boolean", + description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators + }, + { + name: "emitDecoratorMetadata", + type: "boolean", + experimental: true, + description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators + }, + { + name: "moduleResolution", + type: { + "node": 2 /* NodeJs */, + "classic": 1 /* Classic */ + }, + description: ts.Diagnostics.Specifies_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, + error: ts.Diagnostics.Argument_for_moduleResolution_option_must_be_node_or_classic + } + ]; + var optionNameMapCache; + /* @internal */ + function getOptionNameMap() { + if (optionNameMapCache) { + return optionNameMapCache; + } + var optionNameMap = {}; + var shortOptionNames = {}; + ts.forEach(ts.optionDeclarations, function (option) { + optionNameMap[option.name.toLowerCase()] = option; + if (option.shortName) { + shortOptionNames[option.shortName] = option.name; + } + }); + optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; + return optionNameMapCache; + } + ts.getOptionNameMap = getOptionNameMap; + function parseCommandLine(commandLine, readFile) { + var options = {}; + var fileNames = []; + var errors = []; + var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; + parseStrings(commandLine); + return { + options: options, + fileNames: fileNames, + errors: errors + }; + function parseStrings(args) { + var i = 0; + while (i < args.length) { + var s = args[i++]; + if (s.charCodeAt(0) === 64 /* at */) { + parseResponseFile(s.slice(1)); + } + else if (s.charCodeAt(0) === 45 /* minus */) { + s = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase(); + // Try to translate short option names to their full equivalents. + if (ts.hasProperty(shortOptionNames, s)) { + s = shortOptionNames[s]; + } + if (ts.hasProperty(optionNameMap, s)) { + var opt = optionNameMap[s]; + // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). + if (!args[i] && opt.type !== "boolean") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + } + switch (opt.type) { + case "number": + options[opt.name] = parseInt(args[i++]); + break; + case "boolean": + options[opt.name] = true; + break; + case "string": + options[opt.name] = args[i++] || ""; + break; + // If not a primitive, the possible types are specified in what is effectively a map of options. + default: + var map_2 = opt.type; + var key = (args[i++] || "").toLowerCase(); + if (ts.hasProperty(map_2, key)) { + options[opt.name] = map_2[key]; + } + else { + errors.push(ts.createCompilerDiagnostic(opt.error)); + } + } + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + } + } + else { + fileNames.push(s); + } + } + } + function parseResponseFile(fileName) { + var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName); + if (!text) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName)); + return; + } + var args = []; + var pos = 0; + while (true) { + while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */) + pos++; + if (pos >= text.length) + break; + var start = pos; + if (text.charCodeAt(start) === 34 /* doubleQuote */) { + pos++; + while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */) + pos++; + if (pos < text.length) { + args.push(text.substring(start + 1, pos)); + pos++; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName)); + } + } + else { + while (text.charCodeAt(pos) > 32 /* space */) + pos++; + args.push(text.substring(start, pos)); + } + } + parseStrings(args); + } + } + ts.parseCommandLine = parseCommandLine; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readConfigFile(fileName, readFile) { + var text = ""; + try { + text = readFile(fileName); + } + catch (e) { + return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message) }; + } + return parseConfigFileTextToJson(fileName, text); + } + ts.readConfigFile = readConfigFile; + /** + * Parse the text of the tsconfig.json file + * @param fileName The path to the config file + * @param jsonText The text of the config file + */ + function parseConfigFileTextToJson(fileName, jsonText) { + try { + return { config: /\S/.test(jsonText) ? JSON.parse(jsonText) : {} }; + } + catch (e) { + return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; + } + } + ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + /** + * Parse the contents of a config file (tsconfig.json). + * @param json The contents of the config file to parse + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonConfigFileContent(json, host, basePath) { + var errors = []; + return { + options: getCompilerOptions(), + fileNames: getFileNames(), + errors: errors + }; + function getCompilerOptions() { + var options = {}; + var optionNameMap = {}; + ts.forEach(ts.optionDeclarations, function (option) { + optionNameMap[option.name] = option; + }); + var jsonOptions = json["compilerOptions"]; + if (jsonOptions) { + for (var id in jsonOptions) { + if (ts.hasProperty(optionNameMap, id)) { + var opt = optionNameMap[id]; + var optType = opt.type; + var value = jsonOptions[id]; + var expectedType = typeof optType === "string" ? optType : "string"; + if (typeof value === expectedType) { + if (typeof optType !== "string") { + var key = value.toLowerCase(); + if (ts.hasProperty(optType, key)) { + value = optType[key]; + } + else { + errors.push(ts.createCompilerDiagnostic(opt.error)); + value = 0; + } + } + if (opt.isFilePath) { + value = ts.normalizePath(ts.combinePaths(basePath, value)); + if (value === "") { + value = "."; + } + } + options[opt.name] = value; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, id, expectedType)); + } + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, id)); + } + } + } + return options; + } + function getFileNames() { + var fileNames = []; + if (ts.hasProperty(json, "files")) { + if (json["files"] instanceof Array) { + fileNames = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); + } + } + else { + var exclude = json["exclude"] instanceof Array ? ts.map(json["exclude"], ts.normalizeSlashes) : undefined; + var sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude)); + for (var i = 0; i < sysFiles.length; i++) { + var name_28 = sysFiles[i]; + if (ts.fileExtensionIs(name_28, ".d.ts")) { + var baseName = name_28.substr(0, name_28.length - ".d.ts".length); + if (!ts.contains(sysFiles, baseName + ".tsx") && !ts.contains(sysFiles, baseName + ".ts")) { + fileNames.push(name_28); + } + } + else if (ts.fileExtensionIs(name_28, ".ts")) { + if (!ts.contains(sysFiles, name_28 + "x")) { + fileNames.push(name_28); + } + } + else { + fileNames.push(name_28); + } + } + } + return fileNames; + } + } + ts.parseJsonConfigFileContent = parseJsonConfigFileContent; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var OutliningElementsCollector; + (function (OutliningElementsCollector) { + function collectElements(sourceFile) { + var elements = []; + var collapseText = "..."; + function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse) { + if (hintSpanNode && startElement && endElement) { + var span = { + textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end), + hintSpan: ts.createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end), + bannerText: collapseText, + autoCollapse: autoCollapse + }; + elements.push(span); + } + } + function addOutliningSpanComments(commentSpan, autoCollapse) { + if (commentSpan) { + var span = { + textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), + hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), + bannerText: collapseText, + autoCollapse: autoCollapse + }; + elements.push(span); + } + } + function addOutliningForLeadingCommentsForNode(n) { + var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); + if (comments) { + var firstSingleLineCommentStart = -1; + var lastSingleLineCommentEnd = -1; + var isFirstSingleLineComment = true; + var singleLineCommentCount = 0; + for (var _i = 0; _i < comments.length; _i++) { + var currentComment = comments[_i]; + // For single line comments, combine consecutive ones (2 or more) into + // a single span from the start of the first till the end of the last + if (currentComment.kind === 2 /* SingleLineCommentTrivia */) { + if (isFirstSingleLineComment) { + firstSingleLineCommentStart = currentComment.pos; + } + isFirstSingleLineComment = false; + lastSingleLineCommentEnd = currentComment.end; + singleLineCommentCount++; + } + else if (currentComment.kind === 3 /* MultiLineCommentTrivia */) { + combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); + addOutliningSpanComments(currentComment, /*autoCollapse*/ false); + singleLineCommentCount = 0; + lastSingleLineCommentEnd = -1; + isFirstSingleLineComment = true; + } + } + combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); + } + } + function combineAndAddMultipleSingleLineComments(count, start, end) { + // Only outline spans of two or more consecutive single line comments + if (count > 1) { + var multipleSingleLineComments = { + pos: start, + end: end, + kind: 2 /* SingleLineCommentTrivia */ + }; + addOutliningSpanComments(multipleSingleLineComments, /*autoCollapse*/ false); + } + } + function autoCollapse(node) { + return ts.isFunctionBlock(node) && node.parent.kind !== 174 /* ArrowFunction */; + } + var depth = 0; + var maxDepth = 20; + function walk(n) { + if (depth > maxDepth) { + return; + } + if (ts.isDeclaration(n)) { + addOutliningForLeadingCommentsForNode(n); + } + switch (n.kind) { + case 192 /* Block */: + if (!ts.isFunctionBlock(n)) { + var parent_7 = n.parent; + var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); + var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); + // Check if the block is standalone, or 'attached' to some parent statement. + // If the latter, we want to collaps the block, but consider its hint span + // to be the entire span of the parent. + if (parent_7.kind === 197 /* DoStatement */ || + parent_7.kind === 200 /* ForInStatement */ || + parent_7.kind === 201 /* ForOfStatement */ || + parent_7.kind === 199 /* ForStatement */ || + parent_7.kind === 196 /* IfStatement */ || + parent_7.kind === 198 /* WhileStatement */ || + parent_7.kind === 205 /* WithStatement */ || + parent_7.kind === 244 /* CatchClause */) { + addOutliningSpan(parent_7, openBrace, closeBrace, autoCollapse(n)); + break; + } + if (parent_7.kind === 209 /* TryStatement */) { + // Could be the try-block, or the finally-block. + var tryStatement = parent_7; + if (tryStatement.tryBlock === n) { + addOutliningSpan(parent_7, openBrace, closeBrace, autoCollapse(n)); + break; + } + else if (tryStatement.finallyBlock === n) { + var finallyKeyword = ts.findChildOfKind(tryStatement, 85 /* FinallyKeyword */, sourceFile); + if (finallyKeyword) { + addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); + break; + } + } + } + // Block was a standalone block. In this case we want to only collapse + // the span of the block, independent of any parent span. + var span = ts.createTextSpanFromBounds(n.getStart(), n.end); + elements.push({ + textSpan: span, + hintSpan: span, + bannerText: collapseText, + autoCollapse: autoCollapse(n) + }); + break; + } + // Fallthrough. + case 219 /* ModuleBlock */: { + var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); + var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); + addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); + break; + } + case 214 /* ClassDeclaration */: + case 215 /* InterfaceDeclaration */: + case 217 /* EnumDeclaration */: + case 165 /* ObjectLiteralExpression */: + case 220 /* CaseBlock */: { + var openBrace = ts.findChildOfKind(n, 15 /* OpenBraceToken */, sourceFile); + var closeBrace = ts.findChildOfKind(n, 16 /* CloseBraceToken */, sourceFile); + addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); + break; + } + case 164 /* ArrayLiteralExpression */: + var openBracket = ts.findChildOfKind(n, 19 /* OpenBracketToken */, sourceFile); + var closeBracket = ts.findChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); + addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); + break; + } + depth++; + ts.forEachChild(n, walk); + depth--; + } + walk(sourceFile); + return elements; + } + OutliningElementsCollector.collectElements = collectElements; + })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var NavigateTo; + (function (NavigateTo) { + function getNavigateToItems(program, cancellationToken, searchValue, maxResultCount) { + var patternMatcher = ts.createPatternMatcher(searchValue); + var rawItems = []; + // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] + ts.forEach(program.getSourceFiles(), function (sourceFile) { + cancellationToken.throwIfCancellationRequested(); + var nameToDeclarations = sourceFile.getNamedDeclarations(); + for (var name_29 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_29); + if (declarations) { + // First do a quick check to see if the name of the declaration matches the + // last portion of the (possibly) dotted name they're searching for. + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_29); + if (!matches) { + continue; + } + for (var _i = 0; _i < declarations.length; _i++) { + var declaration = declarations[_i]; + // It was a match! If the pattern has dots in it, then also see if the + // declaration container matches as well. + if (patternMatcher.patternContainsDots) { + var containers = getContainers(declaration); + if (!containers) { + return undefined; + } + matches = patternMatcher.getMatches(containers, name_29); + if (!matches) { + continue; + } + } + var fileName = sourceFile.fileName; + var matchKind = bestMatchKind(matches); + rawItems.push({ name: name_29, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + } + } + } + }); + rawItems.sort(compareNavigateToItems); + if (maxResultCount !== undefined) { + rawItems = rawItems.slice(0, maxResultCount); + } + var items = ts.map(rawItems, createNavigateToItem); + return items; + function allMatchesAreCaseSensitive(matches) { + ts.Debug.assert(matches.length > 0); + // This is a case sensitive match, only if all the submatches were case sensitive. + for (var _i = 0; _i < matches.length; _i++) { + var match = matches[_i]; + if (!match.isCaseSensitive) { + return false; + } + } + return true; + } + function getTextOfIdentifierOrLiteral(node) { + if (node) { + if (node.kind === 69 /* Identifier */ || + node.kind === 9 /* StringLiteral */ || + node.kind === 8 /* NumericLiteral */) { + return node.text; + } + } + return undefined; + } + function tryAddSingleDeclarationName(declaration, containers) { + if (declaration && declaration.name) { + var text = getTextOfIdentifierOrLiteral(declaration.name); + if (text !== undefined) { + containers.unshift(text); + } + else if (declaration.name.kind === 136 /* ComputedPropertyName */) { + return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion:*/ true); + } + else { + // Don't know how to add this. + return false; + } + } + return true; + } + // Only added the names of computed properties if they're simple dotted expressions, like: + // + // [X.Y.Z]() { } + function tryAddComputedPropertyName(expression, containers, includeLastPortion) { + var text = getTextOfIdentifierOrLiteral(expression); + if (text !== undefined) { + if (includeLastPortion) { + containers.unshift(text); + } + return true; + } + if (expression.kind === 166 /* PropertyAccessExpression */) { + var propertyAccess = expression; + if (includeLastPortion) { + containers.unshift(propertyAccess.name.text); + } + return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion:*/ true); + } + return false; + } + function getContainers(declaration) { + var containers = []; + // First, if we started with a computed property name, then add all but the last + // portion into the container array. + if (declaration.name.kind === 136 /* ComputedPropertyName */) { + if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion:*/ false)) { + return undefined; + } + } + // Now, walk up our containers, adding all their names to the container array. + declaration = ts.getContainerNode(declaration); + while (declaration) { + if (!tryAddSingleDeclarationName(declaration, containers)) { + return undefined; + } + declaration = ts.getContainerNode(declaration); + } + return containers; + } + function bestMatchKind(matches) { + ts.Debug.assert(matches.length > 0); + var bestMatchKind = ts.PatternMatchKind.camelCase; + for (var _i = 0; _i < matches.length; _i++) { + var match = matches[_i]; + var kind = match.kind; + if (kind < bestMatchKind) { + bestMatchKind = kind; + } + } + return bestMatchKind; + } + // This means "compare in a case insensitive manner." + var baseSensitivity = { sensitivity: "base" }; + function compareNavigateToItems(i1, i2) { + // TODO(cyrusn): get the gamut of comparisons that VS already uses here. + // Right now we just sort by kind first, and then by name of the item. + // We first sort case insensitively. So "Aaa" will come before "bar". + // Then we sort case sensitively, so "aaa" will come before "Aaa". + return i1.matchKind - i2.matchKind || + i1.name.localeCompare(i2.name, undefined, baseSensitivity) || + i1.name.localeCompare(i2.name); + } + function createNavigateToItem(rawItem) { + var declaration = rawItem.declaration; + var container = ts.getContainerNode(declaration); + return { + name: rawItem.name, + kind: ts.getNodeKind(declaration), + kindModifiers: ts.getNodeModifiers(declaration), + matchKind: ts.PatternMatchKind[rawItem.matchKind], + isCaseSensitive: rawItem.isCaseSensitive, + fileName: rawItem.fileName, + textSpan: ts.createTextSpanFromBounds(declaration.getStart(), declaration.getEnd()), + // TODO(jfreeman): What should be the containerName when the container has a computed name? + containerName: container && container.name ? container.name.text : "", + containerKind: container && container.name ? ts.getNodeKind(container) : "" + }; + } + } + NavigateTo.getNavigateToItems = getNavigateToItems; + })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {})); +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + var NavigationBar; + (function (NavigationBar) { + function getNavigationBarItems(sourceFile) { + // If the source file has any child items, then it included in the tree + // and takes lexical ownership of all other top-level items. + var hasGlobalNode = false; + return getItemsWorker(getTopLevelNodes(sourceFile), createTopLevelItem); + function getIndent(node) { + // If we have a global node in the tree, + // then it adds an extra layer of depth to all subnodes. + var indent = hasGlobalNode ? 1 : 0; + var current = node.parent; + while (current) { + switch (current.kind) { + case 218 /* ModuleDeclaration */: + // If we have a module declared as A.B.C, it is more "intuitive" + // to say it only has a single layer of depth + do { + current = current.parent; + } while (current.kind === 218 /* ModuleDeclaration */); + // fall through + case 214 /* ClassDeclaration */: + case 217 /* EnumDeclaration */: + case 215 /* InterfaceDeclaration */: + case 213 /* FunctionDeclaration */: + indent++; + } + current = current.parent; + } + return indent; + } + function getChildNodes(nodes) { + var childNodes = []; + function visit(node) { + switch (node.kind) { + case 193 /* VariableStatement */: + ts.forEach(node.declarationList.declarations, visit); + break; + case 161 /* ObjectBindingPattern */: + case 162 /* ArrayBindingPattern */: + ts.forEach(node.elements, visit); + break; + case 228 /* ExportDeclaration */: + // Handle named exports case e.g.: + // export {a, b as B} from "mod"; + if (node.exportClause) { + ts.forEach(node.exportClause.elements, visit); + } + break; + case 222 /* ImportDeclaration */: + var importClause = node.importClause; + if (importClause) { + // Handle default import case e.g.: + // import d from "mod"; + if (importClause.name) { + childNodes.push(importClause); + } + // Handle named bindings in imports e.g.: + // import * as NS from "mod"; + // import {a, b as B} from "mod"; + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 224 /* NamespaceImport */) { + childNodes.push(importClause.namedBindings); + } + else { + ts.forEach(importClause.namedBindings.elements, visit); + } + } + } + break; + case 163 /* BindingElement */: + case 211 /* VariableDeclaration */: + if (ts.isBindingPattern(node.name)) { + visit(node.name); + break; + } + // Fall through + case 214 /* ClassDeclaration */: + case 217 /* EnumDeclaration */: + case 215 /* InterfaceDeclaration */: + case 218 /* ModuleDeclaration */: + case 213 /* FunctionDeclaration */: + case 221 /* ImportEqualsDeclaration */: + case 226 /* ImportSpecifier */: + case 230 /* ExportSpecifier */: + childNodes.push(node); + break; + } + } + //for (let i = 0, n = nodes.length; i < n; i++) { + // let node = nodes[i]; + // if (node.kind === SyntaxKind.ClassDeclaration || + // node.kind === SyntaxKind.EnumDeclaration || + // node.kind === SyntaxKind.InterfaceDeclaration || + // node.kind === SyntaxKind.ModuleDeclaration || + // node.kind === SyntaxKind.FunctionDeclaration) { + // childNodes.push(node); + // } + // else if (node.kind === SyntaxKind.VariableStatement) { + // childNodes.push.apply(childNodes, (node).declarations); + // } + //} + ts.forEach(nodes, visit); + return sortNodes(childNodes); + } + function getTopLevelNodes(node) { + var topLevelNodes = []; + topLevelNodes.push(node); + addTopLevelNodes(node.statements, topLevelNodes); + return topLevelNodes; + } + function sortNodes(nodes) { + return nodes.slice(0).sort(function (n1, n2) { + if (n1.name && n2.name) { + return ts.getPropertyNameForPropertyNameNode(n1.name).localeCompare(ts.getPropertyNameForPropertyNameNode(n2.name)); + } + else if (n1.name) { + return 1; + } + else if (n2.name) { + return -1; + } + else { + return n1.kind - n2.kind; + } + }); + } + function addTopLevelNodes(nodes, topLevelNodes) { + nodes = sortNodes(nodes); + for (var _i = 0; _i < nodes.length; _i++) { + var node = nodes[_i]; + switch (node.kind) { + case 214 /* ClassDeclaration */: + case 217 /* EnumDeclaration */: + case 215 /* InterfaceDeclaration */: + topLevelNodes.push(node); + break; + case 218 /* ModuleDeclaration */: + var moduleDeclaration = node; + topLevelNodes.push(node); + addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes); + break; + case 213 /* FunctionDeclaration */: + var functionDeclaration = node; + if (isTopLevelFunctionDeclaration(functionDeclaration)) { + topLevelNodes.push(node); + addTopLevelNodes(functionDeclaration.body.statements, topLevelNodes); + } + break; + } + } + } + function isTopLevelFunctionDeclaration(functionDeclaration) { + if (functionDeclaration.kind === 213 /* FunctionDeclaration */) { + // A function declaration is 'top level' if it contains any function declarations + // within it. + if (functionDeclaration.body && functionDeclaration.body.kind === 192 /* Block */) { + // Proper function declarations can only have identifier names + if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 213 /* FunctionDeclaration */ && !isEmpty(s.name.text); })) { + return true; + } + // Or if it is not parented by another function. i.e all functions + // at module scope are 'top level'. + if (!ts.isFunctionBlock(functionDeclaration.parent)) { + return true; + } + } + } + return false; + } + function getItemsWorker(nodes, createItem) { + var items = []; + var keyToItem = {}; + for (var _i = 0; _i < nodes.length; _i++) { + var child = nodes[_i]; + var item = createItem(child); + if (item !== undefined) { + if (item.text.length > 0) { + var key = item.text + "-" + item.kind + "-" + item.indent; + var itemWithSameName = keyToItem[key]; + if (itemWithSameName) { + // We had an item with the same name. Merge these items together. + merge(itemWithSameName, item); + } + else { + keyToItem[key] = item; + items.push(item); + } + } + } + } + return items; + } + function merge(target, source) { + // First, add any spans in the source to the target. + ts.addRange(target.spans, source.spans); + if (source.childItems) { + if (!target.childItems) { + target.childItems = []; + } + // Next, recursively merge or add any children in the source as appropriate. + outer: for (var _i = 0, _a = source.childItems; _i < _a.length; _i++) { + var sourceChild = _a[_i]; + for (var _b = 0, _c = target.childItems; _b < _c.length; _b++) { + var targetChild = _c[_b]; + if (targetChild.text === sourceChild.text && targetChild.kind === sourceChild.kind) { + // Found a match. merge them. + merge(targetChild, sourceChild); + continue outer; + } + } + // Didn't find a match, just add this child to the list. + target.childItems.push(sourceChild); + } + } + } + function createChildItem(node) { + switch (node.kind) { + case 138 /* Parameter */: + if (ts.isBindingPattern(node.name)) { + break; + } + if ((node.flags & 2035 /* Modifier */) === 0) { + return undefined; + } + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberFunctionElement); + case 145 /* GetAccessor */: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement); + case 146 /* SetAccessor */: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); + case 149 /* IndexSignature */: + return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); + case 247 /* EnumMember */: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); + case 147 /* CallSignature */: + return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); + case 148 /* ConstructSignature */: + return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement); + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); + case 213 /* FunctionDeclaration */: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); + case 211 /* VariableDeclaration */: + case 163 /* BindingElement */: + var variableDeclarationNode; + var name_30; + if (node.kind === 163 /* BindingElement */) { + name_30 = node.name; + variableDeclarationNode = node; + // binding elements are added only for variable declarations + // bubble up to the containing variable declaration + while (variableDeclarationNode && variableDeclarationNode.kind !== 211 /* VariableDeclaration */) { + variableDeclarationNode = variableDeclarationNode.parent; + } + ts.Debug.assert(variableDeclarationNode !== undefined); + } + else { + ts.Debug.assert(!ts.isBindingPattern(node.name)); + variableDeclarationNode = node; + name_30 = node.name; + } + if (ts.isConst(variableDeclarationNode)) { + return createItem(node, getTextOfNode(name_30), ts.ScriptElementKind.constElement); + } + else if (ts.isLet(variableDeclarationNode)) { + return createItem(node, getTextOfNode(name_30), ts.ScriptElementKind.letElement); + } + else { + return createItem(node, getTextOfNode(name_30), ts.ScriptElementKind.variableElement); + } + case 144 /* Constructor */: + return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); + case 230 /* ExportSpecifier */: + case 226 /* ImportSpecifier */: + case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportClause */: + case 224 /* NamespaceImport */: + return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias); + } + return undefined; + function createItem(node, name, scriptElementKind) { + return getNavigationBarItem(name, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)]); + } + } + function isEmpty(text) { + return !text || text.trim() === ""; + } + function getNavigationBarItem(text, kind, kindModifiers, spans, childItems, indent) { + if (childItems === void 0) { childItems = []; } + if (indent === void 0) { indent = 0; } + if (isEmpty(text)) { + return undefined; + } + return { + text: text, + kind: kind, + kindModifiers: kindModifiers, + spans: spans, + childItems: childItems, + indent: indent, + bolded: false, + grayed: false + }; + } + function createTopLevelItem(node) { + switch (node.kind) { + case 248 /* SourceFile */: + return createSourceFileItem(node); + case 214 /* ClassDeclaration */: + return createClassItem(node); + case 217 /* EnumDeclaration */: + return createEnumItem(node); + case 215 /* InterfaceDeclaration */: + return createIterfaceItem(node); + case 218 /* ModuleDeclaration */: + return createModuleItem(node); + case 213 /* FunctionDeclaration */: + return createFunctionItem(node); + } + return undefined; + function getModuleName(moduleDeclaration) { + // We want to maintain quotation marks. + if (moduleDeclaration.name.kind === 9 /* StringLiteral */) { + return getTextOfNode(moduleDeclaration.name); + } + // Otherwise, we need to aggregate each identifier to build up the qualified name. + var result = []; + result.push(moduleDeclaration.name.text); + while (moduleDeclaration.body && moduleDeclaration.body.kind === 218 /* ModuleDeclaration */) { + moduleDeclaration = moduleDeclaration.body; + result.push(moduleDeclaration.name.text); + } + return result.join("."); + } + function createModuleItem(node) { + var moduleName = getModuleName(node); + var childItems = getItemsWorker(getChildNodes(getInnermostModule(node).body.statements), createChildItem); + return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); + } + function createFunctionItem(node) { + if (node.body && node.body.kind === 192 /* Block */) { + var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); + return getNavigationBarItem(!node.name ? "default" : node.name.text, ts.ScriptElementKind.functionElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); + } + return undefined; + } + function createSourceFileItem(node) { + var childItems = getItemsWorker(getChildNodes(node.statements), createChildItem); + if (childItems === undefined || childItems.length === 0) { + return undefined; + } + hasGlobalNode = true; + var rootName = ts.isExternalModule(node) + ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(node.fileName)))) + "\"" + : ""; + return getNavigationBarItem(rootName, ts.ScriptElementKind.moduleElement, ts.ScriptElementKindModifier.none, [getNodeSpan(node)], childItems); + } + function createClassItem(node) { + var childItems; + if (node.members) { + var constructor = ts.forEach(node.members, function (member) { + return member.kind === 144 /* Constructor */ && member; + }); + // Add the constructor parameters in as children of the class (for property parameters). + // Note that *all non-binding pattern named* parameters will be added to the nodes array, but parameters that + // are not properties will be filtered out later by createChildItem. + var nodes = removeDynamicallyNamedProperties(node); + if (constructor) { + ts.addRange(nodes, ts.filter(constructor.parameters, function (p) { return !ts.isBindingPattern(p.name); })); + } + childItems = getItemsWorker(sortNodes(nodes), createChildItem); + } + var nodeName = !node.name ? "default" : node.name.text; + return getNavigationBarItem(nodeName, ts.ScriptElementKind.classElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); + } + function createEnumItem(node) { + var childItems = getItemsWorker(sortNodes(removeComputedProperties(node)), createChildItem); + return getNavigationBarItem(node.name.text, ts.ScriptElementKind.enumElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); + } + function createIterfaceItem(node) { + var childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem); + return getNavigationBarItem(node.name.text, ts.ScriptElementKind.interfaceElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); + } + } + function removeComputedProperties(node) { + return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 136 /* ComputedPropertyName */; }); + } + /** + * Like removeComputedProperties, but retains the properties with well known symbol names + */ + function removeDynamicallyNamedProperties(node) { + return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); }); + } + function getInnermostModule(node) { + while (node.body.kind === 218 /* ModuleDeclaration */) { + node = node.body; + } + return node; + } + function getNodeSpan(node) { + return node.kind === 248 /* SourceFile */ + ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) + : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); + } + function getTextOfNode(node) { + return ts.getTextOfNodeFromSourceText(sourceFile.text, node); + } + } + NavigationBar.getNavigationBarItems = getNavigationBarItems; + })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // Note(cyrusn): this enum is ordered from strongest match type to weakest match type. + (function (PatternMatchKind) { + PatternMatchKind[PatternMatchKind["exact"] = 0] = "exact"; + PatternMatchKind[PatternMatchKind["prefix"] = 1] = "prefix"; + PatternMatchKind[PatternMatchKind["substring"] = 2] = "substring"; + PatternMatchKind[PatternMatchKind["camelCase"] = 3] = "camelCase"; + })(ts.PatternMatchKind || (ts.PatternMatchKind = {})); + var PatternMatchKind = ts.PatternMatchKind; + function createPatternMatch(kind, punctuationStripped, isCaseSensitive, camelCaseWeight) { + return { + kind: kind, + punctuationStripped: punctuationStripped, + isCaseSensitive: isCaseSensitive, + camelCaseWeight: camelCaseWeight + }; + } + function createPatternMatcher(pattern) { + // We'll often see the same candidate string many times when searching (For example, when + // we see the name of a module that is used everywhere, or the name of an overload). As + // such, we cache the information we compute about the candidate for the life of this + // pattern matcher so we don't have to compute it multiple times. + var stringToWordSpans = {}; + pattern = pattern.trim(); + var fullPatternSegment = createSegment(pattern); + var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); }); + var invalidPattern = dotSeparatedSegments.length === 0 || ts.forEach(dotSeparatedSegments, segmentIsInvalid); + return { + getMatches: getMatches, + getMatchesForLastSegmentOfPattern: getMatchesForLastSegmentOfPattern, + patternContainsDots: dotSeparatedSegments.length > 1 + }; + // Quick checks so we can bail out when asked to match a candidate. + function skipMatch(candidate) { + return invalidPattern || !candidate; + } + function getMatchesForLastSegmentOfPattern(candidate) { + if (skipMatch(candidate)) { + return undefined; + } + return matchSegment(candidate, ts.lastOrUndefined(dotSeparatedSegments)); + } + function getMatches(candidateContainers, candidate) { + if (skipMatch(candidate)) { + return undefined; + } + // First, check that the last part of the dot separated pattern matches the name of the + // candidate. If not, then there's no point in proceeding and doing the more + // expensive work. + var candidateMatch = matchSegment(candidate, ts.lastOrUndefined(dotSeparatedSegments)); + if (!candidateMatch) { + return undefined; + } + candidateContainers = candidateContainers || []; + // -1 because the last part was checked against the name, and only the rest + // of the parts are checked against the container. + if (dotSeparatedSegments.length - 1 > candidateContainers.length) { + // There weren't enough container parts to match against the pattern parts. + // So this definitely doesn't match. + return undefined; + } + // So far so good. Now break up the container for the candidate and check if all + // the dotted parts match up correctly. + var totalMatch = candidateMatch; + for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i--, j--) { + var segment = dotSeparatedSegments[i]; + var containerName = candidateContainers[j]; + var containerMatch = matchSegment(containerName, segment); + if (!containerMatch) { + // This container didn't match the pattern piece. So there's no match at all. + return undefined; + } + ts.addRange(totalMatch, containerMatch); + } + // Success, this symbol's full name matched against the dotted name the user was asking + // about. + return totalMatch; + } + function getWordSpans(word) { + if (!ts.hasProperty(stringToWordSpans, word)) { + stringToWordSpans[word] = breakIntoWordSpans(word); + } + return stringToWordSpans[word]; + } + function matchTextChunk(candidate, chunk, punctuationStripped) { + var index = indexOfIgnoringCase(candidate, chunk.textLowerCase); + if (index === 0) { + if (chunk.text.length === candidate.length) { + // a) Check if the part matches the candidate entirely, in an case insensitive or + // sensitive manner. If it does, return that there was an exact match. + return createPatternMatch(PatternMatchKind.exact, punctuationStripped, /*isCaseSensitive:*/ candidate === chunk.text); + } + else { + // b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive + // manner. If it does, return that there was a prefix match. + return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ startsWith(candidate, chunk.text)); + } + } + var isLowercase = chunk.isLowerCase; + if (isLowercase) { + if (index > 0) { + // c) If the part is entirely lowercase, then check if it is contained anywhere in the + // candidate in a case insensitive manner. If so, return that there was a substring + // match. + // + // Note: We only have a substring match if the lowercase part is prefix match of some + // word part. That way we don't match something like 'Class' when the user types 'a'. + // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). + var wordSpans = getWordSpans(candidate); + for (var _i = 0; _i < wordSpans.length; _i++) { + var span = wordSpans[_i]; + if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) { + return createPatternMatch(PatternMatchKind.substring, punctuationStripped, + /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false)); + } + } + } + } + else { + // d) If the part was not entirely lowercase, then check if it is contained in the + // candidate in a case *sensitive* manner. If so, return that there was a substring + // match. + if (candidate.indexOf(chunk.text) > 0) { + return createPatternMatch(PatternMatchKind.substring, punctuationStripped, /*isCaseSensitive:*/ true); + } + } + if (!isLowercase) { + // e) If the part was not entirely lowercase, then attempt a camel cased match as well. + if (chunk.characterSpans.length > 0) { + var candidateParts = getWordSpans(candidate); + var camelCaseWeight = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ false); + if (camelCaseWeight !== undefined) { + return createPatternMatch(PatternMatchKind.camelCase, punctuationStripped, /*isCaseSensitive:*/ true, /*camelCaseWeight:*/ camelCaseWeight); + } + camelCaseWeight = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ true); + if (camelCaseWeight !== undefined) { + return createPatternMatch(PatternMatchKind.camelCase, punctuationStripped, /*isCaseSensitive:*/ false, /*camelCaseWeight:*/ camelCaseWeight); + } + } + } + if (isLowercase) { + // f) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries? + // We could check every character boundary start of the candidate for the pattern. However, that's + // an m * n operation in the wost case. Instead, find the first instance of the pattern + // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to + // filter the list based on a substring that starts on a capital letter and also with a lowercase one. + // (Pattern: fogbar, Candidate: quuxfogbarFogBar). + if (chunk.text.length < candidate.length) { + if (index > 0 && isUpperCaseLetter(candidate.charCodeAt(index))) { + return createPatternMatch(PatternMatchKind.substring, punctuationStripped, /*isCaseSensitive:*/ false); + } + } + } + return undefined; + } + function containsSpaceOrAsterisk(text) { + for (var i = 0; i < text.length; i++) { + var ch = text.charCodeAt(i); + if (ch === 32 /* space */ || ch === 42 /* asterisk */) { + return true; + } + } + return false; + } + function matchSegment(candidate, segment) { + // First check if the segment matches as is. This is also useful if the segment contains + // characters we would normally strip when splitting into parts that we also may want to + // match in the candidate. For example if the segment is "@int" and the candidate is + // "@int", then that will show up as an exact match here. + // + // Note: if the segment contains a space or an asterisk then we must assume that it's a + // multi-word segment. + if (!containsSpaceOrAsterisk(segment.totalTextChunk.text)) { + var match = matchTextChunk(candidate, segment.totalTextChunk, /*punctuationStripped:*/ false); + if (match) { + return [match]; + } + } + // The logic for pattern matching is now as follows: + // + // 1) Break the segment passed in into words. Breaking is rather simple and a + // good way to think about it that if gives you all the individual alphanumeric words + // of the pattern. + // + // 2) For each word try to match the word against the candidate value. + // + // 3) Matching is as follows: + // + // a) Check if the word matches the candidate entirely, in an case insensitive or + // sensitive manner. If it does, return that there was an exact match. + // + // b) Check if the word is a prefix of the candidate, in a case insensitive or + // sensitive manner. If it does, return that there was a prefix match. + // + // c) If the word is entirely lowercase, then check if it is contained anywhere in the + // candidate in a case insensitive manner. If so, return that there was a substring + // match. + // + // Note: We only have a substring match if the lowercase part is prefix match of + // some word part. That way we don't match something like 'Class' when the user + // types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with + // 'a'). + // + // d) If the word was not entirely lowercase, then check if it is contained in the + // candidate in a case *sensitive* manner. If so, return that there was a substring + // match. + // + // e) If the word was not entirely lowercase, then attempt a camel cased match as + // well. + // + // f) The word is all lower case. Is it a case insensitive substring of the candidate starting + // on a part boundary of the candidate? + // + // Only if all words have some sort of match is the pattern considered matched. + var subWordTextChunks = segment.subWordTextChunks; + var matches = undefined; + for (var _i = 0; _i < subWordTextChunks.length; _i++) { + var subWordTextChunk = subWordTextChunks[_i]; + // Try to match the candidate with this word + var result = matchTextChunk(candidate, subWordTextChunk, /*punctuationStripped:*/ true); + if (!result) { + return undefined; + } + matches = matches || []; + matches.push(result); + } + return matches; + } + function partStartsWith(candidate, candidateSpan, pattern, ignoreCase, patternSpan) { + var patternPartStart = patternSpan ? patternSpan.start : 0; + var patternPartLength = patternSpan ? patternSpan.length : pattern.length; + if (patternPartLength > candidateSpan.length) { + // Pattern part is longer than the candidate part. There can never be a match. + return false; + } + if (ignoreCase) { + for (var i = 0; i < patternPartLength; i++) { + var ch1 = pattern.charCodeAt(patternPartStart + i); + var ch2 = candidate.charCodeAt(candidateSpan.start + i); + if (toLowerCase(ch1) !== toLowerCase(ch2)) { + return false; + } + } + } + else { + for (var i = 0; i < patternPartLength; i++) { + var ch1 = pattern.charCodeAt(patternPartStart + i); + var ch2 = candidate.charCodeAt(candidateSpan.start + i); + if (ch1 !== ch2) { + return false; + } + } + } + return true; + } + function tryCamelCaseMatch(candidate, candidateParts, chunk, ignoreCase) { + var chunkCharacterSpans = chunk.characterSpans; + // Note: we may have more pattern parts than candidate parts. This is because multiple + // pattern parts may match a candidate part. For example "SiUI" against "SimpleUI". + // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U + // and I will both match in UI. + var currentCandidate = 0; + var currentChunkSpan = 0; + var firstMatch = undefined; + var contiguous = undefined; + while (true) { + // Let's consider our termination cases + if (currentChunkSpan === chunkCharacterSpans.length) { + // We did match! We shall assign a weight to this + var weight = 0; + // Was this contiguous? + if (contiguous) { + weight += 1; + } + // Did we start at the beginning of the candidate? + if (firstMatch === 0) { + weight += 2; + } + return weight; + } + else if (currentCandidate === candidateParts.length) { + // No match, since we still have more of the pattern to hit + return undefined; + } + var candidatePart = candidateParts[currentCandidate]; + var gotOneMatchThisCandidate = false; + // Consider the case of matching SiUI against SimpleUIElement. The candidate parts + // will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si' + // against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to + // still keep matching pattern parts against that candidate part. + for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) { + var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan]; + if (gotOneMatchThisCandidate) { + // We've already gotten one pattern part match in this candidate. We will + // only continue trying to consumer pattern parts if the last part and this + // part are both upper case. + if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) || + !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) { + break; + } + } + if (!partStartsWith(candidate, candidatePart, chunk.text, ignoreCase, chunkCharacterSpan)) { + break; + } + gotOneMatchThisCandidate = true; + firstMatch = firstMatch === undefined ? currentCandidate : firstMatch; + // If we were contiguous, then keep that value. If we weren't, then keep that + // value. If we don't know, then set the value to 'true' as an initial match is + // obviously contiguous. + contiguous = contiguous === undefined ? true : contiguous; + candidatePart = ts.createTextSpan(candidatePart.start + chunkCharacterSpan.length, candidatePart.length - chunkCharacterSpan.length); + } + // Check if we matched anything at all. If we didn't, then we need to unset the + // contiguous bit if we currently had it set. + // If we haven't set the bit yet, then that means we haven't matched anything so + // far, and we don't want to change that. + if (!gotOneMatchThisCandidate && contiguous !== undefined) { + contiguous = false; + } + // Move onto the next candidate. + currentCandidate++; + } + } + } + ts.createPatternMatcher = createPatternMatcher; + // Helper function to compare two matches to determine which is better. Matches are first + // ordered by kind (so all prefix matches always beat all substring matches). Then, if the + // match is a camel case match, the relative weights of the match are used to determine + // which is better (with a greater weight being better). Then if the match is of the same + // type, then a case sensitive match is considered better than an insensitive one. + function patternMatchCompareTo(match1, match2) { + return compareType(match1, match2) || + compareCamelCase(match1, match2) || + compareCase(match1, match2) || + comparePunctuation(match1, match2); + } + function comparePunctuation(result1, result2) { + // Consider a match to be better if it was successful without stripping punctuation + // versus a match that had to strip punctuation to succeed. + if (result1.punctuationStripped !== result2.punctuationStripped) { + return result1.punctuationStripped ? 1 : -1; + } + return 0; + } + function compareCase(result1, result2) { + if (result1.isCaseSensitive !== result2.isCaseSensitive) { + return result1.isCaseSensitive ? -1 : 1; + } + return 0; + } + function compareType(result1, result2) { + return result1.kind - result2.kind; + } + function compareCamelCase(result1, result2) { + if (result1.kind === PatternMatchKind.camelCase && result2.kind === PatternMatchKind.camelCase) { + // Swap the values here. If result1 has a higher weight, then we want it to come + // first. + return result2.camelCaseWeight - result1.camelCaseWeight; + } + return 0; + } + function createSegment(text) { + return { + totalTextChunk: createTextChunk(text), + subWordTextChunks: breakPatternIntoTextChunks(text) + }; + } + // A segment is considered invalid if we couldn't find any words in it. + function segmentIsInvalid(segment) { + return segment.subWordTextChunks.length === 0; + } + function isUpperCaseLetter(ch) { + // Fast check for the ascii range. + if (ch >= 65 /* A */ && ch <= 90 /* Z */) { + return true; + } + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 2 /* Latest */)) { + return false; + } + // TODO: find a way to determine this for any unicode characters in a + // non-allocating manner. + var str = String.fromCharCode(ch); + return str === str.toUpperCase(); + } + function isLowerCaseLetter(ch) { + // Fast check for the ascii range. + if (ch >= 97 /* a */ && ch <= 122 /* z */) { + return true; + } + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 2 /* Latest */)) { + return false; + } + // TODO: find a way to determine this for any unicode characters in a + // non-allocating manner. + var str = String.fromCharCode(ch); + return str === str.toLowerCase(); + } + function containsUpperCaseLetter(string) { + for (var i = 0, n = string.length; i < n; i++) { + if (isUpperCaseLetter(string.charCodeAt(i))) { + return true; + } + } + return false; + } + function startsWith(string, search) { + for (var i = 0, n = search.length; i < n; i++) { + if (string.charCodeAt(i) !== search.charCodeAt(i)) { + return false; + } + } + return true; + } + // Assumes 'value' is already lowercase. + function indexOfIgnoringCase(string, value) { + for (var i = 0, n = string.length - value.length; i <= n; i++) { + if (startsWithIgnoringCase(string, value, i)) { + return i; + } + } + return -1; + } + // Assumes 'value' is already lowercase. + function startsWithIgnoringCase(string, value, start) { + for (var i = 0, n = value.length; i < n; i++) { + var ch1 = toLowerCase(string.charCodeAt(i + start)); + var ch2 = value.charCodeAt(i); + if (ch1 !== ch2) { + return false; + } + } + return true; + } + function toLowerCase(ch) { + // Fast convert for the ascii range. + if (ch >= 65 /* A */ && ch <= 90 /* Z */) { + return 97 /* a */ + (ch - 65 /* A */); + } + if (ch < 127 /* maxAsciiCharacter */) { + return ch; + } + // TODO: find a way to compute this for any unicode characters in a + // non-allocating manner. + return String.fromCharCode(ch).toLowerCase().charCodeAt(0); + } + function isDigit(ch) { + // TODO(cyrusn): Find a way to support this for unicode digits. + return ch >= 48 /* _0 */ && ch <= 57 /* _9 */; + } + function isWordChar(ch) { + return isUpperCaseLetter(ch) || isLowerCaseLetter(ch) || isDigit(ch) || ch === 95 /* _ */ || ch === 36 /* $ */; + } + function breakPatternIntoTextChunks(pattern) { + var result = []; + var wordStart = 0; + var wordLength = 0; + for (var i = 0; i < pattern.length; i++) { + var ch = pattern.charCodeAt(i); + if (isWordChar(ch)) { + if (wordLength++ === 0) { + wordStart = i; + } + } + else { + if (wordLength > 0) { + result.push(createTextChunk(pattern.substr(wordStart, wordLength))); + wordLength = 0; + } + } + } + if (wordLength > 0) { + result.push(createTextChunk(pattern.substr(wordStart, wordLength))); + } + return result; + } + function createTextChunk(text) { + var textLowerCase = text.toLowerCase(); + return { + text: text, + textLowerCase: textLowerCase, + isLowerCase: text === textLowerCase, + characterSpans: breakIntoCharacterSpans(text) + }; + } + /* @internal */ function breakIntoCharacterSpans(identifier) { + return breakIntoSpans(identifier, /*word:*/ false); + } + ts.breakIntoCharacterSpans = breakIntoCharacterSpans; + /* @internal */ function breakIntoWordSpans(identifier) { + return breakIntoSpans(identifier, /*word:*/ true); + } + ts.breakIntoWordSpans = breakIntoWordSpans; + function breakIntoSpans(identifier, word) { + var result = []; + var wordStart = 0; + for (var i = 1, n = identifier.length; i < n; i++) { + var lastIsDigit = isDigit(identifier.charCodeAt(i - 1)); + var currentIsDigit = isDigit(identifier.charCodeAt(i)); + var hasTransitionFromLowerToUpper = transitionFromLowerToUpper(identifier, word, i); + var hasTransitionFromUpperToLower = transitionFromUpperToLower(identifier, word, i, wordStart); + if (charIsPunctuation(identifier.charCodeAt(i - 1)) || + charIsPunctuation(identifier.charCodeAt(i)) || + lastIsDigit !== currentIsDigit || + hasTransitionFromLowerToUpper || + hasTransitionFromUpperToLower) { + if (!isAllPunctuation(identifier, wordStart, i)) { + result.push(ts.createTextSpan(wordStart, i - wordStart)); + } + wordStart = i; + } + } + if (!isAllPunctuation(identifier, wordStart, identifier.length)) { + result.push(ts.createTextSpan(wordStart, identifier.length - wordStart)); + } + return result; + } + function charIsPunctuation(ch) { + switch (ch) { + case 33 /* exclamation */: + case 34 /* doubleQuote */: + case 35 /* hash */: + case 37 /* percent */: + case 38 /* ampersand */: + case 39 /* singleQuote */: + case 40 /* openParen */: + case 41 /* closeParen */: + case 42 /* asterisk */: + case 44 /* comma */: + case 45 /* minus */: + case 46 /* dot */: + case 47 /* slash */: + case 58 /* colon */: + case 59 /* semicolon */: + case 63 /* question */: + case 64 /* at */: + case 91 /* openBracket */: + case 92 /* backslash */: + case 93 /* closeBracket */: + case 95 /* _ */: + case 123 /* openBrace */: + case 125 /* closeBrace */: + return true; + } + return false; + } + function isAllPunctuation(identifier, start, end) { + for (var i = start; i < end; i++) { + var ch = identifier.charCodeAt(i); + // We don't consider _ or $ as punctuation as there may be things with that name. + if (!charIsPunctuation(ch) || ch === 95 /* _ */ || ch === 36 /* $ */) { + return false; + } + } + return true; + } + function transitionFromUpperToLower(identifier, word, index, wordStart) { + if (word) { + // Cases this supports: + // 1) IDisposable -> I, Disposable + // 2) UIElement -> UI, Element + // 3) HTMLDocument -> HTML, Document + // + // etc. + if (index !== wordStart && + index + 1 < identifier.length) { + var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); + var nextIsLower = isLowerCaseLetter(identifier.charCodeAt(index + 1)); + if (currentIsUpper && nextIsLower) { + // We have a transition from an upper to a lower letter here. But we only + // want to break if all the letters that preceded are uppercase. i.e. if we + // have "Foo" we don't want to break that into "F, oo". But if we have + // "IFoo" or "UIFoo", then we want to break that into "I, Foo" and "UI, + // Foo". i.e. the last uppercase letter belongs to the lowercase letters + // that follows. Note: this will make the following not split properly: + // "HELLOthere". However, these sorts of names do not show up in .Net + // programs. + for (var i = wordStart; i < index; i++) { + if (!isUpperCaseLetter(identifier.charCodeAt(i))) { + return false; + } + } + return true; + } + } + } + return false; + } + function transitionFromLowerToUpper(identifier, word, index) { + var lastIsUpper = isUpperCaseLetter(identifier.charCodeAt(index - 1)); + var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); + // See if the casing indicates we're starting a new word. Note: if we're breaking on + // words, then just seeing an upper case character isn't enough. Instead, it has to + // be uppercase and the previous character can't be uppercase. + // + // For example, breaking "AddMetadata" on words would make: Add Metadata + // + // on characters would be: A dd M etadata + // + // Break "AM" on words would be: AM + // + // on characters would be: A M + // + // We break the search string on characters. But we break the symbol name on words. + var transition = word + ? (currentIsUpper && !lastIsUpper) + : currentIsUpper; + return transition; + } +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + var SignatureHelp; + (function (SignatureHelp) { + // A partially written generic type expression is not guaranteed to have the correct syntax tree. the expression could be parsed as less than/greater than expression or a comma expression + // or some other combination depending on what the user has typed so far. For the purposes of signature help we need to consider any location after "<" as a possible generic type reference. + // To do this, the method will back parse the expression starting at the position required. it will try to parse the current expression as a generic type expression, if it did succeed it + // will return the generic identifier that started the expression (e.g. "foo" in "foo(#a, b) -> The token introduces a list, and should begin a sig help session + // Case 2: + // fo#o#(a, b)# -> The token is either not associated with a list, or ends a list, so the session should end + // Case 3: + // foo(a#, #b#) -> The token is buried inside a list, and should give sig help + // Find out if 'node' is an argument, a type argument, or neither + if (node.kind === 25 /* LessThanToken */ || + node.kind === 17 /* OpenParenToken */) { + // Find the list that starts right *after* the < or ( token. + // If the user has just opened a list, consider this item 0. + var list = getChildListThatStartsWithOpenerToken(callExpression, node, sourceFile); + var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; + ts.Debug.assert(list !== undefined); + return { + kind: isTypeArgList ? 0 /* TypeArguments */ : 1 /* CallArguments */, + invocation: callExpression, + argumentsSpan: getApplicableSpanForArguments(list), + argumentIndex: 0, + argumentCount: getArgumentCount(list) + }; + } + // findListItemInfo can return undefined if we are not in parent's argument list + // or type argument list. This includes cases where the cursor is: + // - To the right of the closing paren, non-substitution template, or template tail. + // - Between the type arguments and the arguments (greater than token) + // - On the target of the call (parent.func) + // - On the 'new' keyword in a 'new' expression + var listItemInfo = ts.findListItemInfo(node); + if (listItemInfo) { + var list = listItemInfo.list; + var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; + var argumentIndex = getArgumentIndex(list, node); + var argumentCount = getArgumentCount(list); + ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); + return { + kind: isTypeArgList ? 0 /* TypeArguments */ : 1 /* CallArguments */, + invocation: callExpression, + argumentsSpan: getApplicableSpanForArguments(list), + argumentIndex: argumentIndex, + argumentCount: argumentCount + }; + } + } + else if (node.kind === 11 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 170 /* TaggedTemplateExpression */) { + // Check if we're actually inside the template; + // otherwise we'll fall out and return undefined. + if (ts.isInsideTemplateLiteral(node, position)) { + return getArgumentListInfoForTemplate(node.parent, /*argumentIndex*/ 0); + } + } + else if (node.kind === 12 /* TemplateHead */ && node.parent.parent.kind === 170 /* TaggedTemplateExpression */) { + var templateExpression = node.parent; + var tagExpression = templateExpression.parent; + ts.Debug.assert(templateExpression.kind === 183 /* TemplateExpression */); + var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; + return getArgumentListInfoForTemplate(tagExpression, argumentIndex); + } + else if (node.parent.kind === 190 /* TemplateSpan */ && node.parent.parent.parent.kind === 170 /* TaggedTemplateExpression */) { + var templateSpan = node.parent; + var templateExpression = templateSpan.parent; + var tagExpression = templateExpression.parent; + ts.Debug.assert(templateExpression.kind === 183 /* TemplateExpression */); + // If we're just after a template tail, don't show signature help. + if (node.kind === 14 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) { + return undefined; + } + var spanIndex = templateExpression.templateSpans.indexOf(templateSpan); + var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node); + return getArgumentListInfoForTemplate(tagExpression, argumentIndex); + } + return undefined; + } + function getArgumentIndex(argumentsList, node) { + // The list we got back can include commas. In the presence of errors it may + // also just have nodes without commas. For example "Foo(a b c)" will have 3 + // args without commas. We want to find what index we're at. So we count + // forward until we hit ourselves, only incrementing the index if it isn't a + // comma. + // + // Note: the subtlety around trailing commas (in getArgumentCount) does not apply + // here. That's because we're only walking forward until we hit the node we're + // on. In that case, even if we're after the trailing comma, we'll still see + // that trailing comma in the list, and we'll have generated the appropriate + // arg index. + var argumentIndex = 0; + var listChildren = argumentsList.getChildren(); + for (var _i = 0; _i < listChildren.length; _i++) { + var child = listChildren[_i]; + if (child === node) { + break; + } + if (child.kind !== 24 /* CommaToken */) { + argumentIndex++; + } + } + return argumentIndex; + } + function getArgumentCount(argumentsList) { + // The argument count for a list is normally the number of non-comma children it has. + // For example, if you have "Foo(a,b)" then there will be three children of the arg + // list 'a' '' 'b'. So, in this case the arg count will be 2. However, there + // is a small subtlety. If you have "Foo(a,)", then the child list will just have + // 'a' ''. So, in the case where the last child is a comma, we increase the + // arg count by one to compensate. + // + // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then + // we'll have: 'a' '' '' + // That will give us 2 non-commas. We then add one for the last comma, givin us an + // arg count of 3. + var listChildren = argumentsList.getChildren(); + var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 24 /* CommaToken */; }); + if (listChildren.length > 0 && ts.lastOrUndefined(listChildren).kind === 24 /* CommaToken */) { + argumentCount++; + } + return argumentCount; + } + // spanIndex is either the index for a given template span. + // This does not give appropriate results for a NoSubstitutionTemplateLiteral + function getArgumentIndexForTemplatePiece(spanIndex, node) { + // Because the TemplateStringsArray is the first argument, we have to offset each substitution expression by 1. + // There are three cases we can encounter: + // 1. We are precisely in the template literal (argIndex = 0). + // 2. We are in or to the right of the substitution expression (argIndex = spanIndex + 1). + // 3. We are directly to the right of the template literal, but because we look for the token on the left, + // not enough to put us in the substitution expression; we should consider ourselves part of + // the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1). + // + // Example: f `# abcd $#{# 1 + 1# }# efghi ${ #"#hello"# } # ` + // ^ ^ ^ ^ ^ ^ ^ ^ ^ + // Case: 1 1 3 2 1 3 2 2 1 + ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); + if (ts.isTemplateLiteralKind(node.kind)) { + if (ts.isInsideTemplateLiteral(node, position)) { + return 0; + } + return spanIndex + 2; + } + return spanIndex + 1; + } + function getArgumentListInfoForTemplate(tagExpression, argumentIndex) { + // argumentCount is either 1 or (numSpans + 1) to account for the template strings array argument. + var argumentCount = tagExpression.template.kind === 11 /* NoSubstitutionTemplateLiteral */ + ? 1 + : tagExpression.template.templateSpans.length + 1; + ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); + return { + kind: 2 /* TaggedTemplateArguments */, + invocation: tagExpression, + argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression), + argumentIndex: argumentIndex, + argumentCount: argumentCount + }; + } + function getApplicableSpanForArguments(argumentsList) { + // We use full start and skip trivia on the end because we want to include trivia on + // both sides. For example, + // + // foo( /*comment */ a, b, c /*comment*/ ) + // | | + // + // The applicable span is from the first bar to the second bar (inclusive, + // but not including parentheses) + var applicableSpanStart = argumentsList.getFullStart(); + var applicableSpanEnd = ts.skipTrivia(sourceFile.text, argumentsList.getEnd(), /*stopAfterLineBreak*/ false); + return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); + } + function getApplicableSpanForTaggedTemplate(taggedTemplate) { + var template = taggedTemplate.template; + var applicableSpanStart = template.getStart(); + var applicableSpanEnd = template.getEnd(); + // We need to adjust the end position for the case where the template does not have a tail. + // Otherwise, we will not show signature help past the expression. + // For example, + // + // ` ${ 1 + 1 foo(10) + // | | + // + // This is because a Missing node has no width. However, what we actually want is to include trivia + // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. + if (template.kind === 183 /* TemplateExpression */) { + var lastSpan = ts.lastOrUndefined(template.templateSpans); + if (lastSpan.literal.getFullWidth() === 0) { + applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); + } + } + return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); + } + function getContainingArgumentInfo(node) { + for (var n = node; n.kind !== 248 /* SourceFile */; n = n.parent) { + if (ts.isFunctionBlock(n)) { + return undefined; + } + // If the node is not a subspan of its parent, this is a big problem. + // There have been crashes that might be caused by this violation. + if (n.pos < n.parent.pos || n.end > n.parent.end) { + ts.Debug.fail("Node of kind " + n.kind + " is not a subspan of its parent of kind " + n.parent.kind); + } + var argumentInfo_1 = getImmediatelyContainingArgumentInfo(n); + if (argumentInfo_1) { + return argumentInfo_1; + } + } + return undefined; + } + function getChildListThatStartsWithOpenerToken(parent, openerToken, sourceFile) { + var children = parent.getChildren(sourceFile); + var indexOfOpenerToken = children.indexOf(openerToken); + ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); + return children[indexOfOpenerToken + 1]; + } + /** + * The selectedItemIndex could be negative for several reasons. + * 1. There are too many arguments for all of the overloads + * 2. None of the overloads were type compatible + * The solution here is to try to pick the best overload by picking + * either the first one that has an appropriate number of parameters, + * or the one with the most parameters. + */ + function selectBestInvalidOverloadIndex(candidates, argumentCount) { + var maxParamsSignatureIndex = -1; + var maxParams = -1; + for (var i = 0; i < candidates.length; i++) { + var candidate = candidates[i]; + if (candidate.hasRestParameter || candidate.parameters.length >= argumentCount) { + return i; + } + if (candidate.parameters.length > maxParams) { + maxParams = candidate.parameters.length; + maxParamsSignatureIndex = i; + } + } + return maxParamsSignatureIndex; + } + function createSignatureHelpItems(candidates, bestSignature, argumentListInfo) { + var applicableSpan = argumentListInfo.argumentsSpan; + var isTypeParameterList = argumentListInfo.kind === 0 /* TypeArguments */; + var invocation = argumentListInfo.invocation; + var callTarget = ts.getInvokedExpression(invocation); + var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); + var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); + var items = ts.map(candidates, function (candidateSignature) { + var signatureHelpParameters; + var prefixDisplayParts = []; + var suffixDisplayParts = []; + if (callTargetDisplayParts) { + ts.addRange(prefixDisplayParts, callTargetDisplayParts); + } + if (isTypeParameterList) { + prefixDisplayParts.push(ts.punctuationPart(25 /* LessThanToken */)); + var typeParameters = candidateSignature.typeParameters; + signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray; + suffixDisplayParts.push(ts.punctuationPart(27 /* GreaterThanToken */)); + var parameterParts = ts.mapToDisplayParts(function (writer) { + return typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.parameters, writer, invocation); + }); + ts.addRange(suffixDisplayParts, parameterParts); + } + else { + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + return typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation); + }); + ts.addRange(prefixDisplayParts, typeParameterParts); + prefixDisplayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + var parameters = candidateSignature.parameters; + signatureHelpParameters = parameters.length > 0 ? ts.map(parameters, createSignatureHelpParameterForParameter) : emptyArray; + suffixDisplayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + } + var returnTypeParts = ts.mapToDisplayParts(function (writer) { + return typeChecker.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation); + }); + ts.addRange(suffixDisplayParts, returnTypeParts); + return { + isVariadic: candidateSignature.hasRestParameter, + prefixDisplayParts: prefixDisplayParts, + suffixDisplayParts: suffixDisplayParts, + separatorDisplayParts: [ts.punctuationPart(24 /* CommaToken */), ts.spacePart()], + parameters: signatureHelpParameters, + documentation: candidateSignature.getDocumentationComment() + }; + }); + var argumentIndex = argumentListInfo.argumentIndex; + // argumentCount is the *apparent* number of arguments. + var argumentCount = argumentListInfo.argumentCount; + var selectedItemIndex = candidates.indexOf(bestSignature); + if (selectedItemIndex < 0) { + selectedItemIndex = selectBestInvalidOverloadIndex(candidates, argumentCount); + } + ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); + return { + items: items, + applicableSpan: applicableSpan, + selectedItemIndex: selectedItemIndex, + argumentIndex: argumentIndex, + argumentCount: argumentCount + }; + function createSignatureHelpParameterForParameter(parameter) { + var displayParts = ts.mapToDisplayParts(function (writer) { + return typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation); + }); + return { + name: parameter.name, + documentation: parameter.getDocumentationComment(), + displayParts: displayParts, + isOptional: typeChecker.isOptionalParameter(parameter.valueDeclaration) + }; + } + function createSignatureHelpParameterForTypeParameter(typeParameter) { + var displayParts = ts.mapToDisplayParts(function (writer) { + return typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(typeParameter, writer, invocation); + }); + return { + name: typeParameter.symbol.name, + documentation: emptyArray, + displayParts: displayParts, + isOptional: false + }; + } + } + } + SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; + })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); +})(ts || (ts = {})); +// These utilities are common to multiple language service features. +/* @internal */ +var ts; +(function (ts) { + function getEndLinePosition(line, sourceFile) { + ts.Debug.assert(line >= 0); + var lineStarts = sourceFile.getLineStarts(); + var lineIndex = line; + if (lineIndex + 1 === lineStarts.length) { + // last line - return EOF + return sourceFile.text.length - 1; + } + else { + // current line start + var start = lineStarts[lineIndex]; + // take the start position of the next line -1 = it should be some line break + var pos = lineStarts[lineIndex + 1] - 1; + ts.Debug.assert(ts.isLineBreak(sourceFile.text.charCodeAt(pos))); + // walk backwards skipping line breaks, stop the the beginning of current line. + // i.e: + // + // $ <- end of line for this position should match the start position + while (start <= pos && ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { + pos--; + } + return pos; + } + } + ts.getEndLinePosition = getEndLinePosition; + function getLineStartPositionForPosition(position, sourceFile) { + var lineStarts = sourceFile.getLineStarts(); + var line = sourceFile.getLineAndCharacterOfPosition(position).line; + return lineStarts[line]; + } + ts.getLineStartPositionForPosition = getLineStartPositionForPosition; + function rangeContainsRange(r1, r2) { + return startEndContainsRange(r1.pos, r1.end, r2); + } + ts.rangeContainsRange = rangeContainsRange; + function startEndContainsRange(start, end, range) { + return start <= range.pos && end >= range.end; + } + ts.startEndContainsRange = startEndContainsRange; + function rangeContainsStartEnd(range, start, end) { + return range.pos <= start && range.end >= end; + } + ts.rangeContainsStartEnd = rangeContainsStartEnd; + function rangeOverlapsWithStartEnd(r1, start, end) { + return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end); + } + ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd; + function startEndOverlapsWithStartEnd(start1, end1, start2, end2) { + var start = Math.max(start1, start2); + var end = Math.min(end1, end2); + return start < end; + } + ts.startEndOverlapsWithStartEnd = startEndOverlapsWithStartEnd; + function positionBelongsToNode(candidate, position, sourceFile) { + return candidate.end > position || !isCompletedNode(candidate, sourceFile); + } + ts.positionBelongsToNode = positionBelongsToNode; + function isCompletedNode(n, sourceFile) { + if (ts.nodeIsMissing(n)) { + return false; + } + switch (n.kind) { + case 214 /* ClassDeclaration */: + case 215 /* InterfaceDeclaration */: + case 217 /* EnumDeclaration */: + case 165 /* ObjectLiteralExpression */: + case 161 /* ObjectBindingPattern */: + case 155 /* TypeLiteral */: + case 192 /* Block */: + case 219 /* ModuleBlock */: + case 220 /* CaseBlock */: + return nodeEndsWith(n, 16 /* CloseBraceToken */, sourceFile); + case 244 /* CatchClause */: + return isCompletedNode(n.block, sourceFile); + case 169 /* NewExpression */: + if (!n.arguments) { + return true; + } + // fall through + case 168 /* CallExpression */: + case 172 /* ParenthesizedExpression */: + case 160 /* ParenthesizedType */: + return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); + case 152 /* FunctionType */: + case 153 /* ConstructorType */: + return isCompletedNode(n.type, sourceFile); + case 144 /* Constructor */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 213 /* FunctionDeclaration */: + case 173 /* FunctionExpression */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 148 /* ConstructSignature */: + case 147 /* CallSignature */: + case 174 /* ArrowFunction */: + if (n.body) { + return isCompletedNode(n.body, sourceFile); + } + if (n.type) { + return isCompletedNode(n.type, sourceFile); + } + // Even though type parameters can be unclosed, we can get away with + // having at least a closing paren. + return hasChildOfKind(n, 18 /* CloseParenToken */, sourceFile); + case 218 /* ModuleDeclaration */: + return n.body && isCompletedNode(n.body, sourceFile); + case 196 /* IfStatement */: + if (n.elseStatement) { + return isCompletedNode(n.elseStatement, sourceFile); + } + return isCompletedNode(n.thenStatement, sourceFile); + case 195 /* ExpressionStatement */: + return isCompletedNode(n.expression, sourceFile) || + hasChildOfKind(n, 23 /* SemicolonToken */); + case 164 /* ArrayLiteralExpression */: + case 162 /* ArrayBindingPattern */: + case 167 /* ElementAccessExpression */: + case 136 /* ComputedPropertyName */: + case 157 /* TupleType */: + return nodeEndsWith(n, 20 /* CloseBracketToken */, sourceFile); + case 149 /* IndexSignature */: + if (n.type) { + return isCompletedNode(n.type, sourceFile); + } + return hasChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); + case 241 /* CaseClause */: + case 242 /* DefaultClause */: + // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicitly always consider them non-completed + return false; + case 199 /* ForStatement */: + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + case 198 /* WhileStatement */: + return isCompletedNode(n.statement, sourceFile); + case 197 /* DoStatement */: + // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; + var hasWhileKeyword = findChildOfKind(n, 104 /* WhileKeyword */, sourceFile); + if (hasWhileKeyword) { + return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); + } + return isCompletedNode(n.statement, sourceFile); + case 154 /* TypeQuery */: + return isCompletedNode(n.exprName, sourceFile); + case 176 /* TypeOfExpression */: + case 175 /* DeleteExpression */: + case 177 /* VoidExpression */: + case 184 /* YieldExpression */: + case 185 /* SpreadElementExpression */: + var unaryWordExpression = n; + return isCompletedNode(unaryWordExpression.expression, sourceFile); + case 170 /* TaggedTemplateExpression */: + return isCompletedNode(n.template, sourceFile); + case 183 /* TemplateExpression */: + var lastSpan = ts.lastOrUndefined(n.templateSpans); + return isCompletedNode(lastSpan, sourceFile); + case 190 /* TemplateSpan */: + return ts.nodeIsPresent(n.literal); + case 179 /* PrefixUnaryExpression */: + return isCompletedNode(n.operand, sourceFile); + case 181 /* BinaryExpression */: + return isCompletedNode(n.right, sourceFile); + case 182 /* ConditionalExpression */: + return isCompletedNode(n.whenFalse, sourceFile); + default: + return true; + } + } + ts.isCompletedNode = isCompletedNode; + /* + * Checks if node ends with 'expectedLastToken'. + * If child at position 'length - 1' is 'SemicolonToken' it is skipped and 'expectedLastToken' is compared with child at position 'length - 2'. + */ + function nodeEndsWith(n, expectedLastToken, sourceFile) { + var children = n.getChildren(sourceFile); + if (children.length) { + var last = ts.lastOrUndefined(children); + if (last.kind === expectedLastToken) { + return true; + } + else if (last.kind === 23 /* SemicolonToken */ && children.length !== 1) { + return children[children.length - 2].kind === expectedLastToken; + } + } + return false; + } + function findListItemInfo(node) { + var list = findContainingList(node); + // It is possible at this point for syntaxList to be undefined, either if + // node.parent had no list child, or if none of its list children contained + // the span of node. If this happens, return undefined. The caller should + // handle this case. + if (!list) { + return undefined; + } + var children = list.getChildren(); + var listItemIndex = ts.indexOf(children, node); + return { + listItemIndex: listItemIndex, + list: list + }; + } + ts.findListItemInfo = findListItemInfo; + function hasChildOfKind(n, kind, sourceFile) { + return !!findChildOfKind(n, kind, sourceFile); + } + ts.hasChildOfKind = hasChildOfKind; + function findChildOfKind(n, kind, sourceFile) { + return ts.forEach(n.getChildren(sourceFile), function (c) { return c.kind === kind && c; }); + } + ts.findChildOfKind = findChildOfKind; + function findContainingList(node) { + // The node might be a list element (nonsynthetic) or a comma (synthetic). Either way, it will + // be parented by the container of the SyntaxList, not the SyntaxList itself. + // In order to find the list item index, we first need to locate SyntaxList itself and then search + // for the position of the relevant node (or comma). + var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { + // find syntax list that covers the span of the node + if (c.kind === 271 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { + return c; + } + }); + // Either we didn't find an appropriate list, or the list must contain us. + ts.Debug.assert(!syntaxList || ts.contains(syntaxList.getChildren(), node)); + return syntaxList; + } + ts.findContainingList = findContainingList; + /* Gets the token whose text has range [start, end) and + * position >= start and (position < end or (position === end && token is keyword or identifier)) + */ + function getTouchingWord(sourceFile, position) { + return getTouchingToken(sourceFile, position, function (n) { return isWord(n.kind); }); + } + ts.getTouchingWord = getTouchingWord; + /* Gets the token whose text has range [start, end) and position >= start + * and (position < end or (position === end && token is keyword or identifier or numeric\string litera)) + */ + function getTouchingPropertyName(sourceFile, position) { + return getTouchingToken(sourceFile, position, function (n) { return isPropertyName(n.kind); }); + } + ts.getTouchingPropertyName = getTouchingPropertyName; + /** Returns the token if position is in [start, end) or if position === end and includeItemAtEndPosition(token) === true */ + function getTouchingToken(sourceFile, position, includeItemAtEndPosition) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includeItemAtEndPosition); + } + ts.getTouchingToken = getTouchingToken; + /** Returns a token if position is in [start-of-leading-trivia, end) */ + function getTokenAtPosition(sourceFile, position) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includeItemAtEndPosition*/ undefined); + } + ts.getTokenAtPosition = getTokenAtPosition; + /** Get the token whose text contains the position */ + function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition) { + var current = sourceFile; + outer: while (true) { + if (isToken(current)) { + // exit early + return current; + } + // find the child that contains 'position' + for (var i = 0, n = current.getChildCount(sourceFile); i < n; i++) { + var child = current.getChildAt(i); + var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile); + if (start <= position) { + var end = child.getEnd(); + if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { + current = child; + continue outer; + } + else if (includeItemAtEndPosition && end === position) { + var previousToken = findPrecedingToken(position, sourceFile, child); + if (previousToken && includeItemAtEndPosition(previousToken)) { + return previousToken; + } + } + } + } + return current; + } + } + /** + * The token on the left of the position is the token that strictly includes the position + * or sits to the left of the cursor if it is on a boundary. For example + * + * fo|o -> will return foo + * foo |bar -> will return foo + * + */ + function findTokenOnLeftOfPosition(file, position) { + // Ideally, getTokenAtPosition should return a token. However, it is currently + // broken, so we do a check to make sure the result was indeed a token. + var tokenAtPosition = getTokenAtPosition(file, position); + if (isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { + return tokenAtPosition; + } + return findPrecedingToken(position, file); + } + ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition; + function findNextToken(previousToken, parent) { + return find(parent); + function find(n) { + if (isToken(n) && n.pos === previousToken.end) { + // this is token that starts at the end of previous token - return it + return n; + } + var children = n.getChildren(); + for (var _i = 0; _i < children.length; _i++) { + var child = children[_i]; + var shouldDiveInChildNode = + // previous token is enclosed somewhere in the child + (child.pos <= previousToken.pos && child.end > previousToken.end) || + // previous token ends exactly at the beginning of child + (child.pos === previousToken.end); + if (shouldDiveInChildNode && nodeHasTokens(child)) { + return find(child); + } + } + return undefined; + } + } + ts.findNextToken = findNextToken; + function findPrecedingToken(position, sourceFile, startNode) { + return find(startNode || sourceFile); + function findRightmostToken(n) { + if (isToken(n) || n.kind === 236 /* JsxText */) { + return n; + } + var children = n.getChildren(); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + return candidate && findRightmostToken(candidate); + } + function find(n) { + if (isToken(n) || n.kind === 236 /* JsxText */) { + return n; + } + var children = n.getChildren(); + for (var i = 0, len = children.length; i < len; i++) { + var child = children[i]; + // condition 'position < child.end' checks if child node end after the position + // in the example below this condition will be false for 'aaaa' and 'bbbb' and true for 'ccc' + // aaaa___bbbb___$__ccc + // after we found child node with end after the position we check if start of the node is after the position. + // if yes - then position is in the trivia and we need to look into the previous child to find the token in question. + // if no - position is in the node itself so we should recurse in it. + // NOTE: JsxText is a weird kind of node that can contain only whitespaces (since they are not counted as trivia). + // if this is the case - then we should assume that token in question is located in previous child. + if (position < child.end && (nodeHasTokens(child) || child.kind === 236 /* JsxText */)) { + var start = child.getStart(sourceFile); + var lookInPreviousChild = (start >= position) || + (child.kind === 236 /* JsxText */ && start === child.end); // whitespace only JsxText + if (lookInPreviousChild) { + // actual start of the node is past the position - previous token should be at the end of previous child + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i); + return candidate && findRightmostToken(candidate); + } + else { + // candidate should be in this node + return find(child); + } + } + } + ts.Debug.assert(startNode !== undefined || n.kind === 248 /* SourceFile */); + // Here we know that none of child token nodes embrace the position, + // the only known case is when position is at the end of the file. + // Try to find the rightmost token in the file without filtering. + // Namely we are skipping the check: 'position < node.end' + if (children.length) { + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + return candidate && findRightmostToken(candidate); + } + } + /// finds last node that is considered as candidate for search (isCandidate(node) === true) starting from 'exclusiveStartPosition' + function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) { + for (var i = exclusiveStartPosition - 1; i >= 0; --i) { + if (nodeHasTokens(children[i])) { + return children[i]; + } + } + } + } + ts.findPrecedingToken = findPrecedingToken; + function isInString(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + return token && token.kind === 9 /* StringLiteral */ && position > token.getStart(); + } + ts.isInString = isInString; + function isInComment(sourceFile, position) { + return isInCommentHelper(sourceFile, position, /*predicate*/ undefined); + } + ts.isInComment = isInComment; + /** + * Returns true if the cursor at position in sourceFile is within a comment that additionally + * satisfies predicate, and false otherwise. + */ + function isInCommentHelper(sourceFile, position, predicate) { + var token = getTokenAtPosition(sourceFile, position); + if (token && position <= token.getStart()) { + var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + // The end marker of a single-line comment does not include the newline character. + // In the following case, we are inside a comment (^ denotes the cursor position): + // + // // asdf ^\n + // + // But for multi-line comments, we don't want to be inside the comment in the following case: + // + // /* asdf */^ + // + // Internally, we represent the end of the comment at the newline and closing '/', respectively. + return predicate ? + ts.forEach(commentRanges, function (c) { return c.pos < position && + (c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end) && + predicate(c); }) : + ts.forEach(commentRanges, function (c) { return c.pos < position && + (c.kind == 2 /* SingleLineCommentTrivia */ ? position <= c.end : position < c.end); }); + } + return false; + } + ts.isInCommentHelper = isInCommentHelper; + function hasDocComment(sourceFile, position) { + var token = getTokenAtPosition(sourceFile, position); + // First, we have to see if this position actually landed in a comment. + var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); + return ts.forEach(commentRanges, jsDocPrefix); + function jsDocPrefix(c) { + var text = sourceFile.text; + return text.length >= c.pos + 3 && text[c.pos] === '/' && text[c.pos + 1] === '*' && text[c.pos + 2] === '*'; + } + } + ts.hasDocComment = hasDocComment; + /** + * Get the corresponding JSDocTag node if the position is in a jsDoc comment + */ + function getJsDocTagAtPosition(sourceFile, position) { + var node = ts.getTokenAtPosition(sourceFile, position); + if (isToken(node)) { + switch (node.kind) { + case 102 /* VarKeyword */: + case 108 /* LetKeyword */: + case 74 /* ConstKeyword */: + // if the current token is var, let or const, skip the VariableDeclarationList + node = node.parent === undefined ? undefined : node.parent.parent; + break; + default: + node = node.parent; + break; + } + } + if (node) { + var jsDocComment = node.jsDocComment; + if (jsDocComment) { + for (var _i = 0, _a = jsDocComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.pos <= position && position <= tag.end) { + return tag; + } + } + } + } + return undefined; + } + ts.getJsDocTagAtPosition = getJsDocTagAtPosition; + function nodeHasTokens(n) { + // If we have a token or node that has a non-zero width, it must have tokens. + // Note, that getWidth() does not take trivia into account. + return n.getWidth() !== 0; + } + function getNodeModifiers(node) { + var flags = ts.getCombinedNodeFlags(node); + var result = []; + if (flags & 32 /* Private */) + result.push(ts.ScriptElementKindModifier.privateMemberModifier); + if (flags & 64 /* Protected */) + result.push(ts.ScriptElementKindModifier.protectedMemberModifier); + if (flags & 16 /* Public */) + result.push(ts.ScriptElementKindModifier.publicMemberModifier); + if (flags & 128 /* Static */) + result.push(ts.ScriptElementKindModifier.staticModifier); + if (flags & 256 /* Abstract */) + result.push(ts.ScriptElementKindModifier.abstractModifier); + if (flags & 1 /* Export */) + result.push(ts.ScriptElementKindModifier.exportedModifier); + if (ts.isInAmbientContext(node)) + result.push(ts.ScriptElementKindModifier.ambientModifier); + return result.length > 0 ? result.join(',') : ts.ScriptElementKindModifier.none; + } + ts.getNodeModifiers = getNodeModifiers; + function getTypeArgumentOrTypeParameterList(node) { + if (node.kind === 151 /* TypeReference */ || node.kind === 168 /* CallExpression */) { + return node.typeArguments; + } + if (ts.isFunctionLike(node) || node.kind === 214 /* ClassDeclaration */ || node.kind === 215 /* InterfaceDeclaration */) { + return node.typeParameters; + } + return undefined; + } + ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; + function isToken(n) { + return n.kind >= 0 /* FirstToken */ && n.kind <= 134 /* LastToken */; + } + ts.isToken = isToken; + function isWord(kind) { + return kind === 69 /* Identifier */ || ts.isKeyword(kind); + } + ts.isWord = isWord; + function isPropertyName(kind) { + return kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */ || isWord(kind); + } + function isComment(kind) { + return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */; + } + ts.isComment = isComment; + function isStringOrRegularExpressionOrTemplateLiteral(kind) { + if (kind === 9 /* StringLiteral */ + || kind === 10 /* RegularExpressionLiteral */ + || ts.isTemplateLiteralKind(kind)) { + return true; + } + return false; + } + ts.isStringOrRegularExpressionOrTemplateLiteral = isStringOrRegularExpressionOrTemplateLiteral; + function isPunctuation(kind) { + return 15 /* FirstPunctuation */ <= kind && kind <= 68 /* LastPunctuation */; + } + ts.isPunctuation = isPunctuation; + function isInsideTemplateLiteral(node, position) { + return ts.isTemplateLiteralKind(node.kind) + && (node.getStart() < position && position < node.getEnd()) || (!!node.isUnterminated && position === node.getEnd()); + } + ts.isInsideTemplateLiteral = isInsideTemplateLiteral; + function isAccessibilityModifier(kind) { + switch (kind) { + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + return true; + } + return false; + } + ts.isAccessibilityModifier = isAccessibilityModifier; + function compareDataObjects(dst, src) { + for (var e in dst) { + if (typeof dst[e] === "object") { + if (!compareDataObjects(dst[e], src[e])) { + return false; + } + } + else if (typeof dst[e] !== "function") { + if (dst[e] !== src[e]) { + return false; + } + } + } + return true; + } + ts.compareDataObjects = compareDataObjects; +})(ts || (ts = {})); +// Display-part writer helpers +/* @internal */ +var ts; +(function (ts) { + function isFirstDeclarationOfSymbolParameter(symbol) { + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 138 /* Parameter */; + } + ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; + var displayPartWriter = getDisplayPartWriter(); + function getDisplayPartWriter() { + var displayParts; + var lineStart; + var indent; + resetWriter(); + return { + displayParts: function () { return displayParts; }, + writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, + writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, + writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, + writeSpace: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.space); }, + writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, + writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, + writeSymbol: writeSymbol, + writeLine: writeLine, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, + clear: resetWriter, + trackSymbol: function () { }, + reportInaccessibleThisError: function () { } + }; + function writeIndent() { + if (lineStart) { + var indentString = ts.getIndentString(indent); + if (indentString) { + displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space)); + } + lineStart = false; + } + } + function writeKind(text, kind) { + writeIndent(); + displayParts.push(displayPart(text, kind)); + } + function writeSymbol(text, symbol) { + writeIndent(); + displayParts.push(symbolPart(text, symbol)); + } + function writeLine() { + displayParts.push(lineBreakPart()); + lineStart = true; + } + function resetWriter() { + displayParts = []; + lineStart = true; + indent = 0; + } + } + function symbolPart(text, symbol) { + return displayPart(text, displayPartKind(symbol), symbol); + function displayPartKind(symbol) { + var flags = symbol.flags; + if (flags & 3 /* Variable */) { + return isFirstDeclarationOfSymbolParameter(symbol) ? ts.SymbolDisplayPartKind.parameterName : ts.SymbolDisplayPartKind.localName; + } + else if (flags & 4 /* Property */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 32768 /* GetAccessor */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 65536 /* SetAccessor */) { + return ts.SymbolDisplayPartKind.propertyName; + } + else if (flags & 8 /* EnumMember */) { + return ts.SymbolDisplayPartKind.enumMemberName; + } + else if (flags & 16 /* Function */) { + return ts.SymbolDisplayPartKind.functionName; + } + else if (flags & 32 /* Class */) { + return ts.SymbolDisplayPartKind.className; + } + else if (flags & 64 /* Interface */) { + return ts.SymbolDisplayPartKind.interfaceName; + } + else if (flags & 384 /* Enum */) { + return ts.SymbolDisplayPartKind.enumName; + } + else if (flags & 1536 /* Module */) { + return ts.SymbolDisplayPartKind.moduleName; + } + else if (flags & 8192 /* Method */) { + return ts.SymbolDisplayPartKind.methodName; + } + else if (flags & 262144 /* TypeParameter */) { + return ts.SymbolDisplayPartKind.typeParameterName; + } + else if (flags & 524288 /* TypeAlias */) { + return ts.SymbolDisplayPartKind.aliasName; + } + else if (flags & 8388608 /* Alias */) { + return ts.SymbolDisplayPartKind.aliasName; + } + return ts.SymbolDisplayPartKind.text; + } + } + ts.symbolPart = symbolPart; + function displayPart(text, kind, symbol) { + return { + text: text, + kind: ts.SymbolDisplayPartKind[kind] + }; + } + ts.displayPart = displayPart; + function spacePart() { + return displayPart(" ", ts.SymbolDisplayPartKind.space); + } + ts.spacePart = spacePart; + function keywordPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.keyword); + } + ts.keywordPart = keywordPart; + function punctuationPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.punctuation); + } + ts.punctuationPart = punctuationPart; + function operatorPart(kind) { + return displayPart(ts.tokenToString(kind), ts.SymbolDisplayPartKind.operator); + } + ts.operatorPart = operatorPart; + function textOrKeywordPart(text) { + var kind = ts.stringToToken(text); + return kind === undefined + ? textPart(text) + : keywordPart(kind); + } + ts.textOrKeywordPart = textOrKeywordPart; + function textPart(text) { + return displayPart(text, ts.SymbolDisplayPartKind.text); + } + ts.textPart = textPart; + var carriageReturnLineFeed = "\r\n"; + /** + * The default is CRLF. + */ + function getNewLineOrDefaultFromHost(host) { + return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed; + } + ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; + function lineBreakPart() { + return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); + } + ts.lineBreakPart = lineBreakPart; + function mapToDisplayParts(writeDisplayParts) { + writeDisplayParts(displayPartWriter); + var result = displayPartWriter.displayParts(); + displayPartWriter.clear(); + return result; + } + ts.mapToDisplayParts = mapToDisplayParts; + function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { + return mapToDisplayParts(function (writer) { + typechecker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + }); + } + ts.typeToDisplayParts = typeToDisplayParts; + function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { + return mapToDisplayParts(function (writer) { + typeChecker.getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags); + }); + } + ts.symbolToDisplayParts = symbolToDisplayParts; + function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { + return mapToDisplayParts(function (writer) { + typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + }); + } + ts.signatureToDisplayParts = signatureToDisplayParts; + function getDeclaredName(typeChecker, symbol, location) { + // If this is an export or import specifier it could have been renamed using the 'as' syntax. + // If so we want to search for whatever is under the cursor. + if (isImportOrExportSpecifierName(location)) { + return location.getText(); + } + // Try to get the local symbol if we're dealing with an 'export default' + // since that symbol has the "true" name. + var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); + var name = typeChecker.symbolToString(localExportDefaultSymbol || symbol); + return name; + } + ts.getDeclaredName = getDeclaredName; + function isImportOrExportSpecifierName(location) { + return location.parent && + (location.parent.kind === 226 /* ImportSpecifier */ || location.parent.kind === 230 /* ExportSpecifier */) && + location.parent.propertyName === location; + } + ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; + /** + * Strip off existed single quotes or double quotes from a given string + * + * @return non-quoted string + */ + function stripQuotes(name) { + var length = name.length; + if (length >= 2 && + name.charCodeAt(0) === name.charCodeAt(length - 1) && + (name.charCodeAt(0) === 34 /* doubleQuote */ || name.charCodeAt(0) === 39 /* singleQuote */)) { + return name.substring(1, length - 1); + } + ; + return name; + } + ts.stripQuotes = stripQuotes; +})(ts || (ts = {})); +/// +/// +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var standardScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */); + var jsxScanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */); + /** + * Scanner that is currently used for formatting + */ + var scanner; + var ScanAction; + (function (ScanAction) { + ScanAction[ScanAction["Scan"] = 0] = "Scan"; + ScanAction[ScanAction["RescanGreaterThanToken"] = 1] = "RescanGreaterThanToken"; + ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken"; + ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken"; + ScanAction[ScanAction["RescanJsxIdentifier"] = 4] = "RescanJsxIdentifier"; + })(ScanAction || (ScanAction = {})); + function getFormattingScanner(sourceFile, startPos, endPos) { + ts.Debug.assert(scanner === undefined); + scanner = sourceFile.languageVariant === 1 /* JSX */ ? jsxScanner : standardScanner; + scanner.setText(sourceFile.text); + scanner.setTextPos(startPos); + var wasNewLine = true; + var leadingTrivia; + var trailingTrivia; + var savedPos; + var lastScanAction; + var lastTokenInfo; + return { + advance: advance, + readTokenInfo: readTokenInfo, + isOnToken: isOnToken, + lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, + close: function () { + ts.Debug.assert(scanner !== undefined); + lastTokenInfo = undefined; + scanner.setText(undefined); + scanner = undefined; + } + }; + function advance() { + ts.Debug.assert(scanner !== undefined); + lastTokenInfo = undefined; + var isStarted = scanner.getStartPos() !== startPos; + if (isStarted) { + if (trailingTrivia) { + ts.Debug.assert(trailingTrivia.length !== 0); + wasNewLine = ts.lastOrUndefined(trailingTrivia).kind === 4 /* NewLineTrivia */; + } + else { + wasNewLine = false; + } + } + leadingTrivia = undefined; + trailingTrivia = undefined; + if (!isStarted) { + scanner.scan(); + } + var t; + var pos = scanner.getStartPos(); + // Read leading trivia and token + while (pos < endPos) { + var t_1 = scanner.getToken(); + if (!ts.isTrivia(t_1)) { + break; + } + // consume leading trivia + scanner.scan(); + var item = { + pos: pos, + end: scanner.getStartPos(), + kind: t_1 + }; + pos = scanner.getStartPos(); + if (!leadingTrivia) { + leadingTrivia = []; + } + leadingTrivia.push(item); + } + savedPos = scanner.getStartPos(); + } + function shouldRescanGreaterThanToken(node) { + if (node) { + switch (node.kind) { + case 29 /* GreaterThanEqualsToken */: + case 64 /* GreaterThanGreaterThanEqualsToken */: + case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 45 /* GreaterThanGreaterThanGreaterThanToken */: + case 44 /* GreaterThanGreaterThanToken */: + return true; + } + } + return false; + } + function shouldRescanJsxIdentifier(node) { + if (node.parent) { + switch (node.parent.kind) { + case 238 /* JsxAttribute */: + case 235 /* JsxOpeningElement */: + case 237 /* JsxClosingElement */: + case 234 /* JsxSelfClosingElement */: + return node.kind === 69 /* Identifier */; + } + } + return false; + } + function shouldRescanSlashToken(container) { + return container.kind === 10 /* RegularExpressionLiteral */; + } + function shouldRescanTemplateToken(container) { + return container.kind === 13 /* TemplateMiddle */ || + container.kind === 14 /* TemplateTail */; + } + function startsWithSlashToken(t) { + return t === 39 /* SlashToken */ || t === 61 /* SlashEqualsToken */; + } + function readTokenInfo(n) { + ts.Debug.assert(scanner !== undefined); + if (!isOnToken()) { + // scanner is not on the token (either advance was not called yet or scanner is already past the end position) + return { + leadingTrivia: leadingTrivia, + trailingTrivia: undefined, + token: undefined + }; + } + // normally scanner returns the smallest available token + // check the kind of context node to determine if scanner should have more greedy behavior and consume more text. + var expectedScanAction = shouldRescanGreaterThanToken(n) + ? 1 /* RescanGreaterThanToken */ + : shouldRescanSlashToken(n) + ? 2 /* RescanSlashToken */ + : shouldRescanTemplateToken(n) + ? 3 /* RescanTemplateToken */ + : shouldRescanJsxIdentifier(n) + ? 4 /* RescanJsxIdentifier */ + : 0 /* Scan */; + if (lastTokenInfo && expectedScanAction === lastScanAction) { + // readTokenInfo was called before with the same expected scan action. + // No need to re-scan text, return existing 'lastTokenInfo' + // it is ok to call fixTokenKind here since it does not affect + // what portion of text is consumed. In opposize rescanning can change it, + // i.e. for '>=' when originally scanner eats just one character + // and rescanning forces it to consume more. + return fixTokenKind(lastTokenInfo, n); + } + if (scanner.getStartPos() !== savedPos) { + ts.Debug.assert(lastTokenInfo !== undefined); + // readTokenInfo was called before but scan action differs - rescan text + scanner.setTextPos(savedPos); + scanner.scan(); + } + var currentToken = scanner.getToken(); + if (expectedScanAction === 1 /* RescanGreaterThanToken */ && currentToken === 27 /* GreaterThanToken */) { + currentToken = scanner.reScanGreaterToken(); + ts.Debug.assert(n.kind === currentToken); + lastScanAction = 1 /* RescanGreaterThanToken */; + } + else if (expectedScanAction === 2 /* RescanSlashToken */ && startsWithSlashToken(currentToken)) { + currentToken = scanner.reScanSlashToken(); + ts.Debug.assert(n.kind === currentToken); + lastScanAction = 2 /* RescanSlashToken */; + } + else if (expectedScanAction === 3 /* RescanTemplateToken */ && currentToken === 16 /* CloseBraceToken */) { + currentToken = scanner.reScanTemplateToken(); + lastScanAction = 3 /* RescanTemplateToken */; + } + else if (expectedScanAction === 4 /* RescanJsxIdentifier */ && currentToken === 69 /* Identifier */) { + currentToken = scanner.scanJsxIdentifier(); + lastScanAction = 4 /* RescanJsxIdentifier */; + } + else { + lastScanAction = 0 /* Scan */; + } + var token = { + pos: scanner.getStartPos(), + end: scanner.getTextPos(), + kind: currentToken + }; + // consume trailing trivia + if (trailingTrivia) { + trailingTrivia = undefined; + } + while (scanner.getStartPos() < endPos) { + currentToken = scanner.scan(); + if (!ts.isTrivia(currentToken)) { + break; + } + var trivia = { + pos: scanner.getStartPos(), + end: scanner.getTextPos(), + kind: currentToken + }; + if (!trailingTrivia) { + trailingTrivia = []; + } + trailingTrivia.push(trivia); + if (currentToken === 4 /* NewLineTrivia */) { + // move past new line + scanner.scan(); + break; + } + } + lastTokenInfo = { + leadingTrivia: leadingTrivia, + trailingTrivia: trailingTrivia, + token: token + }; + return fixTokenKind(lastTokenInfo, n); + } + function isOnToken() { + ts.Debug.assert(scanner !== undefined); + var current = (lastTokenInfo && lastTokenInfo.token.kind) || scanner.getToken(); + var startPos = (lastTokenInfo && lastTokenInfo.token.pos) || scanner.getStartPos(); + return startPos < endPos && current !== 1 /* EndOfFileToken */ && !ts.isTrivia(current); + } + // when containing node in the tree is token + // but its kind differs from the kind that was returned by the scanner, + // then kind needs to be fixed. This might happen in cases + // when parser interprets token differently, i.e keyword treated as identifier + function fixTokenKind(tokenInfo, container) { + if (ts.isToken(container) && tokenInfo.token.kind !== container.kind) { + tokenInfo.token.kind = container.kind; + } + return tokenInfo; + } + } + formatting.getFormattingScanner = getFormattingScanner; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var FormattingContext = (function () { + function FormattingContext(sourceFile, formattingRequestKind) { + this.sourceFile = sourceFile; + this.formattingRequestKind = formattingRequestKind; + } + FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { + ts.Debug.assert(currentRange !== undefined, "currentTokenSpan is null"); + ts.Debug.assert(currentTokenParent !== undefined, "currentTokenParent is null"); + ts.Debug.assert(nextRange !== undefined, "nextTokenSpan is null"); + ts.Debug.assert(nextTokenParent !== undefined, "nextTokenParent is null"); + ts.Debug.assert(commonParent !== undefined, "commonParent is null"); + this.currentTokenSpan = currentRange; + this.currentTokenParent = currentTokenParent; + this.nextTokenSpan = nextRange; + this.nextTokenParent = nextTokenParent; + this.contextNode = commonParent; + // drop cached results + this.contextNodeAllOnSameLine = undefined; + this.nextNodeAllOnSameLine = undefined; + this.tokensAreOnSameLine = undefined; + this.contextNodeBlockIsOnOneLine = undefined; + this.nextNodeBlockIsOnOneLine = undefined; + }; + FormattingContext.prototype.ContextNodeAllOnSameLine = function () { + if (this.contextNodeAllOnSameLine === undefined) { + this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode); + } + return this.contextNodeAllOnSameLine; + }; + FormattingContext.prototype.NextNodeAllOnSameLine = function () { + if (this.nextNodeAllOnSameLine === undefined) { + this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent); + } + return this.nextNodeAllOnSameLine; + }; + FormattingContext.prototype.TokensAreOnSameLine = function () { + if (this.tokensAreOnSameLine === undefined) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line; + this.tokensAreOnSameLine = (startLine === endLine); + } + return this.tokensAreOnSameLine; + }; + FormattingContext.prototype.ContextNodeBlockIsOnOneLine = function () { + if (this.contextNodeBlockIsOnOneLine === undefined) { + this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode); + } + return this.contextNodeBlockIsOnOneLine; + }; + FormattingContext.prototype.NextNodeBlockIsOnOneLine = function () { + if (this.nextNodeBlockIsOnOneLine === undefined) { + this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent); + } + return this.nextNodeBlockIsOnOneLine; + }; + FormattingContext.prototype.NodeIsOnOneLine = function (node) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line; + return startLine === endLine; + }; + FormattingContext.prototype.BlockIsOnOneLine = function (node) { + var openBrace = ts.findChildOfKind(node, 15 /* OpenBraceToken */, this.sourceFile); + var closeBrace = ts.findChildOfKind(node, 16 /* CloseBraceToken */, this.sourceFile); + if (openBrace && closeBrace) { + var startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; + var endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; + return startLine === endLine; + } + return false; + }; + return FormattingContext; + })(); + formatting.FormattingContext = FormattingContext; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + (function (FormattingRequestKind) { + FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument"; + FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; + FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; + FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; + FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 4] = "FormatOnClosingCurlyBrace"; + })(formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); + var FormattingRequestKind = formatting.FormattingRequestKind; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var Rule = (function () { + function Rule(Descriptor, Operation, Flag) { + if (Flag === void 0) { Flag = 0 /* None */; } + this.Descriptor = Descriptor; + this.Operation = Operation; + this.Flag = Flag; + } + Rule.prototype.toString = function () { + return "[desc=" + this.Descriptor + "," + + "operation=" + this.Operation + "," + + "flag=" + this.Flag + "]"; + }; + return Rule; + })(); + formatting.Rule = Rule; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + (function (RuleAction) { + RuleAction[RuleAction["Ignore"] = 1] = "Ignore"; + RuleAction[RuleAction["Space"] = 2] = "Space"; + RuleAction[RuleAction["NewLine"] = 4] = "NewLine"; + RuleAction[RuleAction["Delete"] = 8] = "Delete"; + })(formatting.RuleAction || (formatting.RuleAction = {})); + var RuleAction = formatting.RuleAction; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var RuleDescriptor = (function () { + function RuleDescriptor(LeftTokenRange, RightTokenRange) { + this.LeftTokenRange = LeftTokenRange; + this.RightTokenRange = RightTokenRange; + } + RuleDescriptor.prototype.toString = function () { + return "[leftRange=" + this.LeftTokenRange + "," + + "rightRange=" + this.RightTokenRange + "]"; + }; + RuleDescriptor.create1 = function (left, right) { + return RuleDescriptor.create4(formatting.Shared.TokenRange.FromToken(left), formatting.Shared.TokenRange.FromToken(right)); + }; + RuleDescriptor.create2 = function (left, right) { + return RuleDescriptor.create4(left, formatting.Shared.TokenRange.FromToken(right)); + }; + RuleDescriptor.create3 = function (left, right) { + return RuleDescriptor.create4(formatting.Shared.TokenRange.FromToken(left), right); + }; + RuleDescriptor.create4 = function (left, right) { + return new RuleDescriptor(left, right); + }; + return RuleDescriptor; + })(); + formatting.RuleDescriptor = RuleDescriptor; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + (function (RuleFlags) { + RuleFlags[RuleFlags["None"] = 0] = "None"; + RuleFlags[RuleFlags["CanDeleteNewLines"] = 1] = "CanDeleteNewLines"; + })(formatting.RuleFlags || (formatting.RuleFlags = {})); + var RuleFlags = formatting.RuleFlags; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var RuleOperation = (function () { + function RuleOperation() { + this.Context = null; + this.Action = null; + } + RuleOperation.prototype.toString = function () { + return "[context=" + this.Context + "," + + "action=" + this.Action + "]"; + }; + RuleOperation.create1 = function (action) { + return RuleOperation.create2(formatting.RuleOperationContext.Any, action); + }; + RuleOperation.create2 = function (context, action) { + var result = new RuleOperation(); + result.Context = context; + result.Action = action; + return result; + }; + return RuleOperation; + })(); + formatting.RuleOperation = RuleOperation; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var RuleOperationContext = (function () { + function RuleOperationContext() { + var funcs = []; + for (var _i = 0; _i < arguments.length; _i++) { + funcs[_i - 0] = arguments[_i]; + } + this.customContextChecks = funcs; + } + RuleOperationContext.prototype.IsAny = function () { + return this === RuleOperationContext.Any; + }; + RuleOperationContext.prototype.InContext = function (context) { + if (this.IsAny()) { + return true; + } + for (var _i = 0, _a = this.customContextChecks; _i < _a.length; _i++) { + var check = _a[_i]; + if (!check(context)) { + return false; + } + } + return true; + }; + RuleOperationContext.Any = new RuleOperationContext(); + return RuleOperationContext; + })(); + formatting.RuleOperationContext = RuleOperationContext; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var Rules = (function () { + function Rules() { + /// + /// Common Rules + /// + // Leave comments alone + this.IgnoreBeforeComment = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.Comments), formatting.RuleOperation.create1(1 /* Ignore */)); + this.IgnoreAfterLineComment = new formatting.Rule(formatting.RuleDescriptor.create3(2 /* SingleLineCommentTrivia */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create1(1 /* Ignore */)); + // Space after keyword but not before ; or : or ? + this.NoSpaceBeforeSemicolon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeColon = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 54 /* ColonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); + this.NoSpaceBeforeQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 53 /* QuestionToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); + this.SpaceAfterColon = new formatting.Rule(formatting.RuleDescriptor.create3(54 /* ColonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 2 /* Space */)); + this.SpaceAfterQuestionMarkInConditionalOperator = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsConditionalOperatorContext), 2 /* Space */)); + this.NoSpaceAfterQuestionMark = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterSemicolon = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + // Space after }. + this.SpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* CloseBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsAfterCodeBlockContext), 2 /* Space */)); + // Special case for (}, else) and (}, while) since else & while tokens are not part of the tree which makes SpaceAfterCloseBrace rule not applied + this.SpaceBetweenCloseBraceAndElse = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* CloseBraceToken */, 80 /* ElseKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.SpaceBetweenCloseBraceAndWhile = new formatting.Rule(formatting.RuleDescriptor.create1(16 /* CloseBraceToken */, 104 /* WhileKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.NoSpaceAfterCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create3(16 /* CloseBraceToken */, formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 20 /* CloseBracketToken */, 24 /* CommaToken */, 23 /* SemicolonToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + // No space for dot + this.NoSpaceBeforeDot = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 21 /* DotToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterDot = new formatting.Rule(formatting.RuleDescriptor.create3(21 /* DotToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + // No space before and after indexer + this.NoSpaceBeforeOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 19 /* OpenBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(20 /* CloseBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8 /* Delete */)); + // Place a space before open brace in a function declaration + this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; + this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); + // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc) + this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([69 /* Identifier */, 3 /* MultiLineCommentTrivia */, 73 /* ClassKeyword */]); + this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); + // Place a space before open brace in a control flow construct + this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 79 /* DoKeyword */, 100 /* TryKeyword */, 85 /* FinallyKeyword */, 80 /* ElseKeyword */]); + this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); + // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. + this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); + this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSingleLineBlockContext), 2 /* Space */)); + this.NoSpaceBetweenEmptyBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsObjectContext), 8 /* Delete */)); + // Insert new line after { and before } in multi-line contexts. + this.NewLineAfterOpenBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create3(15 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); + // For functions and control block place } on a new line [multi-line rule] + this.NewLineBeforeCloseBraceInBlockContext = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.AnyIncludingMultilineComments, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsMultilineBlockContext), 4 /* NewLine */)); + // Special handling of unary operators. + // Prefix operators generally shouldn't have a space between + // them and their target unary expression. + this.NoSpaceAfterUnaryPrefixOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.UnaryPrefixOperators, formatting.Shared.TokenRange.UnaryPrefixExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); + this.NoSpaceAfterUnaryPreincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(41 /* PlusPlusToken */, formatting.Shared.TokenRange.UnaryPreincrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterUnaryPredecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create3(42 /* MinusMinusToken */, formatting.Shared.TokenRange.UnaryPredecrementExpressions), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeUnaryPostincrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostincrementExpressions, 41 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeUnaryPostdecrementOperator = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.UnaryPostdecrementExpressions, 42 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + // More unary operator special-casing. + // DevDiv 181814: Be careful when removing leading whitespace + // around unary operators. Examples: + // 1 - -2 --X--> 1--2 + // a + ++b --X--> a+++b + this.SpaceAfterPostincrementWhenFollowedByAdd = new formatting.Rule(formatting.RuleDescriptor.create1(41 /* PlusPlusToken */, 35 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterAddWhenFollowedByUnaryPlus = new formatting.Rule(formatting.RuleDescriptor.create1(35 /* PlusToken */, 35 /* PlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterAddWhenFollowedByPreincrement = new formatting.Rule(formatting.RuleDescriptor.create1(35 /* PlusToken */, 41 /* PlusPlusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterPostdecrementWhenFollowedBySubtract = new formatting.Rule(formatting.RuleDescriptor.create1(42 /* MinusMinusToken */, 36 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterSubtractWhenFollowedByUnaryMinus = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* MinusToken */, 36 /* MinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterSubtractWhenFollowedByPredecrement = new formatting.Rule(formatting.RuleDescriptor.create1(36 /* MinusToken */, 42 /* MinusMinusToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.NoSpaceBeforeComma = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 24 /* CommaToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterCertainKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([102 /* VarKeyword */, 98 /* ThrowKeyword */, 92 /* NewKeyword */, 78 /* DeleteKeyword */, 94 /* ReturnKeyword */, 101 /* TypeOfKeyword */, 119 /* AwaitKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.SpaceAfterLetConstInVariableDeclaration = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([108 /* LetKeyword */, 74 /* ConstKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), 2 /* Space */)); + this.NoSpaceBeforeOpenParenInFuncCall = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), 8 /* Delete */)); + this.SpaceAfterFunctionInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create3(87 /* FunctionKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); + this.NoSpaceBeforeOpenParenInFuncDecl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsFunctionDeclContext), 8 /* Delete */)); + this.SpaceAfterVoidOperator = new formatting.Rule(formatting.RuleDescriptor.create3(103 /* VoidKeyword */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsVoidOpContext), 2 /* Space */)); + this.NoSpaceBetweenReturnAndSemicolon = new formatting.Rule(formatting.RuleDescriptor.create1(94 /* ReturnKeyword */, 23 /* SemicolonToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + // Add a space between statements. All keywords except (do,else,case) has open/close parens after them. + // So, we have a rule to add a space for [),Any], [do,Any], [else,Any], and [case,Any] + this.SpaceBetweenStatements = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 79 /* DoKeyword */, 80 /* ElseKeyword */, 71 /* CaseKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotForContext), 2 /* Space */)); + // This low-pri rule takes care of "try {" and "finally {" in case the rule SpaceBeforeOpenBraceInControl didn't execute on FormatOnEnter. + this.SpaceAfterTryFinally = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([100 /* TryKeyword */, 85 /* FinallyKeyword */]), 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + // get x() {} + // set x(val) {} + this.SpaceAfterGetSetInMember = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([123 /* GetKeyword */, 129 /* SetKeyword */]), 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); + // Special case for binary operators (that are keywords). For these we have to add a space and shouldn't follow any user options. + this.SpaceBeforeBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryKeywordOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterBinaryKeywordOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryKeywordOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + // TypeScript-specific higher priority rules + // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses + this.NoSpaceAfterConstructor = new formatting.Rule(formatting.RuleDescriptor.create1(121 /* ConstructorKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + // Use of module as a function call. e.g.: import m2 = module("m2"); + this.NoSpaceAfterModuleImport = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.FromTokens([125 /* ModuleKeyword */, 127 /* RequireKeyword */]), 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + // Add a space around certain TypeScript keywords + this.SpaceAfterCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([115 /* AbstractKeyword */, 73 /* ClassKeyword */, 122 /* DeclareKeyword */, 77 /* DefaultKeyword */, 81 /* EnumKeyword */, 82 /* ExportKeyword */, 83 /* ExtendsKeyword */, 123 /* GetKeyword */, 106 /* ImplementsKeyword */, 89 /* ImportKeyword */, 107 /* InterfaceKeyword */, 125 /* ModuleKeyword */, 126 /* NamespaceKeyword */, 110 /* PrivateKeyword */, 112 /* PublicKeyword */, 111 /* ProtectedKeyword */, 129 /* SetKeyword */, 113 /* StaticKeyword */, 132 /* TypeKeyword */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeCertainTypeScriptKeywords = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([83 /* ExtendsKeyword */, 106 /* ImplementsKeyword */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { + this.SpaceAfterModuleName = new formatting.Rule(formatting.RuleDescriptor.create1(9 /* StringLiteral */, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsModuleDeclContext), 2 /* Space */)); + // Lambda expressions + this.SpaceAfterArrow = new formatting.Rule(formatting.RuleDescriptor.create3(34 /* EqualsGreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + // Optional parameters and let args + this.NoSpaceAfterEllipsis = new formatting.Rule(formatting.RuleDescriptor.create1(22 /* DotDotDotToken */, 69 /* Identifier */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterOptionalParameters = new formatting.Rule(formatting.RuleDescriptor.create3(53 /* QuestionToken */, formatting.Shared.TokenRange.FromTokens([18 /* CloseParenToken */, 24 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNotBinaryOpContext), 8 /* Delete */)); + // generics and type assertions + this.NoSpaceBeforeOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.TypeNames, 25 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceBetweenCloseParenAndAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create1(18 /* CloseParenToken */, 25 /* LessThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceAfterOpenAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(25 /* LessThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceBeforeCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 27 /* GreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceAfterCloseAngularBracket = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.FromTokens([17 /* OpenParenToken */, 19 /* OpenBracketToken */, 27 /* GreaterThanToken */, 24 /* CommaToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeArgumentOrParameterOrAssertionContext), 8 /* Delete */)); + this.NoSpaceAfterTypeAssertion = new formatting.Rule(formatting.RuleDescriptor.create3(27 /* GreaterThanToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsTypeAssertionContext), 8 /* Delete */)); + // Remove spaces in empty interface literals. e.g.: x: {} + this.NoSpaceBetweenEmptyInterfaceBraceBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(15 /* OpenBraceToken */, 16 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsObjectTypeContext), 8 /* Delete */)); + // decorators + this.SpaceBeforeAt = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 55 /* AtToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.NoSpaceAfterAt = new formatting.Rule(formatting.RuleDescriptor.create3(55 /* AtToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.SpaceAfterDecorator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([115 /* AbstractKeyword */, 69 /* Identifier */, 82 /* ExportKeyword */, 77 /* DefaultKeyword */, 73 /* ClassKeyword */, 113 /* StaticKeyword */, 112 /* PublicKeyword */, 110 /* PrivateKeyword */, 111 /* ProtectedKeyword */, 123 /* GetKeyword */, 129 /* SetKeyword */, 19 /* OpenBracketToken */, 37 /* AsteriskToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsEndOfDecoratorContextOnSameLine), 2 /* Space */)); + this.NoSpaceBetweenFunctionKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 37 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 8 /* Delete */)); + this.SpaceAfterStarInGeneratorDeclaration = new formatting.Rule(formatting.RuleDescriptor.create3(37 /* AsteriskToken */, formatting.Shared.TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclarationOrFunctionExpressionContext), 2 /* Space */)); + this.NoSpaceBetweenYieldKeywordAndStar = new formatting.Rule(formatting.RuleDescriptor.create1(114 /* YieldKeyword */, 37 /* AsteriskToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 8 /* Delete */)); + this.SpaceBetweenYieldOrYieldStarAndOperand = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([114 /* YieldKeyword */, 37 /* AsteriskToken */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsYieldOrYieldStarWithOperand), 2 /* Space */)); + // Async-await + this.SpaceBetweenAsyncAndOpenParen = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsArrowFunctionContext, Rules.IsSameLineTokenContext), 2 /* Space */)); + this.SpaceBetweenAsyncAndFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(118 /* AsyncKeyword */, 87 /* FunctionKeyword */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + // template string + this.SpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69 /* Identifier */, formatting.Shared.TokenRange.FromTokens([11 /* NoSubstitutionTemplateLiteral */, 12 /* TemplateHead */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.NoSpaceAfterTemplateHeadAndMiddle = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.FromTokens([12 /* TemplateHead */, 13 /* TemplateMiddle */]), formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeTemplateMiddleAndTail = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.FromTokens([13 /* TemplateMiddle */, 14 /* TemplateTail */])), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + // These rules are higher in priority than user-configurable rules. + this.HighPriorityCommonRules = + [ + this.IgnoreBeforeComment, this.IgnoreAfterLineComment, + this.NoSpaceBeforeColon, this.SpaceAfterColon, this.NoSpaceBeforeQuestionMark, this.SpaceAfterQuestionMarkInConditionalOperator, + this.NoSpaceAfterQuestionMark, + this.NoSpaceBeforeDot, this.NoSpaceAfterDot, + this.NoSpaceAfterUnaryPrefixOperator, + this.NoSpaceAfterUnaryPreincrementOperator, this.NoSpaceAfterUnaryPredecrementOperator, + this.NoSpaceBeforeUnaryPostincrementOperator, this.NoSpaceBeforeUnaryPostdecrementOperator, + this.SpaceAfterPostincrementWhenFollowedByAdd, + this.SpaceAfterAddWhenFollowedByUnaryPlus, this.SpaceAfterAddWhenFollowedByPreincrement, + this.SpaceAfterPostdecrementWhenFollowedBySubtract, + this.SpaceAfterSubtractWhenFollowedByUnaryMinus, this.SpaceAfterSubtractWhenFollowedByPredecrement, + this.NoSpaceAfterCloseBrace, + this.SpaceAfterOpenBrace, this.SpaceBeforeCloseBrace, this.NewLineBeforeCloseBraceInBlockContext, + this.SpaceAfterCloseBrace, this.SpaceBetweenCloseBraceAndElse, this.SpaceBetweenCloseBraceAndWhile, this.NoSpaceBetweenEmptyBraceBrackets, + this.NoSpaceBetweenFunctionKeywordAndStar, this.SpaceAfterStarInGeneratorDeclaration, + this.SpaceAfterFunctionInFuncDecl, this.NewLineAfterOpenBraceInBlockContext, this.SpaceAfterGetSetInMember, + this.NoSpaceBetweenYieldKeywordAndStar, this.SpaceBetweenYieldOrYieldStarAndOperand, + this.NoSpaceBetweenReturnAndSemicolon, + this.SpaceAfterCertainKeywords, + this.SpaceAfterLetConstInVariableDeclaration, + this.NoSpaceBeforeOpenParenInFuncCall, + this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator, + this.SpaceAfterVoidOperator, + this.SpaceBetweenAsyncAndOpenParen, this.SpaceBetweenAsyncAndFunctionKeyword, + this.SpaceBetweenTagAndTemplateString, this.NoSpaceAfterTemplateHeadAndMiddle, this.NoSpaceBeforeTemplateMiddleAndTail, + // TypeScript-specific rules + this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, + this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, + this.SpaceAfterModuleName, + this.SpaceAfterArrow, + this.NoSpaceAfterEllipsis, + this.NoSpaceAfterOptionalParameters, + this.NoSpaceBetweenEmptyInterfaceBraceBrackets, + this.NoSpaceBeforeOpenAngularBracket, + this.NoSpaceBetweenCloseParenAndAngularBracket, + this.NoSpaceAfterOpenAngularBracket, + this.NoSpaceBeforeCloseAngularBracket, + this.NoSpaceAfterCloseAngularBracket, + this.NoSpaceAfterTypeAssertion, + this.SpaceBeforeAt, + this.NoSpaceAfterAt, + this.SpaceAfterDecorator, + ]; + // These rules are lower in priority than user-configurable rules. + this.LowPriorityCommonRules = + [ + this.NoSpaceBeforeSemicolon, + this.SpaceBeforeOpenBraceInControl, this.SpaceBeforeOpenBraceInFunction, this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock, + this.NoSpaceBeforeComma, + this.NoSpaceBeforeOpenBracket, + this.NoSpaceAfterCloseBracket, + this.SpaceAfterSemicolon, + this.NoSpaceBeforeOpenParenInFuncDecl, + this.SpaceBetweenStatements, this.SpaceAfterTryFinally + ]; + /// + /// Rules controlled by user options + /// + // Insert space after comma delimiter + this.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.NoSpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + // Insert space before and after binary operators + this.SpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.SpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 2 /* Space */)); + this.NoSpaceBeforeBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.Any, formatting.Shared.TokenRange.BinaryOperators), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); + this.NoSpaceAfterBinaryOperator = new formatting.Rule(formatting.RuleDescriptor.create4(formatting.Shared.TokenRange.BinaryOperators, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsBinaryOpContext), 8 /* Delete */)); + // Insert space after keywords in control flow statements + this.SpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 2 /* Space */)); + this.NoSpaceAfterKeywordInControl = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Keywords, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext), 8 /* Delete */)); + // Open Brace braces after function + //TypeScript: Function can have return types, which can be made of tons of different token kinds + this.NewLineBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); + // Open Brace braces after TypeScript module/class/interface + this.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); + // Open Brace braces after control block + this.NewLineBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 15 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsBeforeMultilineBlockContext), 4 /* NewLine */), 1 /* CanDeleteNewLines */); + // Insert space after semicolon in for statement + this.SpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsForContext), 2 /* Space */)); + this.NoSpaceAfterSemicolonInFor = new formatting.Rule(formatting.RuleDescriptor.create3(23 /* SemicolonToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsForContext), 8 /* Delete */)); + // Insert space after opening and before closing nonempty parenthesis + this.SpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBetweenParens = new formatting.Rule(formatting.RuleDescriptor.create1(17 /* OpenParenToken */, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterOpenParen = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenParenToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeCloseParen = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + // Insert space after opening and before closing nonempty brackets + this.SpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.SpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); + this.NoSpaceBetweenBrackets = new formatting.Rule(formatting.RuleDescriptor.create1(19 /* OpenBracketToken */, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceAfterOpenBracket = new formatting.Rule(formatting.RuleDescriptor.create3(19 /* OpenBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + this.NoSpaceBeforeCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 20 /* CloseBracketToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 8 /* Delete */)); + // Insert space after function keyword for anonymous functions + this.SpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 2 /* Space */)); + this.NoSpaceAfterAnonymousFunctionKeyword = new formatting.Rule(formatting.RuleDescriptor.create1(87 /* FunctionKeyword */, 17 /* OpenParenToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext), 8 /* Delete */)); + } + Rules.prototype.getRuleName = function (rule) { + var o = this; + for (var name_31 in o) { + if (o[name_31] === rule) { + return name_31; + } + } + throw new Error("Unknown rule"); + }; + /// + /// Contexts + /// + Rules.IsForContext = function (context) { + return context.contextNode.kind === 199 /* ForStatement */; + }; + Rules.IsNotForContext = function (context) { + return !Rules.IsForContext(context); + }; + Rules.IsBinaryOpContext = function (context) { + switch (context.contextNode.kind) { + case 181 /* BinaryExpression */: + case 182 /* ConditionalExpression */: + case 189 /* AsExpression */: + case 150 /* TypePredicate */: + case 158 /* UnionType */: + case 159 /* IntersectionType */: + return true; + // equals in binding elements: function foo([[x, y] = [1, 2]]) + case 163 /* BindingElement */: + // equals in type X = ... + case 216 /* TypeAliasDeclaration */: + // equal in import a = module('a'); + case 221 /* ImportEqualsDeclaration */: + // equal in let a = 0; + case 211 /* VariableDeclaration */: + // equal in p = 0; + case 138 /* Parameter */: + case 247 /* EnumMember */: + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + return context.currentTokenSpan.kind === 56 /* EqualsToken */ || context.nextTokenSpan.kind === 56 /* EqualsToken */; + // "in" keyword in for (let x in []) { } + case 200 /* ForInStatement */: + return context.currentTokenSpan.kind === 90 /* InKeyword */ || context.nextTokenSpan.kind === 90 /* InKeyword */; + // Technically, "of" is not a binary operator, but format it the same way as "in" + case 201 /* ForOfStatement */: + return context.currentTokenSpan.kind === 134 /* OfKeyword */ || context.nextTokenSpan.kind === 134 /* OfKeyword */; + } + return false; + }; + Rules.IsNotBinaryOpContext = function (context) { + return !Rules.IsBinaryOpContext(context); + }; + Rules.IsConditionalOperatorContext = function (context) { + return context.contextNode.kind === 182 /* ConditionalExpression */; + }; + Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { + //// This check is mainly used inside SpaceBeforeOpenBraceInControl and SpaceBeforeOpenBraceInFunction. + //// + //// Ex: + //// if (1) { .... + //// * ) and { are on the same line so apply the rule. Here we don't care whether it's same or multi block context + //// + //// Ex: + //// if (1) + //// { ... } + //// * ) and { are on differnet lines. We only need to format if the block is multiline context. So in this case we don't format. + //// + //// Ex: + //// if (1) + //// { ... + //// } + //// * ) and { are on differnet lines. We only need to format if the block is multiline context. So in this case we format. + return context.TokensAreOnSameLine() || Rules.IsBeforeMultilineBlockContext(context); + }; + // This check is done before an open brace in a control construct, a function, or a typescript block declaration + Rules.IsBeforeMultilineBlockContext = function (context) { + return Rules.IsBeforeBlockContext(context) && !(context.NextNodeAllOnSameLine() || context.NextNodeBlockIsOnOneLine()); + }; + Rules.IsMultilineBlockContext = function (context) { + return Rules.IsBlockContext(context) && !(context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + }; + Rules.IsSingleLineBlockContext = function (context) { + return Rules.IsBlockContext(context) && (context.ContextNodeAllOnSameLine() || context.ContextNodeBlockIsOnOneLine()); + }; + Rules.IsBlockContext = function (context) { + return Rules.NodeIsBlockContext(context.contextNode); + }; + Rules.IsBeforeBlockContext = function (context) { + return Rules.NodeIsBlockContext(context.nextTokenParent); + }; + // IMPORTANT!!! This method must return true ONLY for nodes with open and close braces as immediate children + Rules.NodeIsBlockContext = function (node) { + if (Rules.NodeIsTypeScriptDeclWithBlockContext(node)) { + // This means we are in a context that looks like a block to the user, but in the grammar is actually not a node (it's a class, module, enum, object type literal, etc). + return true; + } + switch (node.kind) { + case 192 /* Block */: + case 220 /* CaseBlock */: + case 165 /* ObjectLiteralExpression */: + case 219 /* ModuleBlock */: + return true; + } + return false; + }; + Rules.IsFunctionDeclContext = function (context) { + switch (context.contextNode.kind) { + case 213 /* FunctionDeclaration */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + //case SyntaxKind.MemberFunctionDeclaration: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + ///case SyntaxKind.MethodSignature: + case 147 /* CallSignature */: + case 173 /* FunctionExpression */: + case 144 /* Constructor */: + case 174 /* ArrowFunction */: + //case SyntaxKind.ConstructorDeclaration: + //case SyntaxKind.SimpleArrowFunctionExpression: + //case SyntaxKind.ParenthesizedArrowFunctionExpression: + case 215 /* InterfaceDeclaration */: + return true; + } + return false; + }; + Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) { + return context.contextNode.kind === 213 /* FunctionDeclaration */ || context.contextNode.kind === 173 /* FunctionExpression */; + }; + Rules.IsTypeScriptDeclWithBlockContext = function (context) { + return Rules.NodeIsTypeScriptDeclWithBlockContext(context.contextNode); + }; + Rules.NodeIsTypeScriptDeclWithBlockContext = function (node) { + switch (node.kind) { + case 214 /* ClassDeclaration */: + case 186 /* ClassExpression */: + case 215 /* InterfaceDeclaration */: + case 217 /* EnumDeclaration */: + case 155 /* TypeLiteral */: + case 218 /* ModuleDeclaration */: + return true; + } + return false; + }; + Rules.IsAfterCodeBlockContext = function (context) { + switch (context.currentTokenParent.kind) { + case 214 /* ClassDeclaration */: + case 218 /* ModuleDeclaration */: + case 217 /* EnumDeclaration */: + case 192 /* Block */: + case 244 /* CatchClause */: + case 219 /* ModuleBlock */: + case 206 /* SwitchStatement */: + return true; + } + return false; + }; + Rules.IsControlDeclContext = function (context) { + switch (context.contextNode.kind) { + case 196 /* IfStatement */: + case 206 /* SwitchStatement */: + case 199 /* ForStatement */: + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + case 198 /* WhileStatement */: + case 209 /* TryStatement */: + case 197 /* DoStatement */: + case 205 /* WithStatement */: + // TODO + // case SyntaxKind.ElseClause: + case 244 /* CatchClause */: + return true; + default: + return false; + } + }; + Rules.IsObjectContext = function (context) { + return context.contextNode.kind === 165 /* ObjectLiteralExpression */; + }; + Rules.IsFunctionCallContext = function (context) { + return context.contextNode.kind === 168 /* CallExpression */; + }; + Rules.IsNewContext = function (context) { + return context.contextNode.kind === 169 /* NewExpression */; + }; + Rules.IsFunctionCallOrNewContext = function (context) { + return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); + }; + Rules.IsPreviousTokenNotComma = function (context) { + return context.currentTokenSpan.kind !== 24 /* CommaToken */; + }; + Rules.IsArrowFunctionContext = function (context) { + return context.contextNode.kind === 174 /* ArrowFunction */; + }; + Rules.IsSameLineTokenContext = function (context) { + return context.TokensAreOnSameLine(); + }; + Rules.IsNotBeforeBlockInFunctionDeclarationContext = function (context) { + return !Rules.IsFunctionDeclContext(context) && !Rules.IsBeforeBlockContext(context); + }; + Rules.IsEndOfDecoratorContextOnSameLine = function (context) { + return context.TokensAreOnSameLine() && + context.contextNode.decorators && + Rules.NodeIsInDecoratorContext(context.currentTokenParent) && + !Rules.NodeIsInDecoratorContext(context.nextTokenParent); + }; + Rules.NodeIsInDecoratorContext = function (node) { + while (ts.isExpression(node)) { + node = node.parent; + } + return node.kind === 139 /* Decorator */; + }; + Rules.IsStartOfVariableDeclarationList = function (context) { + return context.currentTokenParent.kind === 212 /* VariableDeclarationList */ && + context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; + }; + Rules.IsNotFormatOnEnter = function (context) { + return context.formattingRequestKind !== 2 /* FormatOnEnter */; + }; + Rules.IsModuleDeclContext = function (context) { + return context.contextNode.kind === 218 /* ModuleDeclaration */; + }; + Rules.IsObjectTypeContext = function (context) { + return context.contextNode.kind === 155 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + }; + Rules.IsTypeArgumentOrParameterOrAssertion = function (token, parent) { + if (token.kind !== 25 /* LessThanToken */ && token.kind !== 27 /* GreaterThanToken */) { + return false; + } + switch (parent.kind) { + case 151 /* TypeReference */: + case 171 /* TypeAssertionExpression */: + case 214 /* ClassDeclaration */: + case 186 /* ClassExpression */: + case 215 /* InterfaceDeclaration */: + case 213 /* FunctionDeclaration */: + case 173 /* FunctionExpression */: + case 174 /* ArrowFunction */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 147 /* CallSignature */: + case 148 /* ConstructSignature */: + case 168 /* CallExpression */: + case 169 /* NewExpression */: + case 188 /* ExpressionWithTypeArguments */: + return true; + default: + return false; + } + }; + Rules.IsTypeArgumentOrParameterOrAssertionContext = function (context) { + return Rules.IsTypeArgumentOrParameterOrAssertion(context.currentTokenSpan, context.currentTokenParent) || + Rules.IsTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); + }; + Rules.IsTypeAssertionContext = function (context) { + return context.contextNode.kind === 171 /* TypeAssertionExpression */; + }; + Rules.IsVoidOpContext = function (context) { + return context.currentTokenSpan.kind === 103 /* VoidKeyword */ && context.currentTokenParent.kind === 177 /* VoidExpression */; + }; + Rules.IsYieldOrYieldStarWithOperand = function (context) { + return context.contextNode.kind === 184 /* YieldExpression */ && context.contextNode.expression !== undefined; + }; + return Rules; + })(); + formatting.Rules = Rules; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var RulesMap = (function () { + function RulesMap() { + this.map = []; + this.mapRowLength = 0; + } + RulesMap.create = function (rules) { + var result = new RulesMap(); + result.Initialize(rules); + return result; + }; + RulesMap.prototype.Initialize = function (rules) { + this.mapRowLength = 134 /* LastToken */ + 1; + this.map = new Array(this.mapRowLength * this.mapRowLength); //new Array(this.mapRowLength * this.mapRowLength); + // This array is used only during construction of the rulesbucket in the map + var rulesBucketConstructionStateList = new Array(this.map.length); //new Array(this.map.length); + this.FillRules(rules, rulesBucketConstructionStateList); + return this.map; + }; + RulesMap.prototype.FillRules = function (rules, rulesBucketConstructionStateList) { + var _this = this; + rules.forEach(function (rule) { + _this.FillRule(rule, rulesBucketConstructionStateList); + }); + }; + RulesMap.prototype.GetRuleBucketIndex = function (row, column) { + var rulesBucketIndex = (row * this.mapRowLength) + column; + //Debug.Assert(rulesBucketIndex < this.map.Length, "Trying to access an index outside the array."); + return rulesBucketIndex; + }; + RulesMap.prototype.FillRule = function (rule, rulesBucketConstructionStateList) { + var _this = this; + var specificRule = rule.Descriptor.LeftTokenRange !== formatting.Shared.TokenRange.Any && + rule.Descriptor.RightTokenRange !== formatting.Shared.TokenRange.Any; + rule.Descriptor.LeftTokenRange.GetTokens().forEach(function (left) { + rule.Descriptor.RightTokenRange.GetTokens().forEach(function (right) { + var rulesBucketIndex = _this.GetRuleBucketIndex(left, right); + var rulesBucket = _this.map[rulesBucketIndex]; + if (rulesBucket === undefined) { + rulesBucket = _this.map[rulesBucketIndex] = new RulesBucket(); + } + rulesBucket.AddRule(rule, specificRule, rulesBucketConstructionStateList, rulesBucketIndex); + }); + }); + }; + RulesMap.prototype.GetRule = function (context) { + var bucketIndex = this.GetRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind); + var bucket = this.map[bucketIndex]; + if (bucket != null) { + for (var _i = 0, _a = bucket.Rules(); _i < _a.length; _i++) { + var rule = _a[_i]; + if (rule.Operation.Context.InContext(context)) { + return rule; + } + } + } + return null; + }; + return RulesMap; + })(); + formatting.RulesMap = RulesMap; + var MaskBitSize = 5; + var Mask = 0x1f; + (function (RulesPosition) { + RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; + RulesPosition[RulesPosition["IgnoreRulesAny"] = MaskBitSize * 1] = "IgnoreRulesAny"; + RulesPosition[RulesPosition["ContextRulesSpecific"] = MaskBitSize * 2] = "ContextRulesSpecific"; + RulesPosition[RulesPosition["ContextRulesAny"] = MaskBitSize * 3] = "ContextRulesAny"; + RulesPosition[RulesPosition["NoContextRulesSpecific"] = MaskBitSize * 4] = "NoContextRulesSpecific"; + RulesPosition[RulesPosition["NoContextRulesAny"] = MaskBitSize * 5] = "NoContextRulesAny"; + })(formatting.RulesPosition || (formatting.RulesPosition = {})); + var RulesPosition = formatting.RulesPosition; + var RulesBucketConstructionState = (function () { + function RulesBucketConstructionState() { + //// The Rules list contains all the inserted rules into a rulebucket in the following order: + //// 1- Ignore rules with specific token combination + //// 2- Ignore rules with any token combination + //// 3- Context rules with specific token combination + //// 4- Context rules with any token combination + //// 5- Non-context rules with specific token combination + //// 6- Non-context rules with any token combination + //// + //// The member rulesInsertionIndexBitmap is used to describe the number of rules + //// in each sub-bucket (above) hence can be used to know the index of where to insert + //// the next rule. It's a bitmap which contains 6 different sections each is given 5 bits. + //// + //// Example: + //// In order to insert a rule to the end of sub-bucket (3), we get the index by adding + //// the values in the bitmap segments 3rd, 2nd, and 1st. + this.rulesInsertionIndexBitmap = 0; + } + RulesBucketConstructionState.prototype.GetInsertionIndex = function (maskPosition) { + var index = 0; + var pos = 0; + var indexBitmap = this.rulesInsertionIndexBitmap; + while (pos <= maskPosition) { + index += (indexBitmap & Mask); + indexBitmap >>= MaskBitSize; + pos += MaskBitSize; + } + return index; + }; + RulesBucketConstructionState.prototype.IncreaseInsertionIndex = function (maskPosition) { + var value = (this.rulesInsertionIndexBitmap >> maskPosition) & Mask; + value++; + ts.Debug.assert((value & Mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); + var temp = this.rulesInsertionIndexBitmap & ~(Mask << maskPosition); + temp |= value << maskPosition; + this.rulesInsertionIndexBitmap = temp; + }; + return RulesBucketConstructionState; + })(); + formatting.RulesBucketConstructionState = RulesBucketConstructionState; + var RulesBucket = (function () { + function RulesBucket() { + this.rules = []; + } + RulesBucket.prototype.Rules = function () { + return this.rules; + }; + RulesBucket.prototype.AddRule = function (rule, specificTokens, constructionState, rulesBucketIndex) { + var position; + if (rule.Operation.Action === 1 /* Ignore */) { + position = specificTokens ? + RulesPosition.IgnoreRulesSpecific : + RulesPosition.IgnoreRulesAny; + } + else if (!rule.Operation.Context.IsAny()) { + position = specificTokens ? + RulesPosition.ContextRulesSpecific : + RulesPosition.ContextRulesAny; + } + else { + position = specificTokens ? + RulesPosition.NoContextRulesSpecific : + RulesPosition.NoContextRulesAny; + } + var state = constructionState[rulesBucketIndex]; + if (state === undefined) { + state = constructionState[rulesBucketIndex] = new RulesBucketConstructionState(); + } + var index = state.GetInsertionIndex(position); + this.rules.splice(index, 0, rule); + state.IncreaseInsertionIndex(position); + }; + return RulesBucket; + })(); + formatting.RulesBucket = RulesBucket; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var Shared; + (function (Shared) { + var TokenRangeAccess = (function () { + function TokenRangeAccess(from, to, except) { + this.tokens = []; + for (var token = from; token <= to; token++) { + if (except.indexOf(token) < 0) { + this.tokens.push(token); + } + } + } + TokenRangeAccess.prototype.GetTokens = function () { + return this.tokens; + }; + TokenRangeAccess.prototype.Contains = function (token) { + return this.tokens.indexOf(token) >= 0; + }; + return TokenRangeAccess; + })(); + Shared.TokenRangeAccess = TokenRangeAccess; + var TokenValuesAccess = (function () { + function TokenValuesAccess(tks) { + this.tokens = tks && tks.length ? tks : []; + } + TokenValuesAccess.prototype.GetTokens = function () { + return this.tokens; + }; + TokenValuesAccess.prototype.Contains = function (token) { + return this.tokens.indexOf(token) >= 0; + }; + return TokenValuesAccess; + })(); + Shared.TokenValuesAccess = TokenValuesAccess; + var TokenSingleValueAccess = (function () { + function TokenSingleValueAccess(token) { + this.token = token; + } + TokenSingleValueAccess.prototype.GetTokens = function () { + return [this.token]; + }; + TokenSingleValueAccess.prototype.Contains = function (tokenValue) { + return tokenValue === this.token; + }; + return TokenSingleValueAccess; + })(); + Shared.TokenSingleValueAccess = TokenSingleValueAccess; + var TokenAllAccess = (function () { + function TokenAllAccess() { + } + TokenAllAccess.prototype.GetTokens = function () { + var result = []; + for (var token = 0 /* FirstToken */; token <= 134 /* LastToken */; token++) { + result.push(token); + } + return result; + }; + TokenAllAccess.prototype.Contains = function (tokenValue) { + return true; + }; + TokenAllAccess.prototype.toString = function () { + return "[allTokens]"; + }; + return TokenAllAccess; + })(); + Shared.TokenAllAccess = TokenAllAccess; + var TokenRange = (function () { + function TokenRange(tokenAccess) { + this.tokenAccess = tokenAccess; + } + TokenRange.FromToken = function (token) { + return new TokenRange(new TokenSingleValueAccess(token)); + }; + TokenRange.FromTokens = function (tokens) { + return new TokenRange(new TokenValuesAccess(tokens)); + }; + TokenRange.FromRange = function (f, to, except) { + if (except === void 0) { except = []; } + return new TokenRange(new TokenRangeAccess(f, to, except)); + }; + TokenRange.AllTokens = function () { + return new TokenRange(new TokenAllAccess()); + }; + TokenRange.prototype.GetTokens = function () { + return this.tokenAccess.GetTokens(); + }; + TokenRange.prototype.Contains = function (token) { + return this.tokenAccess.Contains(token); + }; + TokenRange.prototype.toString = function () { + return this.tokenAccess.toString(); + }; + TokenRange.Any = TokenRange.AllTokens(); + TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */])); + TokenRange.Keywords = TokenRange.FromRange(70 /* FirstKeyword */, 134 /* LastKeyword */); + TokenRange.BinaryOperators = TokenRange.FromRange(25 /* FirstBinaryOperator */, 68 /* LastBinaryOperator */); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90 /* InKeyword */, 91 /* InstanceOfKeyword */, 134 /* OfKeyword */, 116 /* AsKeyword */, 124 /* IsKeyword */]); + TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([41 /* PlusPlusToken */, 42 /* MinusMinusToken */, 50 /* TildeToken */, 49 /* ExclamationToken */]); + TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([8 /* NumericLiteral */, 69 /* Identifier */, 17 /* OpenParenToken */, 19 /* OpenBracketToken */, 15 /* OpenBraceToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); + TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); + TokenRange.UnaryPostincrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 18 /* CloseParenToken */, 20 /* CloseBracketToken */, 92 /* NewKeyword */]); + TokenRange.UnaryPredecrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 17 /* OpenParenToken */, 97 /* ThisKeyword */, 92 /* NewKeyword */]); + TokenRange.UnaryPostdecrementExpressions = TokenRange.FromTokens([69 /* Identifier */, 18 /* CloseParenToken */, 20 /* CloseBracketToken */, 92 /* NewKeyword */]); + TokenRange.Comments = TokenRange.FromTokens([2 /* SingleLineCommentTrivia */, 3 /* MultiLineCommentTrivia */]); + TokenRange.TypeNames = TokenRange.FromTokens([69 /* Identifier */, 128 /* NumberKeyword */, 130 /* StringKeyword */, 120 /* BooleanKeyword */, 131 /* SymbolKeyword */, 103 /* VoidKeyword */, 117 /* AnyKeyword */]); + return TokenRange; + })(); + Shared.TokenRange = TokenRange; + })(Shared = formatting.Shared || (formatting.Shared = {})); + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var RulesProvider = (function () { + function RulesProvider() { + this.globalRules = new formatting.Rules(); + } + RulesProvider.prototype.getRuleName = function (rule) { + return this.globalRules.getRuleName(rule); + }; + RulesProvider.prototype.getRuleByName = function (name) { + return this.globalRules[name]; + }; + RulesProvider.prototype.getRulesMap = function () { + return this.rulesMap; + }; + RulesProvider.prototype.ensureUpToDate = function (options) { + // TODO: Should this be '==='? + if (this.options == null || !ts.compareDataObjects(this.options, options)) { + var activeRules = this.createActiveRules(options); + var rulesMap = formatting.RulesMap.create(activeRules); + this.activeRules = activeRules; + this.rulesMap = rulesMap; + this.options = ts.clone(options); + } + }; + RulesProvider.prototype.createActiveRules = function (options) { + var rules = this.globalRules.HighPriorityCommonRules.slice(0); + if (options.InsertSpaceAfterCommaDelimiter) { + rules.push(this.globalRules.SpaceAfterComma); + } + else { + rules.push(this.globalRules.NoSpaceAfterComma); + } + if (options.InsertSpaceAfterFunctionKeywordForAnonymousFunctions) { + rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); + } + else { + rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); + } + if (options.InsertSpaceAfterKeywordsInControlFlowStatements) { + rules.push(this.globalRules.SpaceAfterKeywordInControl); + } + else { + rules.push(this.globalRules.NoSpaceAfterKeywordInControl); + } + if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { + rules.push(this.globalRules.SpaceAfterOpenParen); + rules.push(this.globalRules.SpaceBeforeCloseParen); + rules.push(this.globalRules.NoSpaceBetweenParens); + } + else { + rules.push(this.globalRules.NoSpaceAfterOpenParen); + rules.push(this.globalRules.NoSpaceBeforeCloseParen); + rules.push(this.globalRules.NoSpaceBetweenParens); + } + if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { + rules.push(this.globalRules.SpaceAfterOpenBracket); + rules.push(this.globalRules.SpaceBeforeCloseBracket); + rules.push(this.globalRules.NoSpaceBetweenBrackets); + } + else { + rules.push(this.globalRules.NoSpaceAfterOpenBracket); + rules.push(this.globalRules.NoSpaceBeforeCloseBracket); + rules.push(this.globalRules.NoSpaceBetweenBrackets); + } + if (options.InsertSpaceAfterSemicolonInForStatements) { + rules.push(this.globalRules.SpaceAfterSemicolonInFor); + } + else { + rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); + } + if (options.InsertSpaceBeforeAndAfterBinaryOperators) { + rules.push(this.globalRules.SpaceBeforeBinaryOperator); + rules.push(this.globalRules.SpaceAfterBinaryOperator); + } + else { + rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); + rules.push(this.globalRules.NoSpaceAfterBinaryOperator); + } + if (options.PlaceOpenBraceOnNewLineForControlBlocks) { + rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); + } + if (options.PlaceOpenBraceOnNewLineForFunctions) { + rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); + rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); + } + rules = rules.concat(this.globalRules.LowPriorityCommonRules); + return rules; + }; + return RulesProvider; + })(); + formatting.RulesProvider = RulesProvider; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/// +/// +/// +/// +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var Constants; + (function (Constants) { + Constants[Constants["Unknown"] = -1] = "Unknown"; + })(Constants || (Constants = {})); + function formatOnEnter(position, sourceFile, rulesProvider, options) { + var line = sourceFile.getLineAndCharacterOfPosition(position).line; + if (line === 0) { + return []; + } + // get the span for the previous\current line + var span = { + // get start position for the previous line + pos: ts.getStartPositionOfLine(line - 1, sourceFile), + // get end position for the current line (end value is exclusive so add 1 to the result) + end: ts.getEndLinePosition(line, sourceFile) + 1 + }; + return formatSpan(span, sourceFile, options, rulesProvider, 2 /* FormatOnEnter */); + } + formatting.formatOnEnter = formatOnEnter; + function formatOnSemicolon(position, sourceFile, rulesProvider, options) { + return formatOutermostParent(position, 23 /* SemicolonToken */, sourceFile, options, rulesProvider, 3 /* FormatOnSemicolon */); + } + formatting.formatOnSemicolon = formatOnSemicolon; + function formatOnClosingCurly(position, sourceFile, rulesProvider, options) { + return formatOutermostParent(position, 16 /* CloseBraceToken */, sourceFile, options, rulesProvider, 4 /* FormatOnClosingCurlyBrace */); + } + formatting.formatOnClosingCurly = formatOnClosingCurly; + function formatDocument(sourceFile, rulesProvider, options) { + var span = { + pos: 0, + end: sourceFile.text.length + }; + return formatSpan(span, sourceFile, options, rulesProvider, 0 /* FormatDocument */); + } + formatting.formatDocument = formatDocument; + function formatSelection(start, end, sourceFile, rulesProvider, options) { + // format from the beginning of the line + var span = { + pos: ts.getLineStartPositionForPosition(start, sourceFile), + end: end + }; + return formatSpan(span, sourceFile, options, rulesProvider, 1 /* FormatSelection */); + } + formatting.formatSelection = formatSelection; + function formatOutermostParent(position, expectedLastToken, sourceFile, options, rulesProvider, requestKind) { + var parent = findOutermostParent(position, expectedLastToken, sourceFile); + if (!parent) { + return []; + } + var span = { + pos: ts.getLineStartPositionForPosition(parent.getStart(sourceFile), sourceFile), + end: parent.end + }; + return formatSpan(span, sourceFile, options, rulesProvider, requestKind); + } + function findOutermostParent(position, expectedTokenKind, sourceFile) { + var precedingToken = ts.findPrecedingToken(position, sourceFile); + // when it is claimed that trigger character was typed at given position + // we verify that there is a token with a matching kind whose end is equal to position (because the character was just typed). + // If this condition is not hold - then trigger character was typed in some other context, + // i.e.in comment and thus should not trigger autoformatting + if (!precedingToken || + precedingToken.kind !== expectedTokenKind || + position !== precedingToken.getEnd()) { + return undefined; + } + // walk up and search for the parent node that ends at the same position with precedingToken. + // for cases like this + // + // let x = 1; + // while (true) { + // } + // after typing close curly in while statement we want to reformat just the while statement. + // However if we just walk upwards searching for the parent that has the same end value - + // we'll end up with the whole source file. isListElement allows to stop on the list element level + var current = precedingToken; + while (current && + current.parent && + current.parent.end === precedingToken.end && + !isListElement(current.parent, current)) { + current = current.parent; + } + return current; + } + // Returns true if node is a element in some list in parent + // i.e. parent is class declaration with the list of members and node is one of members. + function isListElement(parent, node) { + switch (parent.kind) { + case 214 /* ClassDeclaration */: + case 215 /* InterfaceDeclaration */: + return ts.rangeContainsRange(parent.members, node); + case 218 /* ModuleDeclaration */: + var body = parent.body; + return body && body.kind === 192 /* Block */ && ts.rangeContainsRange(body.statements, node); + case 248 /* SourceFile */: + case 192 /* Block */: + case 219 /* ModuleBlock */: + return ts.rangeContainsRange(parent.statements, node); + case 244 /* CatchClause */: + return ts.rangeContainsRange(parent.block.statements, node); + } + return false; + } + /** find node that fully contains given text range */ + function findEnclosingNode(range, sourceFile) { + return find(sourceFile); + function find(n) { + var candidate = ts.forEachChild(n, function (c) { return ts.startEndContainsRange(c.getStart(sourceFile), c.end, range) && c; }); + if (candidate) { + var result = find(candidate); + if (result) { + return result; + } + } + return n; + } + } + /** formatting is not applied to ranges that contain parse errors. + * This function will return a predicate that for a given text range will tell + * if there are any parse errors that overlap with the range. + */ + function prepareRangeContainsErrorFunction(errors, originalRange) { + if (!errors.length) { + return rangeHasNoErrors; + } + // pick only errors that fall in range + var sorted = errors + .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) + .sort(function (e1, e2) { return e1.start - e2.start; }); + if (!sorted.length) { + return rangeHasNoErrors; + } + var index = 0; + return function (r) { + // in current implementation sequence of arguments [r1, r2...] is monotonically increasing. + // 'index' tracks the index of the most recent error that was checked. + while (true) { + if (index >= sorted.length) { + // all errors in the range were already checked -> no error in specified range + return false; + } + var error = sorted[index]; + if (r.end <= error.start) { + // specified range ends before the error refered by 'index' - no error in range + return false; + } + if (ts.startEndOverlapsWithStartEnd(r.pos, r.end, error.start, error.start + error.length)) { + // specified range overlaps with error range + return true; + } + index++; + } + }; + function rangeHasNoErrors(r) { + return false; + } + } + /** + * Start of the original range might fall inside the comment - scanner will not yield appropriate results + * This function will look for token that is located before the start of target range + * and return its end as start position for the scanner. + */ + function getScanStartPosition(enclosingNode, originalRange, sourceFile) { + var start = enclosingNode.getStart(sourceFile); + if (start === originalRange.pos && enclosingNode.end === originalRange.end) { + return start; + } + var precedingToken = ts.findPrecedingToken(originalRange.pos, sourceFile); + if (!precedingToken) { + // no preceding token found - start from the beginning of enclosing node + return enclosingNode.pos; + } + // preceding token ends after the start of original range (i.e when originaRange.pos falls in the middle of literal) + // start from the beginning of enclosingNode to handle the entire 'originalRange' + if (precedingToken.end >= originalRange.pos) { + return enclosingNode.pos; + } + return precedingToken.end; + } + /* + * For cases like + * if (a || + * b ||$ + * c) {...} + * If we hit Enter at $ we want line ' b ||' to be indented. + * Formatting will be applied to the last two lines. + * Node that fully encloses these lines is binary expression 'a ||...'. + * Initial indentation for this node will be 0. + * Binary expressions don't introduce new indentation scopes, however it is possible + * that some parent node on the same line does - like if statement in this case. + * Note that we are considering parents only from the same line with initial node - + * if parent is on the different line - its delta was already contributed + * to the initial indentation. + */ + function getOwnOrInheritedDelta(n, options, sourceFile) { + var previousLine = -1 /* Unknown */; + var childKind = 0 /* Unknown */; + while (n) { + var line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line; + if (previousLine !== -1 /* Unknown */ && line !== previousLine) { + break; + } + if (formatting.SmartIndenter.shouldIndentChildNode(n.kind, childKind)) { + return options.IndentSize; + } + previousLine = line; + childKind = n.kind; + n = n.parent; + } + return 0; + } + function formatSpan(originalRange, sourceFile, options, rulesProvider, requestKind) { + var rangeContainsError = prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange); + // formatting context is used by rules provider + var formattingContext = new formatting.FormattingContext(sourceFile, requestKind); + // find the smallest node that fully wraps the range and compute the initial indentation for the node + var enclosingNode = findEnclosingNode(originalRange, sourceFile); + var formattingScanner = formatting.getFormattingScanner(sourceFile, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end); + var initialIndentation = formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, options); + var previousRangeHasError; + var previousRange; + var previousParent; + var previousRangeStartLine; + var lastIndentedLine; + var indentationOnLastIndentedLine; + var edits = []; + formattingScanner.advance(); + if (formattingScanner.isOnToken()) { + var startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line; + var undecoratedStartLine = startLine; + if (enclosingNode.decorators) { + undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line; + } + var delta = getOwnOrInheritedDelta(enclosingNode, options, sourceFile); + processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); + } + formattingScanner.close(); + return edits; + // local functions + /** Tries to compute the indentation for a list element. + * If list element is not in range then + * function will pick its actual indentation + * so it can be pushed downstream as inherited indentation. + * If list element is in the range - its indentation will be equal + * to inherited indentation from its predecessors. + */ + function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) { + if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos)) { + if (inheritedIndentation !== -1 /* Unknown */) { + return inheritedIndentation; + } + } + else { + var startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line; + var startLinePosition = ts.getLineStartPositionForPosition(startPos, sourceFile); + var column = formatting.SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options); + if (startLine !== parentStartLine || startPos === column) { + return column; + } + } + return -1 /* Unknown */; + } + function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { + var indentation = inheritedIndentation; + if (indentation === -1 /* Unknown */) { + if (isSomeBlock(node.kind)) { + // blocks should be indented in + // - other blocks + // - source file + // - switch\default clauses + if (isSomeBlock(parent.kind) || + parent.kind === 248 /* SourceFile */ || + parent.kind === 241 /* CaseClause */ || + parent.kind === 242 /* DefaultClause */) { + indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); + } + else { + indentation = parentDynamicIndentation.getIndentation(); + } + } + else { + if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + indentation = parentDynamicIndentation.getIndentation(); + } + else { + indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(); + } + } + } + var delta = formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0 /* Unknown */) ? options.IndentSize : 0; + if (effectiveParentStartLine === startLine) { + // if node is located on the same line with the parent + // - inherit indentation from the parent + // - push children if either parent of node itself has non-zero delta + indentation = startLine === lastIndentedLine + ? indentationOnLastIndentedLine + : parentDynamicIndentation.getIndentation(); + delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta() + delta); + } + return { + indentation: indentation, + delta: delta + }; + } + function getFirstNonDecoratorTokenOfNode(node) { + if (node.modifiers && node.modifiers.length) { + return node.modifiers[0].kind; + } + switch (node.kind) { + case 214 /* ClassDeclaration */: return 73 /* ClassKeyword */; + case 215 /* InterfaceDeclaration */: return 107 /* InterfaceKeyword */; + case 213 /* FunctionDeclaration */: return 87 /* FunctionKeyword */; + case 217 /* EnumDeclaration */: return 217 /* EnumDeclaration */; + case 145 /* GetAccessor */: return 123 /* GetKeyword */; + case 146 /* SetAccessor */: return 129 /* SetKeyword */; + case 143 /* MethodDeclaration */: + if (node.asteriskToken) { + return 37 /* AsteriskToken */; + } + // fall-through + case 141 /* PropertyDeclaration */: + case 138 /* Parameter */: + return node.name.kind; + } + } + function getDynamicIndentation(node, nodeStartLine, indentation, delta) { + return { + getIndentationForComment: function (kind, tokenIndentation) { + switch (kind) { + // preceding comment to the token that closes the indentation scope inherits the indentation from the scope + // .. { + // // comment + // } + case 16 /* CloseBraceToken */: + case 20 /* CloseBracketToken */: + case 18 /* CloseParenToken */: + return indentation + delta; + } + return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; + }, + getIndentationForToken: function (line, kind) { + if (nodeStartLine !== line && node.decorators) { + if (kind === getFirstNonDecoratorTokenOfNode(node)) { + // if this token is the first token following the list of decorators, we do not need to indent + return indentation; + } + } + switch (kind) { + // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent + case 15 /* OpenBraceToken */: + case 16 /* CloseBraceToken */: + case 19 /* OpenBracketToken */: + case 20 /* CloseBracketToken */: + case 17 /* OpenParenToken */: + case 18 /* CloseParenToken */: + case 80 /* ElseKeyword */: + case 104 /* WhileKeyword */: + case 55 /* AtToken */: + return indentation; + default: + // if token line equals to the line of containing node (this is a first token in the node) - use node indentation + return nodeStartLine !== line ? indentation + delta : indentation; + } + }, + getIndentation: function () { return indentation; }, + getDelta: function () { return delta; }, + recomputeIndentation: function (lineAdded) { + if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent.kind, node.kind)) { + if (lineAdded) { + indentation += options.IndentSize; + } + else { + indentation -= options.IndentSize; + } + if (formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0 /* Unknown */)) { + delta = options.IndentSize; + } + else { + delta = 0; + } + } + } + }; + } + function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) { + if (!ts.rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) { + return; + } + var nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta); + // a useful observations when tracking context node + // / + // [a] + // / | \ + // [b] [c] [d] + // node 'a' is a context node for nodes 'b', 'c', 'd' + // except for the leftmost leaf token in [b] - in this case context node ('e') is located somewhere above 'a' + // this rule can be applied recursively to child nodes of 'a'. + // + // context node is set to parent node value after processing every child node + // context node is set to parent of the token after processing every token + var childContextNode = contextNode; + // if there are any tokens that logically belong to node and interleave child nodes + // such tokens will be consumed in processChildNode for for the child that follows them + ts.forEachChild(node, function (child) { + processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListElement*/ false); + }, function (nodes) { + processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation); + }); + // proceed any tokens in the node that are located after child nodes + while (formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(node); + if (tokenInfo.token.end > node.end) { + break; + } + consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation); + } + function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem) { + var childStartPos = child.getStart(sourceFile); + var childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line; + var undecoratedChildStartLine = childStartLine; + if (child.decorators) { + undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(ts.getNonDecoratorTokenPosOfNode(child, sourceFile)).line; + } + // if child is a list item - try to get its indentation + var childIndentationAmount = -1 /* Unknown */; + if (isListItem) { + childIndentationAmount = tryComputeIndentationForListItem(childStartPos, child.end, parentStartLine, originalRange, inheritedIndentation); + if (childIndentationAmount !== -1 /* Unknown */) { + inheritedIndentation = childIndentationAmount; + } + } + // child node is outside the target range - do not dive inside + if (!ts.rangeOverlapsWithStartEnd(originalRange, child.pos, child.end)) { + return inheritedIndentation; + } + if (child.getFullWidth() === 0) { + return inheritedIndentation; + } + while (formattingScanner.isOnToken()) { + // proceed any parent tokens that are located prior to child.getStart() + var tokenInfo = formattingScanner.readTokenInfo(node); + if (tokenInfo.token.end > childStartPos) { + // stop when formatting scanner advances past the beginning of the child + break; + } + consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation); + } + if (!formattingScanner.isOnToken()) { + return inheritedIndentation; + } + if (ts.isToken(child)) { + // if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules + var tokenInfo = formattingScanner.readTokenInfo(child); + ts.Debug.assert(tokenInfo.token.end === child.end); + consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation); + return inheritedIndentation; + } + var effectiveParentStartLine = child.kind === 139 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); + processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); + childContextNode = node; + return inheritedIndentation; + } + function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { + var listStartToken = getOpenTokenForList(parent, nodes); + var listEndToken = getCloseTokenForOpenToken(listStartToken); + var listDynamicIndentation = parentDynamicIndentation; + var startLine = parentStartLine; + if (listStartToken !== 0 /* Unknown */) { + // introduce a new indentation scope for lists (including list start and end tokens) + while (formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(parent); + if (tokenInfo.token.end > nodes.pos) { + // stop when formatting scanner moves past the beginning of node list + break; + } + else if (tokenInfo.token.kind === listStartToken) { + // consume list start token + startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; + var indentation_1 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); + listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_1.indentation, indentation_1.delta); + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation); + } + else { + // consume any tokens that precede the list as child elements of 'node' using its indentation scope + consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation); + } + } + } + var inheritedIndentation = -1 /* Unknown */; + for (var _i = 0; _i < nodes.length; _i++) { + var child = nodes[_i]; + inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListElement*/ true); + } + if (listEndToken !== 0 /* Unknown */) { + if (formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(parent); + // consume the list end token only if it is still belong to the parent + // there might be the case when current token matches end token but does not considered as one + // function (x: function) <-- + // without this check close paren will be interpreted as list end token for function expression which is wrong + if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + // consume list end token + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation); + } + } + } + } + function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation) { + ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token)); + var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); + var indentToken = false; + if (currentTokenInfo.leadingTrivia) { + processTrivia(currentTokenInfo.leadingTrivia, parent, childContextNode, dynamicIndentation); + } + var lineAdded; + var isTokenInRange = ts.rangeContainsRange(originalRange, currentTokenInfo.token); + var tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos); + if (isTokenInRange) { + var rangeHasError = rangeContainsError(currentTokenInfo.token); + // save prevStartLine since processRange will overwrite this value with current ones + var prevStartLine = previousRangeStartLine; + lineAdded = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation); + if (rangeHasError) { + // do not indent comments\token if token range overlaps with some error + indentToken = false; + } + else { + if (lineAdded !== undefined) { + indentToken = lineAdded; + } + else { + indentToken = lastTriviaWasNewLine && tokenStart.line !== prevStartLine; + } + } + } + if (currentTokenInfo.trailingTrivia) { + processTrivia(currentTokenInfo.trailingTrivia, parent, childContextNode, dynamicIndentation); + } + if (indentToken) { + var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? + dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind) : + -1 /* Unknown */; + if (currentTokenInfo.leadingTrivia) { + var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation); + var indentNextTokenOrTrivia = true; + for (var _i = 0, _a = currentTokenInfo.leadingTrivia; _i < _a.length; _i++) { + var triviaItem = _a[_i]; + if (!ts.rangeContainsRange(originalRange, triviaItem)) { + continue; + } + switch (triviaItem.kind) { + case 3 /* MultiLineCommentTrivia */: + indentMultilineComment(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); + indentNextTokenOrTrivia = false; + break; + case 2 /* SingleLineCommentTrivia */: + if (indentNextTokenOrTrivia) { + insertIndentation(triviaItem.pos, commentIndentation, /*lineAdded*/ false); + indentNextTokenOrTrivia = false; + } + break; + case 4 /* NewLineTrivia */: + indentNextTokenOrTrivia = true; + break; + } + } + } + // indent token only if is it is in target range and does not overlap with any error ranges + if (tokenIndentation !== -1 /* Unknown */) { + insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAdded); + lastIndentedLine = tokenStart.line; + indentationOnLastIndentedLine = tokenIndentation; + } + } + formattingScanner.advance(); + childContextNode = parent; + } + } + function processTrivia(trivia, parent, contextNode, dynamicIndentation) { + for (var _i = 0; _i < trivia.length; _i++) { + var triviaItem = trivia[_i]; + if (ts.isComment(triviaItem.kind) && ts.rangeContainsRange(originalRange, triviaItem)) { + var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos); + processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation); + } + } + } + function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { + var rangeHasError = rangeContainsError(range); + var lineAdded; + if (!rangeHasError && !previousRangeHasError) { + if (!previousRange) { + // trim whitespaces starting from the beginning of the span up to the current line + var originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos); + trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line); + } + else { + lineAdded = + processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation); + } + } + previousRange = range; + previousParent = parent; + previousRangeStartLine = rangeStart.line; + previousRangeHasError = rangeHasError; + return lineAdded; + } + function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) { + formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode); + var rule = rulesProvider.getRulesMap().GetRule(formattingContext); + var trimTrailingWhitespaces; + var lineAdded; + if (rule) { + applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); + if (rule.Operation.Action & (2 /* Space */ | 8 /* Delete */) && currentStartLine !== previousStartLine) { + lineAdded = false; + // Handle the case where the next line is moved to be the end of this line. + // In this case we don't indent the next line in the next pass. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAdded*/ false); + } + } + else if (rule.Operation.Action & 4 /* NewLine */ && currentStartLine === previousStartLine) { + lineAdded = true; + // Handle the case where token2 is moved to the new line. + // In this case we indent token2 in the next pass but we set + // sameLineIndent flag to notify the indenter that the indentation is within the line. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAdded*/ true); + } + } + // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line + trimTrailingWhitespaces = + (rule.Operation.Action & (4 /* NewLine */ | 2 /* Space */)) && + rule.Flag !== 1 /* CanDeleteNewLines */; + } + else { + trimTrailingWhitespaces = true; + } + if (currentStartLine !== previousStartLine && trimTrailingWhitespaces) { + // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line + trimTrailingWhitespacesForLines(previousStartLine, currentStartLine, previousItem); + } + return lineAdded; + } + function insertIndentation(pos, indentation, lineAdded) { + var indentationString = getIndentationString(indentation, options); + if (lineAdded) { + // new line is added before the token by the formatting rules + // insert indentation string at the very beginning of the token + recordReplace(pos, 0, indentationString); + } + else { + var tokenStart = sourceFile.getLineAndCharacterOfPosition(pos); + if (indentation !== tokenStart.character) { + var startLinePosition = ts.getStartPositionOfLine(tokenStart.line, sourceFile); + recordReplace(startLinePosition, tokenStart.character, indentationString); + } + } + } + function indentMultilineComment(commentRange, indentation, firstLineIsIndented) { + // split comment in lines + var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; + var parts; + if (startLine === endLine) { + if (!firstLineIsIndented) { + // treat as single line comment + insertIndentation(commentRange.pos, indentation, /*lineAdded*/ false); + } + return; + } + else { + parts = []; + var startPos = commentRange.pos; + for (var line = startLine; line < endLine; ++line) { + var endOfLine = ts.getEndLinePosition(line, sourceFile); + parts.push({ pos: startPos, end: endOfLine }); + startPos = ts.getStartPositionOfLine(line + 1, sourceFile); + } + parts.push({ pos: startPos, end: commentRange.end }); + } + var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile); + var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); + if (indentation === nonWhitespaceColumnInFirstPart.column) { + return; + } + var startIndex = 0; + if (firstLineIsIndented) { + startIndex = 1; + startLine++; + } + // shift all parts on the delta size + var delta = indentation - nonWhitespaceColumnInFirstPart.column; + for (var i = startIndex, len = parts.length; i < len; ++i, ++startLine) { + var startLinePos_1 = ts.getStartPositionOfLine(startLine, sourceFile); + var nonWhitespaceCharacterAndColumn = i === 0 + ? nonWhitespaceColumnInFirstPart + : formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(parts[i].pos, parts[i].end, sourceFile, options); + var newIndentation = nonWhitespaceCharacterAndColumn.column + delta; + if (newIndentation > 0) { + var indentationString = getIndentationString(newIndentation, options); + recordReplace(startLinePos_1, nonWhitespaceCharacterAndColumn.character, indentationString); + } + else { + recordDelete(startLinePos_1, nonWhitespaceCharacterAndColumn.character); + } + } + } + function trimTrailingWhitespacesForLines(line1, line2, range) { + for (var line = line1; line < line2; ++line) { + var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); + var lineEndPosition = ts.getEndLinePosition(line, sourceFile); + // do not trim whitespaces in comments or template expression + if (range && (ts.isComment(range.kind) || ts.isStringOrRegularExpressionOrTemplateLiteral(range.kind)) && range.pos <= lineEndPosition && range.end > lineEndPosition) { + continue; + } + var pos = lineEndPosition; + while (pos >= lineStartPosition && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { + pos--; + } + if (pos !== lineEndPosition) { + ts.Debug.assert(pos === lineStartPosition || !ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))); + recordDelete(pos + 1, lineEndPosition - pos); + } + } + } + function newTextChange(start, len, newText) { + return { span: ts.createTextSpan(start, len), newText: newText }; + } + function recordDelete(start, len) { + if (len) { + edits.push(newTextChange(start, len, "")); + } + } + function recordReplace(start, len, newText) { + if (len || newText) { + edits.push(newTextChange(start, len, newText)); + } + } + function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { + var between; + switch (rule.Operation.Action) { + case 1 /* Ignore */: + // no action required + return; + case 8 /* Delete */: + if (previousRange.end !== currentRange.pos) { + // delete characters starting from t1.end up to t2.pos exclusive + recordDelete(previousRange.end, currentRange.pos - previousRange.end); + } + break; + case 4 /* NewLine */: + // exit early if we on different lines and rule cannot change number of newlines + // if line1 and line2 are on subsequent lines then no edits are required - ok to exit + // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines + if (rule.Flag !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { + return; + } + // edit should not be applied only if we have one line feed between elements + var lineDelta = currentStartLine - previousStartLine; + if (lineDelta !== 1) { + recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter); + } + break; + case 2 /* Space */: + // exit early if we on different lines and rule cannot change number of newlines + if (rule.Flag !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { + return; + } + var posDelta = currentRange.pos - previousRange.end; + if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32 /* space */) { + recordReplace(previousRange.end, currentRange.pos - previousRange.end, " "); + } + break; + } + } + } + function isSomeBlock(kind) { + switch (kind) { + case 192 /* Block */: + case 219 /* ModuleBlock */: + return true; + } + return false; + } + function getOpenTokenForList(node, list) { + switch (node.kind) { + case 144 /* Constructor */: + case 213 /* FunctionDeclaration */: + case 173 /* FunctionExpression */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 174 /* ArrowFunction */: + if (node.typeParameters === list) { + return 25 /* LessThanToken */; + } + else if (node.parameters === list) { + return 17 /* OpenParenToken */; + } + break; + case 168 /* CallExpression */: + case 169 /* NewExpression */: + if (node.typeArguments === list) { + return 25 /* LessThanToken */; + } + else if (node.arguments === list) { + return 17 /* OpenParenToken */; + } + break; + case 151 /* TypeReference */: + if (node.typeArguments === list) { + return 25 /* LessThanToken */; + } + } + return 0 /* Unknown */; + } + function getCloseTokenForOpenToken(kind) { + switch (kind) { + case 17 /* OpenParenToken */: + return 18 /* CloseParenToken */; + case 25 /* LessThanToken */: + return 27 /* GreaterThanToken */; + } + return 0 /* Unknown */; + } + var internedSizes; + var internedTabsIndentation; + var internedSpacesIndentation; + function getIndentationString(indentation, options) { + // reset interned strings if FormatCodeOptions were changed + var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize); + if (resetInternedStrings) { + internedSizes = { tabSize: options.TabSize, indentSize: options.IndentSize }; + internedTabsIndentation = internedSpacesIndentation = undefined; + } + if (!options.ConvertTabsToSpaces) { + var tabs = Math.floor(indentation / options.TabSize); + var spaces = indentation - tabs * options.TabSize; + var tabString; + if (!internedTabsIndentation) { + internedTabsIndentation = []; + } + if (internedTabsIndentation[tabs] === undefined) { + internedTabsIndentation[tabs] = tabString = repeat('\t', tabs); + } + else { + tabString = internedTabsIndentation[tabs]; + } + return spaces ? tabString + repeat(" ", spaces) : tabString; + } + else { + var spacesString; + var quotient = Math.floor(indentation / options.IndentSize); + var remainder = indentation % options.IndentSize; + if (!internedSpacesIndentation) { + internedSpacesIndentation = []; + } + if (internedSpacesIndentation[quotient] === undefined) { + spacesString = repeat(" ", options.IndentSize * quotient); + internedSpacesIndentation[quotient] = spacesString; + } + else { + spacesString = internedSpacesIndentation[quotient]; + } + return remainder ? spacesString + repeat(" ", remainder) : spacesString; + } + function repeat(value, count) { + var s = ""; + for (var i = 0; i < count; ++i) { + s += value; + } + return s; + } + } + formatting.getIndentationString = getIndentationString; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + var formatting; + (function (formatting) { + var SmartIndenter; + (function (SmartIndenter) { + var Value; + (function (Value) { + Value[Value["Unknown"] = -1] = "Unknown"; + })(Value || (Value = {})); + function getIndentation(position, sourceFile, options) { + if (position > sourceFile.text.length) { + return 0; // past EOF + } + // no indentation when the indent style is set to none, + // so we can return fast + if (options.IndentStyle === ts.IndentStyle.None) { + return 0; + } + var precedingToken = ts.findPrecedingToken(position, sourceFile); + if (!precedingToken) { + return 0; + } + // no indentation in string \regex\template literals + var precedingTokenIsLiteral = ts.isStringOrRegularExpressionOrTemplateLiteral(precedingToken.kind); + if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && precedingToken.end > position) { + return 0; + } + var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; + // indentation is first non-whitespace character in a previous line + // for block indentation, we should look for a line which contains something that's not + // whitespace. + if (options.IndentStyle === ts.IndentStyle.Block) { + // move backwards until we find a line with a non-whitespace character, + // then find the first non-whitespace character for that line. + var current_1 = position; + while (current_1 > 0) { + var char = sourceFile.text.charCodeAt(current_1); + if (!ts.isWhiteSpace(char) && !ts.isLineBreak(char)) { + break; + } + current_1--; + } + var lineStart = ts.getLineStartPositionForPosition(current_1, sourceFile); + return SmartIndenter.findFirstNonWhitespaceColumn(lineStart, current_1, sourceFile, options); + } + if (precedingToken.kind === 24 /* CommaToken */ && precedingToken.parent.kind !== 181 /* BinaryExpression */) { + // previous token is comma that separates items in list - find the previous item and try to derive indentation from it + var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation; + } + } + // try to find node that can contribute to indentation and includes 'position' starting from 'precedingToken' + // if such node is found - compute initial indentation for 'position' inside this node + var previous; + var current = precedingToken; + var currentStart; + var indentationDelta; + while (current) { + if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current.kind, previous ? previous.kind : 0 /* Unknown */)) { + currentStart = getStartLineAndCharacterForNode(current, sourceFile); + if (nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile)) { + indentationDelta = 0; + } + else { + indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0; + } + break; + } + // check if current node is a list item - if yes, take indentation from it + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation; + } + actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation + options.IndentSize; + } + previous = current; + current = current.parent; + } + if (!current) { + // no parent was found - return 0 to be indented on the level of SourceFile + return 0; + } + return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, options); + } + SmartIndenter.getIndentation = getIndentation; + function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { + var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); + return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, options); + } + SmartIndenter.getIndentationForNode = getIndentationForNode; + function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { + var parent = current.parent; + var parentStart; + // walk upwards and collect indentations for pairs of parent-child nodes + // indentation is not added if parent and child nodes start on the same line or if parent is IfStatement and child starts on the same line with 'else clause' + while (parent) { + var useActualIndentation = true; + if (ignoreActualIndentationRange) { + var start = current.getStart(sourceFile); + useActualIndentation = start < ignoreActualIndentationRange.pos || start > ignoreActualIndentationRange.end; + } + if (useActualIndentation) { + // check if current node is a list item - if yes, take indentation from it + var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation + indentationDelta; + } + } + parentStart = getParentStart(parent, current, sourceFile); + var parentAndChildShareLine = parentStart.line === currentStart.line || + childStartsOnTheSameLineWithElseInIfStatement(parent, current, currentStart.line, sourceFile); + if (useActualIndentation) { + // try to fetch actual indentation for current node from source text + var actualIndentation = getActualIndentationForNode(current, parent, currentStart, parentAndChildShareLine, sourceFile, options); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation + indentationDelta; + } + actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); + if (actualIndentation !== -1 /* Unknown */) { + return actualIndentation + indentationDelta; + } + } + // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line + if (shouldIndentChildNode(parent.kind, current.kind) && !parentAndChildShareLine) { + indentationDelta += options.IndentSize; + } + current = parent; + currentStart = parentStart; + parent = current.parent; + } + return indentationDelta; + } + function getParentStart(parent, child, sourceFile) { + var containingList = getContainingList(child, sourceFile); + if (containingList) { + return sourceFile.getLineAndCharacterOfPosition(containingList.pos); + } + return sourceFile.getLineAndCharacterOfPosition(parent.getStart(sourceFile)); + } + /* + * Function returns Value.Unknown if indentation cannot be determined + */ + function getActualIndentationForListItemBeforeComma(commaToken, sourceFile, options) { + // previous token is comma that separates items in list - find the previous item and try to derive indentation from it + var commaItemInfo = ts.findListItemInfo(commaToken); + if (commaItemInfo && commaItemInfo.listItemIndex > 0) { + return deriveActualIndentationFromList(commaItemInfo.list.getChildren(), commaItemInfo.listItemIndex - 1, sourceFile, options); + } + else { + // handle broken code gracefully + return -1 /* Unknown */; + } + } + /* + * Function returns Value.Unknown if actual indentation for node should not be used (i.e because node is nested expression) + */ + function getActualIndentationForNode(current, parent, currentLineAndChar, parentAndChildShareLine, sourceFile, options) { + // actual indentation is used for statements\declarations if one of cases below is true: + // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually + // - parent and child are not on the same line + var useActualIndentation = (ts.isDeclaration(current) || ts.isStatement(current)) && + (parent.kind === 248 /* SourceFile */ || !parentAndChildShareLine); + if (!useActualIndentation) { + return -1 /* Unknown */; + } + return findColumnForFirstNonWhitespaceCharacterInLine(currentLineAndChar, sourceFile, options); + } + function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) { + var nextToken = ts.findNextToken(precedingToken, current); + if (!nextToken) { + return false; + } + if (nextToken.kind === 15 /* OpenBraceToken */) { + // open braces are always indented at the parent level + return true; + } + else if (nextToken.kind === 16 /* CloseBraceToken */) { + // close braces are indented at the parent level if they are located on the same line with cursor + // this means that if new line will be added at $ position, this case will be indented + // class A { + // $ + // } + /// and this one - not + // class A { + // $} + var nextTokenStartLine = getStartLineAndCharacterForNode(nextToken, sourceFile).line; + return lineAtPosition === nextTokenStartLine; + } + return false; + } + function getStartLineAndCharacterForNode(n, sourceFile) { + return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); + } + function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { + if (parent.kind === 196 /* IfStatement */ && parent.elseStatement === child) { + var elseKeyword = ts.findChildOfKind(parent, 80 /* ElseKeyword */, sourceFile); + ts.Debug.assert(elseKeyword !== undefined); + var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; + return elseKeywordStartLine === childStartLine; + } + return false; + } + SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement = childStartsOnTheSameLineWithElseInIfStatement; + function getContainingList(node, sourceFile) { + if (node.parent) { + switch (node.parent.kind) { + case 151 /* TypeReference */: + if (node.parent.typeArguments && + ts.rangeContainsStartEnd(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd())) { + return node.parent.typeArguments; + } + break; + case 165 /* ObjectLiteralExpression */: + return node.parent.properties; + case 164 /* ArrayLiteralExpression */: + return node.parent.elements; + case 213 /* FunctionDeclaration */: + case 173 /* FunctionExpression */: + case 174 /* ArrowFunction */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 147 /* CallSignature */: + case 148 /* ConstructSignature */: { + var start = node.getStart(sourceFile); + if (node.parent.typeParameters && + ts.rangeContainsStartEnd(node.parent.typeParameters, start, node.getEnd())) { + return node.parent.typeParameters; + } + if (ts.rangeContainsStartEnd(node.parent.parameters, start, node.getEnd())) { + return node.parent.parameters; + } + break; + } + case 169 /* NewExpression */: + case 168 /* CallExpression */: { + var start = node.getStart(sourceFile); + if (node.parent.typeArguments && + ts.rangeContainsStartEnd(node.parent.typeArguments, start, node.getEnd())) { + return node.parent.typeArguments; + } + if (node.parent.arguments && + ts.rangeContainsStartEnd(node.parent.arguments, start, node.getEnd())) { + return node.parent.arguments; + } + break; + } + } + } + return undefined; + } + function getActualIndentationForListItem(node, sourceFile, options) { + var containingList = getContainingList(node, sourceFile); + return containingList ? getActualIndentationFromList(containingList) : -1 /* Unknown */; + function getActualIndentationFromList(list) { + var index = ts.indexOf(list, node); + return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : -1 /* Unknown */; + } + } + function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { + // actual indentation should not be used when: + // - node is close parenthesis - this is the end of the expression + if (node.kind === 18 /* CloseParenToken */) { + return -1 /* Unknown */; + } + if (node.parent && (node.parent.kind === 168 /* CallExpression */ || + node.parent.kind === 169 /* NewExpression */) && + node.parent.expression !== node) { + var fullCallOrNewExpression = node.parent.expression; + var startingExpression = getStartingExpression(fullCallOrNewExpression); + if (fullCallOrNewExpression === startingExpression) { + return -1 /* Unknown */; + } + var fullCallOrNewExpressionEnd = sourceFile.getLineAndCharacterOfPosition(fullCallOrNewExpression.end); + var startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end); + if (fullCallOrNewExpressionEnd.line === startingExpressionEnd.line) { + return -1 /* Unknown */; + } + return findColumnForFirstNonWhitespaceCharacterInLine(fullCallOrNewExpressionEnd, sourceFile, options); + } + return -1 /* Unknown */; + function getStartingExpression(node) { + while (true) { + switch (node.kind) { + case 168 /* CallExpression */: + case 169 /* NewExpression */: + case 166 /* PropertyAccessExpression */: + case 167 /* ElementAccessExpression */: + node = node.expression; + break; + default: + return node; + } + } + return node; + } + } + function deriveActualIndentationFromList(list, index, sourceFile, options) { + ts.Debug.assert(index >= 0 && index < list.length); + var node = list[index]; + // walk toward the start of the list starting from current node and check if the line is the same for all items. + // if end line for item [i - 1] differs from the start line for item [i] - find column of the first non-whitespace character on the line of item [i] + var lineAndCharacter = getStartLineAndCharacterForNode(node, sourceFile); + for (var i = index - 1; i >= 0; --i) { + if (list[i].kind === 24 /* CommaToken */) { + continue; + } + // skip list items that ends on the same line with the current list element + var prevEndLine = sourceFile.getLineAndCharacterOfPosition(list[i].end).line; + if (prevEndLine !== lineAndCharacter.line) { + return findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options); + } + lineAndCharacter = getStartLineAndCharacterForNode(list[i], sourceFile); + } + return -1 /* Unknown */; + } + function findColumnForFirstNonWhitespaceCharacterInLine(lineAndCharacter, sourceFile, options) { + var lineStart = sourceFile.getPositionOfLineAndCharacter(lineAndCharacter.line, 0); + return findFirstNonWhitespaceColumn(lineStart, lineStart + lineAndCharacter.character, sourceFile, options); + } + /* + Character is the actual index of the character since the beginning of the line. + Column - position of the character after expanding tabs to spaces + "0\t2$" + value of 'character' for '$' is 3 + value of 'column' for '$' is 6 (assuming that tab size is 4) + */ + function findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options) { + var character = 0; + var column = 0; + for (var pos = startPos; pos < endPos; ++pos) { + var ch = sourceFile.text.charCodeAt(pos); + if (!ts.isWhiteSpace(ch)) { + break; + } + if (ch === 9 /* tab */) { + column += options.TabSize + (column % options.TabSize); + } + else { + column++; + } + character++; + } + return { column: column, character: character }; + } + SmartIndenter.findFirstNonWhitespaceCharacterAndColumn = findFirstNonWhitespaceCharacterAndColumn; + function findFirstNonWhitespaceColumn(startPos, endPos, sourceFile, options) { + return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column; + } + SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; + function nodeContentIsAlwaysIndented(kind) { + switch (kind) { + case 195 /* ExpressionStatement */: + case 214 /* ClassDeclaration */: + case 186 /* ClassExpression */: + case 215 /* InterfaceDeclaration */: + case 217 /* EnumDeclaration */: + case 216 /* TypeAliasDeclaration */: + case 164 /* ArrayLiteralExpression */: + case 192 /* Block */: + case 219 /* ModuleBlock */: + case 165 /* ObjectLiteralExpression */: + case 155 /* TypeLiteral */: + case 157 /* TupleType */: + case 220 /* CaseBlock */: + case 242 /* DefaultClause */: + case 241 /* CaseClause */: + case 172 /* ParenthesizedExpression */: + case 166 /* PropertyAccessExpression */: + case 168 /* CallExpression */: + case 169 /* NewExpression */: + case 193 /* VariableStatement */: + case 211 /* VariableDeclaration */: + case 227 /* ExportAssignment */: + case 204 /* ReturnStatement */: + case 182 /* ConditionalExpression */: + case 162 /* ArrayBindingPattern */: + case 161 /* ObjectBindingPattern */: + case 233 /* JsxElement */: + case 234 /* JsxSelfClosingElement */: + case 142 /* MethodSignature */: + case 147 /* CallSignature */: + case 148 /* ConstructSignature */: + case 138 /* Parameter */: + case 152 /* FunctionType */: + case 153 /* ConstructorType */: + case 160 /* ParenthesizedType */: + case 170 /* TaggedTemplateExpression */: + case 178 /* AwaitExpression */: + return true; + } + return false; + } + function shouldIndentChildNode(parent, child) { + if (nodeContentIsAlwaysIndented(parent)) { + return true; + } + switch (parent) { + case 197 /* DoStatement */: + case 198 /* WhileStatement */: + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + case 199 /* ForStatement */: + case 196 /* IfStatement */: + case 213 /* FunctionDeclaration */: + case 173 /* FunctionExpression */: + case 143 /* MethodDeclaration */: + case 174 /* ArrowFunction */: + case 144 /* Constructor */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + return child !== 192 /* Block */; + default: + return false; + } + } + SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; + })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +/// +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +/// +/// +/// +/// +/// +/// +/// +/// +/// +var ts; +(function (ts) { + /** The version of the language service API */ + ts.servicesVersion = "0.4"; + var ScriptSnapshot; + (function (ScriptSnapshot) { + var StringScriptSnapshot = (function () { + function StringScriptSnapshot(text) { + this.text = text; + } + StringScriptSnapshot.prototype.getText = function (start, end) { + return this.text.substring(start, end); + }; + StringScriptSnapshot.prototype.getLength = function () { + return this.text.length; + }; + StringScriptSnapshot.prototype.getChangeRange = function (oldSnapshot) { + // Text-based snapshots do not support incremental parsing. Return undefined + // to signal that to the caller. + return undefined; + }; + return StringScriptSnapshot; + })(); + function fromString(text) { + return new StringScriptSnapshot(text); + } + ScriptSnapshot.fromString = fromString; + })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); + var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ true); + var emptyArray = []; + var jsDocTagNames = [ + "augments", + "author", + "argument", + "borrows", + "class", + "constant", + "constructor", + "constructs", + "default", + "deprecated", + "description", + "event", + "example", + "extends", + "field", + "fileOverview", + "function", + "ignore", + "inner", + "lends", + "link", + "memberOf", + "name", + "namespace", + "param", + "private", + "property", + "public", + "requires", + "returns", + "see", + "since", + "static", + "throws", + "type", + "version" + ]; + var jsDocCompletionEntries; + function createNode(kind, pos, end, flags, parent) { + var node = new (ts.getNodeConstructor(kind))(); + node.pos = pos; + node.end = end; + node.flags = flags; + node.parent = parent; + return node; + } + var NodeObject = (function () { + function NodeObject() { + } + NodeObject.prototype.getSourceFile = function () { + return ts.getSourceFileOfNode(this); + }; + NodeObject.prototype.getStart = function (sourceFile) { + return ts.getTokenPosOfNode(this, sourceFile); + }; + NodeObject.prototype.getFullStart = function () { + return this.pos; + }; + NodeObject.prototype.getEnd = function () { + return this.end; + }; + NodeObject.prototype.getWidth = function (sourceFile) { + return this.getEnd() - this.getStart(sourceFile); + }; + NodeObject.prototype.getFullWidth = function () { + return this.end - this.pos; + }; + NodeObject.prototype.getLeadingTriviaWidth = function (sourceFile) { + return this.getStart(sourceFile) - this.pos; + }; + NodeObject.prototype.getFullText = function (sourceFile) { + return (sourceFile || this.getSourceFile()).text.substring(this.pos, this.end); + }; + NodeObject.prototype.getText = function (sourceFile) { + return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd()); + }; + NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end) { + scanner.setTextPos(pos); + while (pos < end) { + var token = scanner.scan(); + var textPos = scanner.getTextPos(); + nodes.push(createNode(token, pos, textPos, 4096 /* Synthetic */, this)); + pos = textPos; + } + return pos; + }; + NodeObject.prototype.createSyntaxList = function (nodes) { + var list = createNode(271 /* SyntaxList */, nodes.pos, nodes.end, 4096 /* Synthetic */, this); + list._children = []; + var pos = nodes.pos; + for (var _i = 0; _i < nodes.length; _i++) { + var node = nodes[_i]; + if (pos < node.pos) { + pos = this.addSyntheticNodes(list._children, pos, node.pos); + } + list._children.push(node); + pos = node.end; + } + if (pos < nodes.end) { + this.addSyntheticNodes(list._children, pos, nodes.end); + } + return list; + }; + NodeObject.prototype.createChildren = function (sourceFile) { + var _this = this; + var children; + if (this.kind >= 135 /* FirstNode */) { + scanner.setText((sourceFile || this.getSourceFile()).text); + children = []; + var pos = this.pos; + var processNode = function (node) { + if (pos < node.pos) { + pos = _this.addSyntheticNodes(children, pos, node.pos); + } + children.push(node); + pos = node.end; + }; + var processNodes = function (nodes) { + if (pos < nodes.pos) { + pos = _this.addSyntheticNodes(children, pos, nodes.pos); + } + children.push(_this.createSyntaxList(nodes)); + pos = nodes.end; + }; + ts.forEachChild(this, processNode, processNodes); + if (pos < this.end) { + this.addSyntheticNodes(children, pos, this.end); + } + scanner.setText(undefined); + } + this._children = children || emptyArray; + }; + NodeObject.prototype.getChildCount = function (sourceFile) { + if (!this._children) + this.createChildren(sourceFile); + return this._children.length; + }; + NodeObject.prototype.getChildAt = function (index, sourceFile) { + if (!this._children) + this.createChildren(sourceFile); + return this._children[index]; + }; + NodeObject.prototype.getChildren = function (sourceFile) { + if (!this._children) + this.createChildren(sourceFile); + return this._children; + }; + NodeObject.prototype.getFirstToken = function (sourceFile) { + var children = this.getChildren(sourceFile); + if (!children.length) { + return undefined; + } + var child = children[0]; + return child.kind < 135 /* FirstNode */ ? child : child.getFirstToken(sourceFile); + }; + NodeObject.prototype.getLastToken = function (sourceFile) { + var children = this.getChildren(sourceFile); + var child = ts.lastOrUndefined(children); + if (!child) { + return undefined; + } + return child.kind < 135 /* FirstNode */ ? child : child.getLastToken(sourceFile); + }; + return NodeObject; + })(); + var SymbolObject = (function () { + function SymbolObject(flags, name) { + this.flags = flags; + this.name = name; + } + SymbolObject.prototype.getFlags = function () { + return this.flags; + }; + SymbolObject.prototype.getName = function () { + return this.name; + }; + SymbolObject.prototype.getDeclarations = function () { + return this.declarations; + }; + SymbolObject.prototype.getDocumentationComment = function () { + if (this.documentationComment === undefined) { + this.documentationComment = getJsDocCommentsFromDeclarations(this.declarations, this.name, !(this.flags & 4 /* Property */)); + } + return this.documentationComment; + }; + return SymbolObject; + })(); + function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { + var documentationComment = []; + var docComments = getJsDocCommentsSeparatedByNewLines(); + ts.forEach(docComments, function (docComment) { + if (documentationComment.length) { + documentationComment.push(ts.lineBreakPart()); + } + documentationComment.push(docComment); + }); + return documentationComment; + function getJsDocCommentsSeparatedByNewLines() { + var paramTag = "@param"; + var jsDocCommentParts = []; + ts.forEach(declarations, function (declaration, indexOfDeclaration) { + // Make sure we are collecting doc comment from declaration once, + // In case of union property there might be same declaration multiple times + // which only varies in type parameter + // Eg. let a: Array | Array; a.length + // The property length will have two declarations of property length coming + // from Array - Array and Array + if (ts.indexOf(declarations, declaration) === indexOfDeclaration) { + var sourceFileOfDeclaration = ts.getSourceFileOfNode(declaration); + // If it is parameter - try and get the jsDoc comment with @param tag from function declaration's jsDoc comments + if (canUseParsedParamTagComments && declaration.kind === 138 /* Parameter */) { + ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration), function (jsDocCommentTextRange) { + var cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); + if (cleanedParamJsDocComment) { + ts.addRange(jsDocCommentParts, cleanedParamJsDocComment); + } + }); + } + // If this is left side of dotted module declaration, there is no doc comments associated with this node + if (declaration.kind === 218 /* ModuleDeclaration */ && declaration.body.kind === 218 /* ModuleDeclaration */) { + return; + } + // If this is dotted module name, get the doc comments from the parent + while (declaration.kind === 218 /* ModuleDeclaration */ && declaration.parent.kind === 218 /* ModuleDeclaration */) { + declaration = declaration.parent; + } + // Get the cleaned js doc comment text from the declaration + ts.forEach(getJsDocCommentTextRange(declaration.kind === 211 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { + var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); + if (cleanedJsDocComment) { + ts.addRange(jsDocCommentParts, cleanedJsDocComment); + } + }); + } + }); + return jsDocCommentParts; + function getJsDocCommentTextRange(node, sourceFile) { + return ts.map(ts.getJsDocComments(node, sourceFile), function (jsDocComment) { + return { + pos: jsDocComment.pos + "/*".length, + end: jsDocComment.end - "*/".length // Trim off comment end indicator + }; + }); + } + function consumeWhiteSpacesOnTheLine(pos, end, sourceFile, maxSpacesToRemove) { + if (maxSpacesToRemove !== undefined) { + end = Math.min(end, pos + maxSpacesToRemove); + } + for (; pos < end; pos++) { + var ch = sourceFile.text.charCodeAt(pos); + if (!ts.isWhiteSpace(ch) || ts.isLineBreak(ch)) { + // Either found lineBreak or non whiteSpace + return pos; + } + } + return end; + } + function consumeLineBreaks(pos, end, sourceFile) { + while (pos < end && ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { + pos++; + } + return pos; + } + function isName(pos, end, sourceFile, name) { + return pos + name.length < end && + sourceFile.text.substr(pos, name.length) === name && + (ts.isWhiteSpace(sourceFile.text.charCodeAt(pos + name.length)) || + ts.isLineBreak(sourceFile.text.charCodeAt(pos + name.length))); + } + function isParamTag(pos, end, sourceFile) { + // If it is @param tag + return isName(pos, end, sourceFile, paramTag); + } + function pushDocCommentLineText(docComments, text, blankLineCount) { + // Add the empty lines in between texts + while (blankLineCount--) { + docComments.push(ts.textPart("")); + } + docComments.push(ts.textPart(text)); + } + function getCleanedJsDocComment(pos, end, sourceFile) { + var spacesToRemoveAfterAsterisk; + var docComments = []; + var blankLineCount = 0; + var isInParamTag = false; + while (pos < end) { + var docCommentTextOfLine = ""; + // First consume leading white space + pos = consumeWhiteSpacesOnTheLine(pos, end, sourceFile); + // If the comment starts with '*' consume the spaces on this line + if (pos < end && sourceFile.text.charCodeAt(pos) === 42 /* asterisk */) { + var lineStartPos = pos + 1; + pos = consumeWhiteSpacesOnTheLine(pos + 1, end, sourceFile, spacesToRemoveAfterAsterisk); + // Set the spaces to remove after asterisk as margin if not already set + if (spacesToRemoveAfterAsterisk === undefined && pos < end && !ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { + spacesToRemoveAfterAsterisk = pos - lineStartPos; + } + } + else if (spacesToRemoveAfterAsterisk === undefined) { + spacesToRemoveAfterAsterisk = 0; + } + // Analyse text on this line + while (pos < end && !ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { + var ch = sourceFile.text.charAt(pos); + if (ch === "@") { + // If it is @param tag + if (isParamTag(pos, end, sourceFile)) { + isInParamTag = true; + pos += paramTag.length; + continue; + } + else { + isInParamTag = false; + } + } + // Add the ch to doc text if we arent in param tag + if (!isInParamTag) { + docCommentTextOfLine += ch; + } + // Scan next character + pos++; + } + // Continue with next line + pos = consumeLineBreaks(pos, end, sourceFile); + if (docCommentTextOfLine) { + pushDocCommentLineText(docComments, docCommentTextOfLine, blankLineCount); + blankLineCount = 0; + } + else if (!isInParamTag && docComments.length) { + // This is blank line when there is text already parsed + blankLineCount++; + } + } + return docComments; + } + function getCleanedParamJsDocComment(pos, end, sourceFile) { + var paramHelpStringMargin; + var paramDocComments = []; + while (pos < end) { + if (isParamTag(pos, end, sourceFile)) { + var blankLineCount = 0; + var recordedParamTag = false; + // Consume leading spaces + pos = consumeWhiteSpaces(pos + paramTag.length); + if (pos >= end) { + break; + } + // Ignore type expression + if (sourceFile.text.charCodeAt(pos) === 123 /* openBrace */) { + pos++; + for (var curlies = 1; pos < end; pos++) { + var charCode = sourceFile.text.charCodeAt(pos); + // { character means we need to find another } to match the found one + if (charCode === 123 /* openBrace */) { + curlies++; + continue; + } + // } char + if (charCode === 125 /* closeBrace */) { + curlies--; + if (curlies === 0) { + // We do not have any more } to match the type expression is ignored completely + pos++; + break; + } + else { + // there are more { to be matched with } + continue; + } + } + // Found start of another tag + if (charCode === 64 /* at */) { + break; + } + } + // Consume white spaces + pos = consumeWhiteSpaces(pos); + if (pos >= end) { + break; + } + } + // Parameter name + if (isName(pos, end, sourceFile, name)) { + // Found the parameter we are looking for consume white spaces + pos = consumeWhiteSpaces(pos + name.length); + if (pos >= end) { + break; + } + var paramHelpString = ""; + var firstLineParamHelpStringPos = pos; + while (pos < end) { + var ch = sourceFile.text.charCodeAt(pos); + // at line break, set this comment line text and go to next line + if (ts.isLineBreak(ch)) { + if (paramHelpString) { + pushDocCommentLineText(paramDocComments, paramHelpString, blankLineCount); + paramHelpString = ""; + blankLineCount = 0; + recordedParamTag = true; + } + else if (recordedParamTag) { + blankLineCount++; + } + // Get the pos after cleaning start of the line + setPosForParamHelpStringOnNextLine(firstLineParamHelpStringPos); + continue; + } + // Done scanning param help string - next tag found + if (ch === 64 /* at */) { + break; + } + paramHelpString += sourceFile.text.charAt(pos); + // Go to next character + pos++; + } + // If there is param help text, add it top the doc comments + if (paramHelpString) { + pushDocCommentLineText(paramDocComments, paramHelpString, blankLineCount); + } + paramHelpStringMargin = undefined; + } + // If this is the start of another tag, continue with the loop in seach of param tag with symbol name + if (sourceFile.text.charCodeAt(pos) === 64 /* at */) { + continue; + } + } + // Next character + pos++; + } + return paramDocComments; + function consumeWhiteSpaces(pos) { + while (pos < end && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { + pos++; + } + return pos; + } + function setPosForParamHelpStringOnNextLine(firstLineParamHelpStringPos) { + // Get the pos after consuming line breaks + pos = consumeLineBreaks(pos, end, sourceFile); + if (pos >= end) { + return; + } + if (paramHelpStringMargin === undefined) { + paramHelpStringMargin = sourceFile.getLineAndCharacterOfPosition(firstLineParamHelpStringPos).character; + } + // Now consume white spaces max + var startOfLinePos = pos; + pos = consumeWhiteSpacesOnTheLine(pos, end, sourceFile, paramHelpStringMargin); + if (pos >= end) { + return; + } + var consumedSpaces = pos - startOfLinePos; + if (consumedSpaces < paramHelpStringMargin) { + var ch = sourceFile.text.charCodeAt(pos); + if (ch === 42 /* asterisk */) { + // Consume more spaces after asterisk + pos = consumeWhiteSpacesOnTheLine(pos + 1, end, sourceFile, paramHelpStringMargin - consumedSpaces - 1); + } + } + } + } + } + } + var TypeObject = (function () { + function TypeObject(checker, flags) { + this.checker = checker; + this.flags = flags; + } + TypeObject.prototype.getFlags = function () { + return this.flags; + }; + TypeObject.prototype.getSymbol = function () { + return this.symbol; + }; + TypeObject.prototype.getProperties = function () { + return this.checker.getPropertiesOfType(this); + }; + TypeObject.prototype.getProperty = function (propertyName) { + return this.checker.getPropertyOfType(this, propertyName); + }; + TypeObject.prototype.getApparentProperties = function () { + return this.checker.getAugmentedPropertiesOfType(this); + }; + TypeObject.prototype.getCallSignatures = function () { + return this.checker.getSignaturesOfType(this, 0 /* Call */); + }; + TypeObject.prototype.getConstructSignatures = function () { + return this.checker.getSignaturesOfType(this, 1 /* Construct */); + }; + TypeObject.prototype.getStringIndexType = function () { + return this.checker.getIndexTypeOfType(this, 0 /* String */); + }; + TypeObject.prototype.getNumberIndexType = function () { + return this.checker.getIndexTypeOfType(this, 1 /* Number */); + }; + TypeObject.prototype.getBaseTypes = function () { + return this.flags & (1024 /* Class */ | 2048 /* Interface */) + ? this.checker.getBaseTypes(this) + : undefined; + }; + return TypeObject; + })(); + var SignatureObject = (function () { + function SignatureObject(checker) { + this.checker = checker; + } + SignatureObject.prototype.getDeclaration = function () { + return this.declaration; + }; + SignatureObject.prototype.getTypeParameters = function () { + return this.typeParameters; + }; + SignatureObject.prototype.getParameters = function () { + return this.parameters; + }; + SignatureObject.prototype.getReturnType = function () { + return this.checker.getReturnTypeOfSignature(this); + }; + SignatureObject.prototype.getDocumentationComment = function () { + if (this.documentationComment === undefined) { + this.documentationComment = this.declaration ? getJsDocCommentsFromDeclarations([this.declaration], + /*name*/ undefined, + /*canUseParsedParamTagComments*/ false) : []; + } + return this.documentationComment; + }; + return SignatureObject; + })(); + var SourceFileObject = (function (_super) { + __extends(SourceFileObject, _super); + function SourceFileObject() { + _super.apply(this, arguments); + } + SourceFileObject.prototype.update = function (newText, textChangeRange) { + return ts.updateSourceFile(this, newText, textChangeRange); + }; + SourceFileObject.prototype.getLineAndCharacterOfPosition = function (position) { + return ts.getLineAndCharacterOfPosition(this, position); + }; + SourceFileObject.prototype.getLineStarts = function () { + return ts.getLineStarts(this); + }; + SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character) { + return ts.getPositionOfLineAndCharacter(this, line, character); + }; + SourceFileObject.prototype.getNamedDeclarations = function () { + if (!this.namedDeclarations) { + this.namedDeclarations = this.computeNamedDeclarations(); + } + return this.namedDeclarations; + }; + SourceFileObject.prototype.computeNamedDeclarations = function () { + var result = {}; + ts.forEachChild(this, visit); + return result; + function addDeclaration(declaration) { + var name = getDeclarationName(declaration); + if (name) { + var declarations = getDeclarations(name); + declarations.push(declaration); + } + } + function getDeclarations(name) { + return ts.getProperty(result, name) || (result[name] = []); + } + function getDeclarationName(declaration) { + if (declaration.name) { + var result_2 = getTextOfIdentifierOrLiteral(declaration.name); + if (result_2 !== undefined) { + return result_2; + } + if (declaration.name.kind === 136 /* ComputedPropertyName */) { + var expr = declaration.name.expression; + if (expr.kind === 166 /* PropertyAccessExpression */) { + return expr.name.text; + } + return getTextOfIdentifierOrLiteral(expr); + } + } + return undefined; + } + function getTextOfIdentifierOrLiteral(node) { + if (node) { + if (node.kind === 69 /* Identifier */ || + node.kind === 9 /* StringLiteral */ || + node.kind === 8 /* NumericLiteral */) { + return node.text; + } + } + return undefined; + } + function visit(node) { + switch (node.kind) { + case 213 /* FunctionDeclaration */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + var functionDeclaration = node; + var declarationName = getDeclarationName(functionDeclaration); + if (declarationName) { + var declarations = getDeclarations(declarationName); + var lastDeclaration = ts.lastOrUndefined(declarations); + // Check whether this declaration belongs to an "overload group". + if (lastDeclaration && functionDeclaration.parent === lastDeclaration.parent && functionDeclaration.symbol === lastDeclaration.symbol) { + // Overwrite the last declaration if it was an overload + // and this one is an implementation. + if (functionDeclaration.body && !lastDeclaration.body) { + declarations[declarations.length - 1] = functionDeclaration; + } + } + else { + declarations.push(functionDeclaration); + } + ts.forEachChild(node, visit); + } + break; + case 214 /* ClassDeclaration */: + case 215 /* InterfaceDeclaration */: + case 216 /* TypeAliasDeclaration */: + case 217 /* EnumDeclaration */: + case 218 /* ModuleDeclaration */: + case 221 /* ImportEqualsDeclaration */: + case 230 /* ExportSpecifier */: + case 226 /* ImportSpecifier */: + case 221 /* ImportEqualsDeclaration */: + case 223 /* ImportClause */: + case 224 /* NamespaceImport */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 155 /* TypeLiteral */: + addDeclaration(node); + // fall through + case 144 /* Constructor */: + case 193 /* VariableStatement */: + case 212 /* VariableDeclarationList */: + case 161 /* ObjectBindingPattern */: + case 162 /* ArrayBindingPattern */: + case 219 /* ModuleBlock */: + ts.forEachChild(node, visit); + break; + case 192 /* Block */: + if (ts.isFunctionBlock(node)) { + ts.forEachChild(node, visit); + } + break; + case 138 /* Parameter */: + // Only consider properties defined as constructor parameters + if (!(node.flags & 112 /* AccessibilityModifier */)) { + break; + } + // fall through + case 211 /* VariableDeclaration */: + case 163 /* BindingElement */: + if (ts.isBindingPattern(node.name)) { + ts.forEachChild(node.name, visit); + break; + } + case 247 /* EnumMember */: + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + addDeclaration(node); + break; + case 228 /* ExportDeclaration */: + // Handle named exports case e.g.: + // export {a, b as B} from "mod"; + if (node.exportClause) { + ts.forEach(node.exportClause.elements, visit); + } + break; + case 222 /* ImportDeclaration */: + var importClause = node.importClause; + if (importClause) { + // Handle default import case e.g.: + // import d from "mod"; + if (importClause.name) { + addDeclaration(importClause); + } + // Handle named bindings in imports e.g.: + // import * as NS from "mod"; + // import {a, b as B} from "mod"; + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 224 /* NamespaceImport */) { + addDeclaration(importClause.namedBindings); + } + else { + ts.forEach(importClause.namedBindings.elements, visit); + } + } + } + break; + } + } + }; + return SourceFileObject; + })(NodeObject); + var TextChange = (function () { + function TextChange() { + } + return TextChange; + })(); + ts.TextChange = TextChange; + var HighlightSpanKind; + (function (HighlightSpanKind) { + HighlightSpanKind.none = "none"; + HighlightSpanKind.definition = "definition"; + HighlightSpanKind.reference = "reference"; + HighlightSpanKind.writtenReference = "writtenReference"; + })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); + (function (IndentStyle) { + IndentStyle[IndentStyle["None"] = 0] = "None"; + IndentStyle[IndentStyle["Block"] = 1] = "Block"; + IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; + })(ts.IndentStyle || (ts.IndentStyle = {})); + var IndentStyle = ts.IndentStyle; + (function (SymbolDisplayPartKind) { + SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["className"] = 1] = "className"; + SymbolDisplayPartKind[SymbolDisplayPartKind["enumName"] = 2] = "enumName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["fieldName"] = 3] = "fieldName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["interfaceName"] = 4] = "interfaceName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["keyword"] = 5] = "keyword"; + SymbolDisplayPartKind[SymbolDisplayPartKind["lineBreak"] = 6] = "lineBreak"; + SymbolDisplayPartKind[SymbolDisplayPartKind["numericLiteral"] = 7] = "numericLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["stringLiteral"] = 8] = "stringLiteral"; + SymbolDisplayPartKind[SymbolDisplayPartKind["localName"] = 9] = "localName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["methodName"] = 10] = "methodName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["moduleName"] = 11] = "moduleName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["operator"] = 12] = "operator"; + SymbolDisplayPartKind[SymbolDisplayPartKind["parameterName"] = 13] = "parameterName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["propertyName"] = 14] = "propertyName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["punctuation"] = 15] = "punctuation"; + SymbolDisplayPartKind[SymbolDisplayPartKind["space"] = 16] = "space"; + SymbolDisplayPartKind[SymbolDisplayPartKind["text"] = 17] = "text"; + SymbolDisplayPartKind[SymbolDisplayPartKind["typeParameterName"] = 18] = "typeParameterName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["enumMemberName"] = 19] = "enumMemberName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; + SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; + })(ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); + var SymbolDisplayPartKind = ts.SymbolDisplayPartKind; + (function (OutputFileType) { + OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; + OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap"; + OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration"; + })(ts.OutputFileType || (ts.OutputFileType = {})); + var OutputFileType = ts.OutputFileType; + (function (EndOfLineState) { + EndOfLineState[EndOfLineState["None"] = 0] = "None"; + EndOfLineState[EndOfLineState["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia"; + EndOfLineState[EndOfLineState["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral"; + EndOfLineState[EndOfLineState["InDoubleQuoteStringLiteral"] = 3] = "InDoubleQuoteStringLiteral"; + EndOfLineState[EndOfLineState["InTemplateHeadOrNoSubstitutionTemplate"] = 4] = "InTemplateHeadOrNoSubstitutionTemplate"; + EndOfLineState[EndOfLineState["InTemplateMiddleOrTail"] = 5] = "InTemplateMiddleOrTail"; + EndOfLineState[EndOfLineState["InTemplateSubstitutionPosition"] = 6] = "InTemplateSubstitutionPosition"; + })(ts.EndOfLineState || (ts.EndOfLineState = {})); + var EndOfLineState = ts.EndOfLineState; + (function (TokenClass) { + TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; + TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; + TokenClass[TokenClass["Operator"] = 2] = "Operator"; + TokenClass[TokenClass["Comment"] = 3] = "Comment"; + TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; + TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; + TokenClass[TokenClass["NumberLiteral"] = 6] = "NumberLiteral"; + TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; + TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; + })(ts.TokenClass || (ts.TokenClass = {})); + var TokenClass = ts.TokenClass; + // TODO: move these to enums + var ScriptElementKind; + (function (ScriptElementKind) { + ScriptElementKind.unknown = ""; + ScriptElementKind.warning = "warning"; + // predefined type (void) or keyword (class) + ScriptElementKind.keyword = "keyword"; + // top level script node + ScriptElementKind.scriptElement = "script"; + // module foo {} + ScriptElementKind.moduleElement = "module"; + // class X {} + ScriptElementKind.classElement = "class"; + // var x = class X {} + ScriptElementKind.localClassElement = "local class"; + // interface Y {} + ScriptElementKind.interfaceElement = "interface"; + // type T = ... + ScriptElementKind.typeElement = "type"; + // enum E + ScriptElementKind.enumElement = "enum"; + // Inside module and script only + // let v = .. + ScriptElementKind.variableElement = "var"; + // Inside function + ScriptElementKind.localVariableElement = "local var"; + // Inside module and script only + // function f() { } + ScriptElementKind.functionElement = "function"; + // Inside function + ScriptElementKind.localFunctionElement = "local function"; + // class X { [public|private]* foo() {} } + ScriptElementKind.memberFunctionElement = "method"; + // class X { [public|private]* [get|set] foo:number; } + ScriptElementKind.memberGetAccessorElement = "getter"; + ScriptElementKind.memberSetAccessorElement = "setter"; + // class X { [public|private]* foo:number; } + // interface Y { foo:number; } + ScriptElementKind.memberVariableElement = "property"; + // class X { constructor() { } } + ScriptElementKind.constructorImplementationElement = "constructor"; + // interface Y { ():number; } + ScriptElementKind.callSignatureElement = "call"; + // interface Y { []:number; } + ScriptElementKind.indexSignatureElement = "index"; + // interface Y { new():Y; } + ScriptElementKind.constructSignatureElement = "construct"; + // function foo(*Y*: string) + ScriptElementKind.parameterElement = "parameter"; + ScriptElementKind.typeParameterElement = "type parameter"; + ScriptElementKind.primitiveType = "primitive type"; + ScriptElementKind.label = "label"; + ScriptElementKind.alias = "alias"; + ScriptElementKind.constElement = "const"; + ScriptElementKind.letElement = "let"; + })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); + var ScriptElementKindModifier; + (function (ScriptElementKindModifier) { + ScriptElementKindModifier.none = ""; + ScriptElementKindModifier.publicMemberModifier = "public"; + ScriptElementKindModifier.privateMemberModifier = "private"; + ScriptElementKindModifier.protectedMemberModifier = "protected"; + ScriptElementKindModifier.exportedModifier = "export"; + ScriptElementKindModifier.ambientModifier = "declare"; + ScriptElementKindModifier.staticModifier = "static"; + ScriptElementKindModifier.abstractModifier = "abstract"; + })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); + var ClassificationTypeNames = (function () { + function ClassificationTypeNames() { + } + ClassificationTypeNames.comment = "comment"; + ClassificationTypeNames.identifier = "identifier"; + ClassificationTypeNames.keyword = "keyword"; + ClassificationTypeNames.numericLiteral = "number"; + ClassificationTypeNames.operator = "operator"; + ClassificationTypeNames.stringLiteral = "string"; + ClassificationTypeNames.whiteSpace = "whitespace"; + ClassificationTypeNames.text = "text"; + ClassificationTypeNames.punctuation = "punctuation"; + ClassificationTypeNames.className = "class name"; + ClassificationTypeNames.enumName = "enum name"; + ClassificationTypeNames.interfaceName = "interface name"; + ClassificationTypeNames.moduleName = "module name"; + ClassificationTypeNames.typeParameterName = "type parameter name"; + ClassificationTypeNames.typeAliasName = "type alias name"; + ClassificationTypeNames.parameterName = "parameter name"; + ClassificationTypeNames.docCommentTagName = "doc comment tag name"; + return ClassificationTypeNames; + })(); + ts.ClassificationTypeNames = ClassificationTypeNames; + (function (ClassificationType) { + ClassificationType[ClassificationType["comment"] = 1] = "comment"; + ClassificationType[ClassificationType["identifier"] = 2] = "identifier"; + ClassificationType[ClassificationType["keyword"] = 3] = "keyword"; + ClassificationType[ClassificationType["numericLiteral"] = 4] = "numericLiteral"; + ClassificationType[ClassificationType["operator"] = 5] = "operator"; + ClassificationType[ClassificationType["stringLiteral"] = 6] = "stringLiteral"; + ClassificationType[ClassificationType["regularExpressionLiteral"] = 7] = "regularExpressionLiteral"; + ClassificationType[ClassificationType["whiteSpace"] = 8] = "whiteSpace"; + ClassificationType[ClassificationType["text"] = 9] = "text"; + ClassificationType[ClassificationType["punctuation"] = 10] = "punctuation"; + ClassificationType[ClassificationType["className"] = 11] = "className"; + ClassificationType[ClassificationType["enumName"] = 12] = "enumName"; + ClassificationType[ClassificationType["interfaceName"] = 13] = "interfaceName"; + ClassificationType[ClassificationType["moduleName"] = 14] = "moduleName"; + ClassificationType[ClassificationType["typeParameterName"] = 15] = "typeParameterName"; + ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName"; + ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName"; + ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName"; + })(ts.ClassificationType || (ts.ClassificationType = {})); + var ClassificationType = ts.ClassificationType; + function displayPartsToString(displayParts) { + if (displayParts) { + return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); + } + return ""; + } + ts.displayPartsToString = displayPartsToString; + function isLocalVariableOrFunction(symbol) { + if (symbol.parent) { + return false; // This is exported symbol + } + return ts.forEach(symbol.declarations, function (declaration) { + // Function expressions are local + if (declaration.kind === 173 /* FunctionExpression */) { + return true; + } + if (declaration.kind !== 211 /* VariableDeclaration */ && declaration.kind !== 213 /* FunctionDeclaration */) { + return false; + } + // If the parent is not sourceFile or module block it is local variable + for (var parent_8 = declaration.parent; !ts.isFunctionBlock(parent_8); parent_8 = parent_8.parent) { + // Reached source file or module block + if (parent_8.kind === 248 /* SourceFile */ || parent_8.kind === 219 /* ModuleBlock */) { + return false; + } + } + // parent is in function block + return true; + }); + } + function getDefaultCompilerOptions() { + // Always default to "ScriptTarget.ES5" for the language service + return { + target: 1 /* ES5 */, + module: 0 /* None */, + jsx: 1 /* Preserve */ + }; + } + ts.getDefaultCompilerOptions = getDefaultCompilerOptions; + // Cache host information about scrip Should be refreshed + // at each language service public entry point, since we don't know when + // set of scripts handled by the host changes. + var HostCache = (function () { + function HostCache(host, getCanonicalFileName) { + this.host = host; + // script id => script index + this.fileNameToEntry = ts.createFileMap(getCanonicalFileName); + // Initialize the list with the root file names + var rootFileNames = host.getScriptFileNames(); + for (var _i = 0; _i < rootFileNames.length; _i++) { + var fileName = rootFileNames[_i]; + this.createEntry(fileName); + } + // store the compilation settings + this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); + } + HostCache.prototype.compilationSettings = function () { + return this._compilationSettings; + }; + HostCache.prototype.createEntry = function (fileName) { + var entry; + var scriptSnapshot = this.host.getScriptSnapshot(fileName); + if (scriptSnapshot) { + entry = { + hostFileName: fileName, + version: this.host.getScriptVersion(fileName), + scriptSnapshot: scriptSnapshot + }; + } + this.fileNameToEntry.set(fileName, entry); + return entry; + }; + HostCache.prototype.getEntry = function (fileName) { + return this.fileNameToEntry.get(fileName); + }; + HostCache.prototype.contains = function (fileName) { + return this.fileNameToEntry.contains(fileName); + }; + HostCache.prototype.getOrCreateEntry = function (fileName) { + if (this.contains(fileName)) { + return this.getEntry(fileName); + } + return this.createEntry(fileName); + }; + HostCache.prototype.getRootFileNames = function () { + var fileNames = []; + this.fileNameToEntry.forEachValue(function (value) { + if (value) { + fileNames.push(value.hostFileName); + } + }); + return fileNames; + }; + HostCache.prototype.getVersion = function (fileName) { + var file = this.getEntry(fileName); + return file && file.version; + }; + HostCache.prototype.getScriptSnapshot = function (fileName) { + var file = this.getEntry(fileName); + return file && file.scriptSnapshot; + }; + return HostCache; + })(); + var SyntaxTreeCache = (function () { + function SyntaxTreeCache(host) { + this.host = host; + } + SyntaxTreeCache.prototype.getCurrentSourceFile = function (fileName) { + var scriptSnapshot = this.host.getScriptSnapshot(fileName); + if (!scriptSnapshot) { + // The host does not know about this file. + throw new Error("Could not find file: '" + fileName + "'."); + } + var version = this.host.getScriptVersion(fileName); + var sourceFile; + if (this.currentFileName !== fileName) { + // This is a new file, just parse it + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2 /* Latest */, version, /*setNodeParents:*/ true); + } + else if (this.currentFileVersion !== version) { + // This is the same file, just a newer version. Incrementally parse the file. + var editRange = scriptSnapshot.getChangeRange(this.currentFileScriptSnapshot); + sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version, editRange); + } + if (sourceFile) { + // All done, ensure state is up to date + this.currentFileVersion = version; + this.currentFileName = fileName; + this.currentFileScriptSnapshot = scriptSnapshot; + this.currentSourceFile = sourceFile; + } + return this.currentSourceFile; + }; + return SyntaxTreeCache; + })(); + function setSourceFileFields(sourceFile, scriptSnapshot, version) { + sourceFile.version = version; + sourceFile.scriptSnapshot = scriptSnapshot; + } + /* + * This function will compile source text from 'input' argument using specified compiler options. + * If not options are provided - it will use a set of default compiler options. + * Extra compiler options that will unconditionally be used by this function are: + * - isolatedModules = true + * - allowNonTsExtensions = true + * - noLib = true + * - noResolve = true + */ + function transpileModule(input, transpileOptions) { + var options = transpileOptions.compilerOptions ? ts.clone(transpileOptions.compilerOptions) : getDefaultCompilerOptions(); + options.isolatedModules = true; + // Filename can be non-ts file. + options.allowNonTsExtensions = true; + // We are not returning a sourceFile for lib file when asked by the program, + // so pass --noLib to avoid reporting a file not found error. + options.noLib = true; + // We are not doing a full typecheck, we are not resolving the whole context, + // so pass --noResolve to avoid reporting missing file errors. + options.noResolve = true; + // if jsx is specified then treat file as .tsx + var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); + var sourceFile = ts.createSourceFile(inputFileName, input, options.target); + if (transpileOptions.moduleName) { + sourceFile.moduleName = transpileOptions.moduleName; + } + sourceFile.renamedDependencies = transpileOptions.renamedDependencies; + var newLine = ts.getNewLineCharacter(options); + // Output + var outputText; + var sourceMapText; + // Create a compilerHost object to allow the compiler to read and write files + var compilerHost = { + getSourceFile: function (fileName, target) { return fileName === ts.normalizeSlashes(inputFileName) ? sourceFile : undefined; }, + writeFile: function (name, text, writeByteOrderMark) { + if (ts.fileExtensionIs(name, ".map")) { + ts.Debug.assert(sourceMapText === undefined, "Unexpected multiple source map outputs for the file '" + name + "'"); + sourceMapText = text; + } + else { + ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: " + name); + outputText = text; + } + }, + getDefaultLibFileName: function () { return "lib.d.ts"; }, + useCaseSensitiveFileNames: function () { return false; }, + getCanonicalFileName: function (fileName) { return fileName; }, + getCurrentDirectory: function () { return ""; }, + getNewLine: function () { return newLine; }, + fileExists: function (fileName) { return fileName === inputFileName; }, + readFile: function (fileName) { return ""; } + }; + var program = ts.createProgram([inputFileName], options, compilerHost); + var diagnostics; + if (transpileOptions.reportDiagnostics) { + diagnostics = []; + ts.addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile)); + ts.addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics()); + } + // Emit + program.emit(); + ts.Debug.assert(outputText !== undefined, "Output generation failed"); + return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; + } + ts.transpileModule = transpileModule; + /* + * This is a shortcut function for transpileModule - it accepts transpileOptions as parameters and returns only outputText part of the result. + */ + function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { + var output = transpileModule(input, { compilerOptions: compilerOptions, fileName: fileName, reportDiagnostics: !!diagnostics, moduleName: moduleName }); + // addRange correctly handles cases when wither 'from' or 'to' argument is missing + ts.addRange(diagnostics, output.diagnostics); + return output.outputText; + } + ts.transpile = transpile; + function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents) { + var text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); + var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents); + setSourceFileFields(sourceFile, scriptSnapshot, version); + // after full parsing we can use table with interned strings as name table + sourceFile.nameTable = sourceFile.identifiers; + return sourceFile; + } + ts.createLanguageServiceSourceFile = createLanguageServiceSourceFile; + ts.disableIncrementalParsing = false; + function updateLanguageServiceSourceFile(sourceFile, scriptSnapshot, version, textChangeRange, aggressiveChecks) { + // If we were given a text change range, and our version or open-ness changed, then + // incrementally parse this file. + if (textChangeRange) { + if (version !== sourceFile.version) { + // Once incremental parsing is ready, then just call into this function. + if (!ts.disableIncrementalParsing) { + var newText; + // grab the fragment from the beginning of the original text to the beginning of the span + var prefix = textChangeRange.span.start !== 0 + ? sourceFile.text.substr(0, textChangeRange.span.start) + : ""; + // grab the fragment from the end of the span till the end of the original text + var suffix = ts.textSpanEnd(textChangeRange.span) !== sourceFile.text.length + ? sourceFile.text.substr(ts.textSpanEnd(textChangeRange.span)) + : ""; + if (textChangeRange.newLength === 0) { + // edit was a deletion - just combine prefix and suffix + newText = prefix && suffix ? prefix + suffix : prefix || suffix; + } + else { + // it was actual edit, fetch the fragment of new text that correspond to new span + var changedText = scriptSnapshot.getText(textChangeRange.span.start, textChangeRange.span.start + textChangeRange.newLength); + // combine prefix, changed text and suffix + newText = prefix && suffix + ? prefix + changedText + suffix + : prefix + ? (prefix + changedText) + : (changedText + suffix); + } + var newSourceFile = ts.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); + setSourceFileFields(newSourceFile, scriptSnapshot, version); + // after incremental parsing nameTable might not be up-to-date + // drop it so it can be lazily recreated later + newSourceFile.nameTable = undefined; + // dispose all resources held by old script snapshot + if (sourceFile !== newSourceFile && sourceFile.scriptSnapshot) { + if (sourceFile.scriptSnapshot.dispose) { + sourceFile.scriptSnapshot.dispose(); + } + sourceFile.scriptSnapshot = undefined; + } + return newSourceFile; + } + } + } + // Otherwise, just create a new source file. + return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents:*/ true); + } + ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; + function createGetCanonicalFileName(useCaseSensitivefileNames) { + return useCaseSensitivefileNames + ? (function (fileName) { return fileName; }) + : (function (fileName) { return fileName.toLowerCase(); }); + } + ts.createGetCanonicalFileName = createGetCanonicalFileName; + function createDocumentRegistry(useCaseSensitiveFileNames) { + // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have + // for those settings. + var buckets = {}; + var getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); + function getKeyFromCompilationSettings(settings) { + return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx; + } + function getBucketForCompilationSettings(settings, createIfMissing) { + var key = getKeyFromCompilationSettings(settings); + var bucket = ts.lookUp(buckets, key); + if (!bucket && createIfMissing) { + buckets[key] = bucket = ts.createFileMap(getCanonicalFileName); + } + return bucket; + } + function reportStats() { + var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === '_'; }).map(function (name) { + var entries = ts.lookUp(buckets, name); + var sourceFiles = []; + for (var i in entries) { + var entry = entries.get(i); + sourceFiles.push({ + name: i, + refCount: entry.languageServiceRefCount, + references: entry.owners.slice(0) + }); + } + sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); + return { + bucket: name, + sourceFiles: sourceFiles + }; + }); + return JSON.stringify(bucketInfoArray, null, 2); + } + function acquireDocument(fileName, compilationSettings, scriptSnapshot, version) { + return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring:*/ true); + } + function updateDocument(fileName, compilationSettings, scriptSnapshot, version) { + return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring:*/ false); + } + function acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, acquiring) { + var bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ true); + var entry = bucket.get(fileName); + if (!entry) { + ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); + // Have never seen this file with these settings. Create a new source file for it. + var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents:*/ false); + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 0, + owners: [] + }; + bucket.set(fileName, entry); + } + else { + // We have an entry for this file. However, it may be for a different version of + // the script snapshot. If so, update it appropriately. Otherwise, we can just + // return it as is. + if (entry.sourceFile.version !== version) { + entry.sourceFile = updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); + } + } + // If we're acquiring, then this is the first time this LS is asking for this document. + // Increase our ref count so we know there's another LS using the document. If we're + // not acquiring, then that means the LS is 'updating' the file instead, and that means + // it has already acquired the document previously. As such, we do not need to increase + // the ref count. + if (acquiring) { + entry.languageServiceRefCount++; + } + return entry.sourceFile; + } + function releaseDocument(fileName, compilationSettings) { + var bucket = getBucketForCompilationSettings(compilationSettings, false); + ts.Debug.assert(bucket !== undefined); + var entry = bucket.get(fileName); + entry.languageServiceRefCount--; + ts.Debug.assert(entry.languageServiceRefCount >= 0); + if (entry.languageServiceRefCount === 0) { + bucket.remove(fileName); + } + } + return { + acquireDocument: acquireDocument, + updateDocument: updateDocument, + releaseDocument: releaseDocument, + reportStats: reportStats + }; + } + ts.createDocumentRegistry = createDocumentRegistry; + function preProcessFile(sourceText, readImportFiles) { + if (readImportFiles === void 0) { readImportFiles = true; } + var referencedFiles = []; + var importedFiles = []; + var ambientExternalModules; + var isNoDefaultLib = false; + function processTripleSlashDirectives() { + var commentRanges = ts.getLeadingCommentRanges(sourceText, 0); + ts.forEach(commentRanges, function (commentRange) { + var comment = sourceText.substring(commentRange.pos, commentRange.end); + var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, commentRange); + if (referencePathMatchResult) { + isNoDefaultLib = referencePathMatchResult.isNoDefaultLib; + var fileReference = referencePathMatchResult.fileReference; + if (fileReference) { + referencedFiles.push(fileReference); + } + } + }); + } + function recordAmbientExternalModule() { + if (!ambientExternalModules) { + ambientExternalModules = []; + } + ambientExternalModules.push(scanner.getTokenValue()); + } + function recordModuleName() { + var importPath = scanner.getTokenValue(); + var pos = scanner.getTokenPos(); + importedFiles.push({ + fileName: importPath, + pos: pos, + end: pos + importPath.length + }); + } + function processImport() { + scanner.setText(sourceText); + var token = scanner.scan(); + // Look for: + // import "mod"; + // import d from "mod" + // import {a as A } from "mod"; + // import * as NS from "mod" + // import d, {a, b as B} from "mod" + // import i = require("mod"); + // + // export * from "mod" + // export {a as b} from "mod" + // export import i = require("mod") + while (token !== 1 /* EndOfFileToken */) { + if (token === 122 /* DeclareKeyword */) { + // declare module "mod" + token = scanner.scan(); + if (token === 125 /* ModuleKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + recordAmbientExternalModule(); + continue; + } + } + } + else if (token === 89 /* ImportKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // import "mod"; + recordModuleName(); + continue; + } + else { + if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + token = scanner.scan(); + if (token === 133 /* FromKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // import d from "mod"; + recordModuleName(); + continue; + } + } + else if (token === 56 /* EqualsToken */) { + token = scanner.scan(); + if (token === 127 /* RequireKeyword */) { + token = scanner.scan(); + if (token === 17 /* OpenParenToken */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // import i = require("mod"); + recordModuleName(); + continue; + } + } + } + } + else if (token === 24 /* CommaToken */) { + // consume comma and keep going + token = scanner.scan(); + } + else { + // unknown syntax + continue; + } + } + if (token === 15 /* OpenBraceToken */) { + token = scanner.scan(); + // consume "{ a as B, c, d as D}" clauses + while (token !== 16 /* CloseBraceToken */) { + token = scanner.scan(); + } + if (token === 16 /* CloseBraceToken */) { + token = scanner.scan(); + if (token === 133 /* FromKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // import {a as A} from "mod"; + // import d, {a, b as B} from "mod" + recordModuleName(); + } + } + } + } + else if (token === 37 /* AsteriskToken */) { + token = scanner.scan(); + if (token === 116 /* AsKeyword */) { + token = scanner.scan(); + if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + token = scanner.scan(); + if (token === 133 /* FromKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // import * as NS from "mod" + // import d, * as NS from "mod" + recordModuleName(); + } + } + } + } + } + } + } + else if (token === 82 /* ExportKeyword */) { + token = scanner.scan(); + if (token === 15 /* OpenBraceToken */) { + token = scanner.scan(); + // consume "{ a as B, c, d as D}" clauses + while (token !== 16 /* CloseBraceToken */) { + token = scanner.scan(); + } + if (token === 16 /* CloseBraceToken */) { + token = scanner.scan(); + if (token === 133 /* FromKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // export {a as A} from "mod"; + // export {a, b as B} from "mod" + recordModuleName(); + } + } + } + } + else if (token === 37 /* AsteriskToken */) { + token = scanner.scan(); + if (token === 133 /* FromKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // export * from "mod" + recordModuleName(); + } + } + } + else if (token === 89 /* ImportKeyword */) { + token = scanner.scan(); + if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + token = scanner.scan(); + if (token === 56 /* EqualsToken */) { + token = scanner.scan(); + if (token === 127 /* RequireKeyword */) { + token = scanner.scan(); + if (token === 17 /* OpenParenToken */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // export import i = require("mod"); + recordModuleName(); + } + } + } + } + } + } + } + token = scanner.scan(); + } + scanner.setText(undefined); + } + if (readImportFiles) { + processImport(); + } + processTripleSlashDirectives(); + return { referencedFiles: referencedFiles, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientExternalModules }; + } + ts.preProcessFile = preProcessFile; + /// Helpers + function getTargetLabel(referenceNode, labelName) { + while (referenceNode) { + if (referenceNode.kind === 207 /* LabeledStatement */ && referenceNode.label.text === labelName) { + return referenceNode.label; + } + referenceNode = referenceNode.parent; + } + return undefined; + } + function isJumpStatementTarget(node) { + return node.kind === 69 /* Identifier */ && + (node.parent.kind === 203 /* BreakStatement */ || node.parent.kind === 202 /* ContinueStatement */) && + node.parent.label === node; + } + function isLabelOfLabeledStatement(node) { + return node.kind === 69 /* Identifier */ && + node.parent.kind === 207 /* LabeledStatement */ && + node.parent.label === node; + } + /** + * Whether or not a 'node' is preceded by a label of the given string. + * Note: 'node' cannot be a SourceFile. + */ + function isLabeledBy(node, labelName) { + for (var owner = node.parent; owner.kind === 207 /* LabeledStatement */; owner = owner.parent) { + if (owner.label.text === labelName) { + return true; + } + } + return false; + } + function isLabelName(node) { + return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); + } + function isRightSideOfQualifiedName(node) { + return node.parent.kind === 135 /* QualifiedName */ && node.parent.right === node; + } + function isRightSideOfPropertyAccess(node) { + return node && node.parent && node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.name === node; + } + function isCallExpressionTarget(node) { + if (isRightSideOfPropertyAccess(node)) { + node = node.parent; + } + return node && node.parent && node.parent.kind === 168 /* CallExpression */ && node.parent.expression === node; + } + function isNewExpressionTarget(node) { + if (isRightSideOfPropertyAccess(node)) { + node = node.parent; + } + return node && node.parent && node.parent.kind === 169 /* NewExpression */ && node.parent.expression === node; + } + function isNameOfModuleDeclaration(node) { + return node.parent.kind === 218 /* ModuleDeclaration */ && node.parent.name === node; + } + function isNameOfFunctionDeclaration(node) { + return node.kind === 69 /* Identifier */ && + ts.isFunctionLike(node.parent) && node.parent.name === node; + } + /** Returns true if node is a name of an object literal property, e.g. "a" in x = { "a": 1 } */ + function isNameOfPropertyAssignment(node) { + return (node.kind === 69 /* Identifier */ || node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && + (node.parent.kind === 245 /* PropertyAssignment */ || node.parent.kind === 246 /* ShorthandPropertyAssignment */) && node.parent.name === node; + } + function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { + if (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) { + switch (node.parent.kind) { + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 245 /* PropertyAssignment */: + case 247 /* EnumMember */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 218 /* ModuleDeclaration */: + return node.parent.name === node; + case 167 /* ElementAccessExpression */: + return node.parent.argumentExpression === node; + } + } + return false; + } + function isNameOfExternalModuleImportOrDeclaration(node) { + if (node.kind === 9 /* StringLiteral */) { + return isNameOfModuleDeclaration(node) || + (ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node); + } + return false; + } + /** Returns true if the position is within a comment */ + function isInsideComment(sourceFile, token, position) { + // The position has to be: 1. in the leading trivia (before token.getStart()), and 2. within a comment + return position <= token.getStart(sourceFile) && + (isInsideCommentRange(ts.getTrailingCommentRanges(sourceFile.text, token.getFullStart())) || + isInsideCommentRange(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()))); + function isInsideCommentRange(comments) { + return ts.forEach(comments, function (comment) { + // either we are 1. completely inside the comment, or 2. at the end of the comment + if (comment.pos < position && position < comment.end) { + return true; + } + else if (position === comment.end) { + var text = sourceFile.text; + var width = comment.end - comment.pos; + // is single line comment or just /* + if (width <= 2 || text.charCodeAt(comment.pos + 1) === 47 /* slash */) { + return true; + } + else { + // is unterminated multi-line comment + return !(text.charCodeAt(comment.end - 1) === 47 /* slash */ && + text.charCodeAt(comment.end - 2) === 42 /* asterisk */); + } + } + return false; + }); + } + } + var SemanticMeaning; + (function (SemanticMeaning) { + SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; + SemanticMeaning[SemanticMeaning["Value"] = 1] = "Value"; + SemanticMeaning[SemanticMeaning["Type"] = 2] = "Type"; + SemanticMeaning[SemanticMeaning["Namespace"] = 4] = "Namespace"; + SemanticMeaning[SemanticMeaning["All"] = 7] = "All"; + })(SemanticMeaning || (SemanticMeaning = {})); + var BreakContinueSearchType; + (function (BreakContinueSearchType) { + BreakContinueSearchType[BreakContinueSearchType["None"] = 0] = "None"; + BreakContinueSearchType[BreakContinueSearchType["Unlabeled"] = 1] = "Unlabeled"; + BreakContinueSearchType[BreakContinueSearchType["Labeled"] = 2] = "Labeled"; + BreakContinueSearchType[BreakContinueSearchType["All"] = 3] = "All"; + })(BreakContinueSearchType || (BreakContinueSearchType = {})); + // A cache of completion entries for keywords, these do not change between sessions + var keywordCompletions = []; + for (var i = 70 /* FirstKeyword */; i <= 134 /* LastKeyword */; i++) { + keywordCompletions.push({ + name: ts.tokenToString(i), + kind: ScriptElementKind.keyword, + kindModifiers: ScriptElementKindModifier.none, + sortText: "0" + }); + } + /* @internal */ function getContainerNode(node) { + while (true) { + node = node.parent; + if (!node) { + return undefined; + } + switch (node.kind) { + case 248 /* SourceFile */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 213 /* FunctionDeclaration */: + case 173 /* FunctionExpression */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 214 /* ClassDeclaration */: + case 215 /* InterfaceDeclaration */: + case 217 /* EnumDeclaration */: + case 218 /* ModuleDeclaration */: + return node; + } + } + } + ts.getContainerNode = getContainerNode; + /* @internal */ function getNodeKind(node) { + switch (node.kind) { + case 218 /* ModuleDeclaration */: return ScriptElementKind.moduleElement; + case 214 /* ClassDeclaration */: return ScriptElementKind.classElement; + case 215 /* InterfaceDeclaration */: return ScriptElementKind.interfaceElement; + case 216 /* TypeAliasDeclaration */: return ScriptElementKind.typeElement; + case 217 /* EnumDeclaration */: return ScriptElementKind.enumElement; + case 211 /* VariableDeclaration */: + return ts.isConst(node) + ? ScriptElementKind.constElement + : ts.isLet(node) + ? ScriptElementKind.letElement + : ScriptElementKind.variableElement; + case 213 /* FunctionDeclaration */: return ScriptElementKind.functionElement; + case 145 /* GetAccessor */: return ScriptElementKind.memberGetAccessorElement; + case 146 /* SetAccessor */: return ScriptElementKind.memberSetAccessorElement; + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + return ScriptElementKind.memberFunctionElement; + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + return ScriptElementKind.memberVariableElement; + case 149 /* IndexSignature */: return ScriptElementKind.indexSignatureElement; + case 148 /* ConstructSignature */: return ScriptElementKind.constructSignatureElement; + case 147 /* CallSignature */: return ScriptElementKind.callSignatureElement; + case 144 /* Constructor */: return ScriptElementKind.constructorImplementationElement; + case 137 /* TypeParameter */: return ScriptElementKind.typeParameterElement; + case 247 /* EnumMember */: return ScriptElementKind.variableElement; + case 138 /* Parameter */: return (node.flags & 112 /* AccessibilityModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; + case 221 /* ImportEqualsDeclaration */: + case 226 /* ImportSpecifier */: + case 223 /* ImportClause */: + case 230 /* ExportSpecifier */: + case 224 /* NamespaceImport */: + return ScriptElementKind.alias; + } + return ScriptElementKind.unknown; + } + ts.getNodeKind = getNodeKind; + var CancellationTokenObject = (function () { + function CancellationTokenObject(cancellationToken) { + this.cancellationToken = cancellationToken; + } + CancellationTokenObject.prototype.isCancellationRequested = function () { + return this.cancellationToken && this.cancellationToken.isCancellationRequested(); + }; + CancellationTokenObject.prototype.throwIfCancellationRequested = function () { + if (this.isCancellationRequested()) { + throw new ts.OperationCanceledException(); + } + }; + return CancellationTokenObject; + })(); + function createLanguageService(host, documentRegistry) { + if (documentRegistry === void 0) { documentRegistry = createDocumentRegistry(); } + var syntaxTreeCache = new SyntaxTreeCache(host); + var ruleProvider; + var program; + var lastProjectVersion; + var useCaseSensitivefileNames = false; + var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); + // Check if the localized messages json is set, otherwise query the host for it + if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { + ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); + } + function log(message) { + if (host.log) { + host.log(message); + } + } + var getCanonicalFileName = createGetCanonicalFileName(useCaseSensitivefileNames); + function getValidSourceFile(fileName) { + fileName = ts.normalizeSlashes(fileName); + var sourceFile = program.getSourceFile(getCanonicalFileName(fileName)); + if (!sourceFile) { + throw new Error("Could not find file: '" + fileName + "'."); + } + return sourceFile; + } + function getRuleProvider(options) { + // Ensure rules are initialized and up to date wrt to formatting options + if (!ruleProvider) { + ruleProvider = new ts.formatting.RulesProvider(); + } + ruleProvider.ensureUpToDate(options); + return ruleProvider; + } + function synchronizeHostData() { + // perform fast check if host supports it + if (host.getProjectVersion) { + var hostProjectVersion = host.getProjectVersion(); + if (hostProjectVersion) { + if (lastProjectVersion === hostProjectVersion) { + return; + } + lastProjectVersion = hostProjectVersion; + } + } + // Get a fresh cache of the host information + var hostCache = new HostCache(host, getCanonicalFileName); + // If the program is already up-to-date, we can reuse it + if (programUpToDate()) { + return; + } + // IMPORTANT - It is critical from this moment onward that we do not check + // cancellation tokens. We are about to mutate source files from a previous program + // instance. If we cancel midway through, we may end up in an inconsistent state where + // the program points to old source files that have been invalidated because of + // incremental parsing. + var oldSettings = program && program.getCompilerOptions(); + var newSettings = hostCache.compilationSettings(); + var changesInCompilationSettingsAffectSyntax = oldSettings && + (oldSettings.target !== newSettings.target || + oldSettings.module !== newSettings.module || + oldSettings.noResolve !== newSettings.noResolve || + oldSettings.jsx !== newSettings.jsx); + // Now create a new compiler + var compilerHost = { + getSourceFile: getOrCreateSourceFile, + getCancellationToken: function () { return cancellationToken; }, + getCanonicalFileName: getCanonicalFileName, + useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, + getNewLine: function () { return ts.getNewLineOrDefaultFromHost(host); }, + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: function (fileName, data, writeByteOrderMark) { }, + getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + fileExists: function (fileName) { + // stub missing host functionality + ts.Debug.assert(!host.resolveModuleNames); + return hostCache.getOrCreateEntry(fileName) !== undefined; + }, + readFile: function (fileName) { + // stub missing host functionality + var entry = hostCache.getOrCreateEntry(fileName); + return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + } + }; + if (host.resolveModuleNames) { + compilerHost.resolveModuleNames = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; + } + var newProgram = ts.createProgram(hostCache.getRootFileNames(), newSettings, compilerHost, program); + // Release any files we have acquired in the old program but are + // not part of the new program. + if (program) { + var oldSourceFiles = program.getSourceFiles(); + for (var _i = 0; _i < oldSourceFiles.length; _i++) { + var oldSourceFile = oldSourceFiles[_i]; + var fileName = oldSourceFile.fileName; + if (!newProgram.getSourceFile(fileName) || changesInCompilationSettingsAffectSyntax) { + documentRegistry.releaseDocument(fileName, oldSettings); + } + } + } + // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. + // It needs to be cleared to allow all collected snapshots to be released + hostCache = undefined; + program = newProgram; + // Make sure all the nodes in the program are both bound, and have their parent + // pointers set property. + program.getTypeChecker(); + return; + function getOrCreateSourceFile(fileName) { + ts.Debug.assert(hostCache !== undefined); + // The program is asking for this file, check first if the host can locate it. + // If the host can not locate the file, then it does not exist. return undefined + // to the program to allow reporting of errors for missing files. + var hostFileInformation = hostCache.getOrCreateEntry(fileName); + if (!hostFileInformation) { + return undefined; + } + // Check if the language version has changed since we last created a program; if they are the same, + // it is safe to reuse the souceFiles; if not, then the shape of the AST can change, and the oldSourceFile + // can not be reused. we have to dump all syntax trees and create new ones. + if (!changesInCompilationSettingsAffectSyntax) { + // Check if the old program had this file already + var oldSourceFile = program && program.getSourceFile(fileName); + if (oldSourceFile) { + // We already had a source file for this file name. Go to the registry to + // ensure that we get the right up to date version of it. We need this to + // address the following 'race'. Specifically, say we have the following: + // + // LS1 + // \ + // DocumentRegistry + // / + // LS2 + // + // Each LS has a reference to file 'foo.ts' at version 1. LS2 then updates + // it's version of 'foo.ts' to version 2. This will cause LS2 and the + // DocumentRegistry to have version 2 of the document. HOwever, LS1 will + // have version 1. And *importantly* this source file will be *corrupt*. + // The act of creating version 2 of the file irrevocably damages the version + // 1 file. + // + // So, later when we call into LS1, we need to make sure that it doesn't use + // it's source file any more, and instead defers to DocumentRegistry to get + // either version 1, version 2 (or some other version) depending on what the + // host says should be used. + return documentRegistry.updateDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version); + } + } + // Could not find this file in the old program, create a new SourceFile for it. + return documentRegistry.acquireDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version); + } + function sourceFileUpToDate(sourceFile) { + return sourceFile && sourceFile.version === hostCache.getVersion(sourceFile.fileName); + } + function programUpToDate() { + // If we haven't create a program yet, then it is not up-to-date + if (!program) { + return false; + } + // If number of files in the program do not match, it is not up-to-date + var rootFileNames = hostCache.getRootFileNames(); + if (program.getSourceFiles().length !== rootFileNames.length) { + return false; + } + // If any file is not up-to-date, then the whole program is not up-to-date + for (var _i = 0; _i < rootFileNames.length; _i++) { + var fileName = rootFileNames[_i]; + if (!sourceFileUpToDate(program.getSourceFile(fileName))) { + return false; + } + } + // If the compilation settings do no match, then the program is not up-to-date + return ts.compareDataObjects(program.getCompilerOptions(), hostCache.compilationSettings()); + } + } + function getProgram() { + synchronizeHostData(); + return program; + } + function cleanupSemanticCache() { + // TODO: Should we jettison the program (or it's type checker) here? + } + function dispose() { + if (program) { + ts.forEach(program.getSourceFiles(), function (f) { + return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions()); + }); + } + } + /// Diagnostics + function getSyntacticDiagnostics(fileName) { + synchronizeHostData(); + return program.getSyntacticDiagnostics(getValidSourceFile(fileName), cancellationToken); + } + /** + * getSemanticDiagnostiscs return array of Diagnostics. If '-d' is not enabled, only report semantic errors + * If '-d' enabled, report both semantic and emitter errors + */ + function getSemanticDiagnostics(fileName) { + synchronizeHostData(); + var targetSourceFile = getValidSourceFile(fileName); + // For JavaScript files, we don't want to report the normal typescript semantic errors. + // Instead, we just report errors for using TypeScript-only constructs from within a + // JavaScript file. + if (ts.isJavaScript(fileName)) { + return getJavaScriptSemanticDiagnostics(targetSourceFile); + } + // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. + // Therefore only get diagnostics for given file. + var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); + if (!program.getCompilerOptions().declaration) { + return semanticDiagnostics; + } + // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface + var declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); + return ts.concatenate(semanticDiagnostics, declarationDiagnostics); + } + function getJavaScriptSemanticDiagnostics(sourceFile) { + var diagnostics = []; + walk(sourceFile); + return diagnostics; + function walk(node) { + if (!node) { + return false; + } + switch (node.kind) { + case 221 /* ImportEqualsDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return true; + case 227 /* ExportAssignment */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return true; + case 214 /* ClassDeclaration */: + var classDeclaration = node; + if (checkModifiers(classDeclaration.modifiers) || + checkTypeParameters(classDeclaration.typeParameters)) { + return true; + } + break; + case 243 /* HeritageClause */: + var heritageClause = node; + if (heritageClause.token === 106 /* ImplementsKeyword */) { + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 215 /* InterfaceDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 218 /* ModuleDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 216 /* TypeAliasDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return true; + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 144 /* Constructor */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 173 /* FunctionExpression */: + case 213 /* FunctionDeclaration */: + case 174 /* ArrowFunction */: + case 213 /* FunctionDeclaration */: + var functionDeclaration = node; + if (checkModifiers(functionDeclaration.modifiers) || + checkTypeParameters(functionDeclaration.typeParameters) || + checkTypeAnnotation(functionDeclaration.type)) { + return true; + } + break; + case 193 /* VariableStatement */: + var variableStatement = node; + if (checkModifiers(variableStatement.modifiers)) { + return true; + } + break; + case 211 /* VariableDeclaration */: + var variableDeclaration = node; + if (checkTypeAnnotation(variableDeclaration.type)) { + return true; + } + break; + case 168 /* CallExpression */: + case 169 /* NewExpression */: + var expression = node; + if (expression.typeArguments && expression.typeArguments.length > 0) { + var start = expression.typeArguments.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 138 /* Parameter */: + var parameter = node; + if (parameter.modifiers) { + var start = parameter.modifiers.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + return true; + } + if (parameter.questionToken) { + diagnostics.push(ts.createDiagnosticForNode(parameter.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, '?')); + return true; + } + if (parameter.type) { + diagnostics.push(ts.createDiagnosticForNode(parameter.type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 141 /* PropertyDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 217 /* EnumDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 171 /* TypeAssertionExpression */: + var typeAssertionExpression = node; + diagnostics.push(ts.createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return true; + case 139 /* Decorator */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.decorators_can_only_be_used_in_a_ts_file)); + return true; + } + return ts.forEachChild(node, walk); + } + function checkTypeParameters(typeParameters) { + if (typeParameters) { + var start = typeParameters.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start, typeParameters.end - start, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + return true; + } + return false; + } + function checkTypeAnnotation(type) { + if (type) { + diagnostics.push(ts.createDiagnosticForNode(type, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return true; + } + return false; + } + function checkModifiers(modifiers) { + if (modifiers) { + for (var _i = 0; _i < modifiers.length; _i++) { + var modifier = modifiers[_i]; + switch (modifier.kind) { + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + case 122 /* DeclareKeyword */: + diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + return true; + // These are all legal modifiers. + case 113 /* StaticKeyword */: + case 82 /* ExportKeyword */: + case 74 /* ConstKeyword */: + case 77 /* DefaultKeyword */: + case 115 /* AbstractKeyword */: + } + } + } + return false; + } + } + function getCompilerOptionsDiagnostics() { + synchronizeHostData(); + return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); + } + /** + * Get the name to be display in completion from a given symbol. + * + * @return undefined if the name is of external module otherwise a name with striped of any quote + */ + function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, location) { + var displayName = ts.getDeclaredName(program.getTypeChecker(), symbol, location); + if (displayName) { + var firstCharCode = displayName.charCodeAt(0); + // First check of the displayName is not external module; if it is an external module, it is not valid entry + if ((symbol.flags & 1536 /* Namespace */) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { + // If the symbol is external module, don't show it in the completion list + // (i.e declare module "http" { let x; } | // <= request completion here, "http" should not be there) + return undefined; + } + } + return getCompletionEntryDisplayName(displayName, target, performCharacterChecks); + } + /** + * Get a displayName from a given for completion list, performing any necessary quotes stripping + * and checking whether the name is valid identifier name. + */ + function getCompletionEntryDisplayName(name, target, performCharacterChecks) { + if (!name) { + return undefined; + } + name = ts.stripQuotes(name); + if (!name) { + return undefined; + } + // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an + // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. + // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. + // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. + if (performCharacterChecks) { + if (!ts.isIdentifierStart(name.charCodeAt(0), target)) { + return undefined; + } + for (var i = 1, n = name.length; i < n; i++) { + if (!ts.isIdentifierPart(name.charCodeAt(i), target)) { + return undefined; + } + } + } + return name; + } + function getCompletionData(fileName, position) { + var typeChecker = program.getTypeChecker(); + var syntacticStart = new Date().getTime(); + var sourceFile = getValidSourceFile(fileName); + var isJavaScriptFile = ts.isJavaScript(fileName); + var isJsDocTagName = false; + var start = new Date().getTime(); + var currentToken = ts.getTokenAtPosition(sourceFile, position); + log("getCompletionData: Get current token: " + (new Date().getTime() - start)); + start = new Date().getTime(); + // Completion not allowed inside comments, bail out if this is the case + var insideComment = isInsideComment(sourceFile, currentToken, position); + log("getCompletionData: Is inside comment: " + (new Date().getTime() - start)); + if (insideComment) { + // The current position is next to the '@' sign, when no tag name being provided yet. + // Provide a full list of tag names + if (ts.hasDocComment(sourceFile, position) && sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { + isJsDocTagName = true; + } + // Completion should work inside certain JsDoc tags. For example: + // /** @type {number | string} */ + // Completion should work in the brackets + var insideJsDocTagExpression = false; + var tag = ts.getJsDocTagAtPosition(sourceFile, position); + if (tag) { + if (tag.tagName.pos <= position && position <= tag.tagName.end) { + isJsDocTagName = true; + } + switch (tag.kind) { + case 269 /* JSDocTypeTag */: + case 267 /* JSDocParameterTag */: + case 268 /* JSDocReturnTag */: + var tagWithExpression = tag; + if (tagWithExpression.typeExpression) { + insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; + } + break; + } + } + if (isJsDocTagName) { + return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; + } + if (!insideJsDocTagExpression) { + // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal + // comment or the plain text part of a jsDoc comment, so no completion should be available + log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); + return undefined; + } + } + start = new Date().getTime(); + var previousToken = ts.findPrecedingToken(position, sourceFile); + log("getCompletionData: Get previous token 1: " + (new Date().getTime() - start)); + // The decision to provide completion depends on the contextToken, which is determined through the previousToken. + // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file + var contextToken = previousToken; + // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| + // Skip this partial identifier and adjust the contextToken to the token that precedes it. + if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { + var start_3 = new Date().getTime(); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); + log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_3)); + } + // Find the node where completion is requested on. + // Also determine whether we are trying to complete with members of that node + // or attributes of a JSX tag. + var node = currentToken; + var isRightOfDot = false; + var isRightOfOpenTag = false; + var isStartingCloseTag = false; + var location = ts.getTouchingPropertyName(sourceFile, position); + if (contextToken) { + // Bail out if this is a known invalid completion location + if (isCompletionListBlocker(contextToken)) { + log("Returning an empty list because completion was requested in an invalid position."); + return undefined; + } + var parent_9 = contextToken.parent, kind = contextToken.kind; + if (kind === 21 /* DotToken */) { + if (parent_9.kind === 166 /* PropertyAccessExpression */) { + node = contextToken.parent.expression; + isRightOfDot = true; + } + else if (parent_9.kind === 135 /* QualifiedName */) { + node = contextToken.parent.left; + isRightOfDot = true; + } + else { + // There is nothing that precedes the dot, so this likely just a stray character + // or leading into a '...' token. Just bail out instead. + return undefined; + } + } + else if (sourceFile.languageVariant === 1 /* JSX */) { + if (kind === 25 /* LessThanToken */) { + isRightOfOpenTag = true; + location = contextToken; + } + else if (kind === 39 /* SlashToken */ && contextToken.parent.kind === 237 /* JsxClosingElement */) { + isStartingCloseTag = true; + } + } + } + var semanticStart = new Date().getTime(); + var isMemberCompletion; + var isNewIdentifierLocation; + var symbols = []; + if (isRightOfDot) { + getTypeScriptMemberSymbols(); + } + else if (isRightOfOpenTag) { + var tagSymbols = typeChecker.getJsxIntrinsicTagNames(); + if (tryGetGlobalSymbols()) { + symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & 107455 /* Value */); })); + } + else { + symbols = tagSymbols; + } + isMemberCompletion = true; + isNewIdentifierLocation = false; + } + else if (isStartingCloseTag) { + var tagName = contextToken.parent.parent.openingElement.tagName; + symbols = [typeChecker.getSymbolAtLocation(tagName)]; + isMemberCompletion = true; + isNewIdentifierLocation = false; + } + else { + // For JavaScript or TypeScript, if we're not after a dot, then just try to get the + // global symbols in scope. These results should be valid for either language as + // the set of symbols that can be referenced from this location. + if (!tryGetGlobalSymbols()) { + return undefined; + } + } + log("getCompletionData: Semantic work: " + (new Date().getTime() - semanticStart)); + return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; + function getTypeScriptMemberSymbols() { + // Right of dot member completion list + isMemberCompletion = true; + isNewIdentifierLocation = false; + if (node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */ || node.kind === 166 /* PropertyAccessExpression */) { + var symbol = typeChecker.getSymbolAtLocation(node); + // This is an alias, follow what it aliases + if (symbol && symbol.flags & 8388608 /* Alias */) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + if (symbol && symbol.flags & 1952 /* HasExports */) { + // Extract module or enum members + var exportedSymbols = typeChecker.getExportsOfModule(symbol); + ts.forEach(exportedSymbols, function (symbol) { + if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); + } + }); + } + } + var type = typeChecker.getTypeAtLocation(node); + addTypeProperties(type); + } + function addTypeProperties(type) { + if (type) { + // Filter private properties + for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { + var symbol = _a[_i]; + if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); + } + } + if (isJavaScriptFile && type.flags & 16384 /* Union */) { + // In javascript files, for union types, we don't just get the members that + // the individual types have in common, we also include all the members that + // each individual type has. This is because we're going to add all identifiers + // anyways. So we might as well elevate the members that were at least part + // of the individual types to a higher status since we know what they are. + var unionType = type; + for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { + var elementType = _c[_b]; + addTypeProperties(elementType); + } + } + } + } + function tryGetGlobalSymbols() { + var objectLikeContainer; + var namedImportsOrExports; + var jsxContainer; + if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { + return tryGetObjectLikeCompletionSymbols(objectLikeContainer); + } + if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { + // cursor is in an import clause + // try to show exported member for imported module + return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); + } + if (jsxContainer = tryGetContainingJsxElement(contextToken)) { + var attrsType; + if ((jsxContainer.kind === 234 /* JsxSelfClosingElement */) || (jsxContainer.kind === 235 /* JsxOpeningElement */)) { + // Cursor is inside a JSX self-closing element or opening element + attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); + if (attrsType) { + symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); + isMemberCompletion = true; + isNewIdentifierLocation = false; + return true; + } + } + } + // Get all entities in the current scope. + isMemberCompletion = false; + isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); + if (previousToken !== contextToken) { + ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); + } + // We need to find the node that will give us an appropriate scope to begin + // aggregating completion candidates. This is achieved in 'getScopeNode' + // by finding the first node that encompasses a position, accounting for whether a node + // is "complete" to decide whether a position belongs to the node. + // + // However, at the end of an identifier, we are interested in the scope of the identifier + // itself, but fall outside of the identifier. For instance: + // + // xyz => x$ + // + // the cursor is outside of both the 'x' and the arrow function 'xyz => x', + // so 'xyz' is not returned in our results. + // + // We define 'adjustedPosition' so that we may appropriately account for + // being at the end of an identifier. The intention is that if requesting completion + // at the end of an identifier, it should be effectively equivalent to requesting completion + // anywhere inside/at the beginning of the identifier. So in the previous case, the + // 'adjustedPosition' will work as if requesting completion in the following: + // + // xyz => $x + // + // If previousToken !== contextToken, then + // - 'contextToken' was adjusted to the token prior to 'previousToken' + // because we were at the end of an identifier. + // - 'previousToken' is defined. + var adjustedPosition = previousToken !== contextToken ? + previousToken.getStart() : + position; + var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; + /// TODO filter meaning based on the current context + var symbolMeanings = 793056 /* Type */ | 107455 /* Value */ | 1536 /* Namespace */ | 8388608 /* Alias */; + symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + return true; + } + /** + * Finds the first node that "embraces" the position, so that one may + * accurately aggregate locals from the closest containing scope. + */ + function getScopeNode(initialToken, position, sourceFile) { + var scope = initialToken; + while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { + scope = scope.parent; + } + return scope; + } + function isCompletionListBlocker(contextToken) { + var start = new Date().getTime(); + var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || + isSolelyIdentifierDefinitionLocation(contextToken) || + isDotOfNumericLiteral(contextToken) || + isInJsxText(contextToken); + log("getCompletionsAtPosition: isCompletionListBlocker: " + (new Date().getTime() - start)); + return result; + } + function isInJsxText(contextToken) { + if (contextToken.kind === 236 /* JsxText */) { + return true; + } + if (contextToken.kind === 27 /* GreaterThanToken */ && contextToken.parent) { + if (contextToken.parent.kind === 235 /* JsxOpeningElement */) { + return true; + } + if (contextToken.parent.kind === 237 /* JsxClosingElement */ || contextToken.parent.kind === 234 /* JsxSelfClosingElement */) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 233 /* JsxElement */; + } + } + return false; + } + function isNewIdentifierDefinitionLocation(previousToken) { + if (previousToken) { + var containingNodeKind = previousToken.parent.kind; + switch (previousToken.kind) { + case 24 /* CommaToken */: + return containingNodeKind === 168 /* CallExpression */ // func( a, | + || containingNodeKind === 144 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 169 /* NewExpression */ // new C(a, | + || containingNodeKind === 164 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 181 /* BinaryExpression */ // let x = (a, | + || containingNodeKind === 152 /* FunctionType */; // var x: (s: string, list| + case 17 /* OpenParenToken */: + return containingNodeKind === 168 /* CallExpression */ // func( | + || containingNodeKind === 144 /* Constructor */ // constructor( | + || containingNodeKind === 169 /* NewExpression */ // new C(a| + || containingNodeKind === 172 /* ParenthesizedExpression */ // let x = (a| + || containingNodeKind === 160 /* ParenthesizedType */; // function F(pred: (a| /* this can become an arrow function, where 'a' is the argument */ + case 19 /* OpenBracketToken */: + return containingNodeKind === 164 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 149 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 136 /* ComputedPropertyName */; // [ | /* this can become an index signature */ + case 125 /* ModuleKeyword */: // module | + case 126 /* NamespaceKeyword */: + return true; + case 21 /* DotToken */: + return containingNodeKind === 218 /* ModuleDeclaration */; // module A.| + case 15 /* OpenBraceToken */: + return containingNodeKind === 214 /* ClassDeclaration */; // class A{ | + case 56 /* EqualsToken */: + return containingNodeKind === 211 /* VariableDeclaration */ // let x = a| + || containingNodeKind === 181 /* BinaryExpression */; // x = a| + case 12 /* TemplateHead */: + return containingNodeKind === 183 /* TemplateExpression */; // `aa ${| + case 13 /* TemplateMiddle */: + return containingNodeKind === 190 /* TemplateSpan */; // `aa ${10} dd ${| + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + return containingNodeKind === 141 /* PropertyDeclaration */; // class A{ public | + } + // Previous token may have been a keyword that was converted to an identifier. + switch (previousToken.getText()) { + case "public": + case "protected": + case "private": + return true; + } + } + return false; + } + function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { + if (contextToken.kind === 9 /* StringLiteral */ + || contextToken.kind === 10 /* RegularExpressionLiteral */ + || ts.isTemplateLiteralKind(contextToken.kind)) { + var start_4 = contextToken.getStart(); + var end = contextToken.getEnd(); + // To be "in" one of these literals, the position has to be: + // 1. entirely within the token text. + // 2. at the end position of an unterminated token. + // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). + if (start_4 < position && position < end) { + return true; + } + if (position === end) { + return !!contextToken.isUnterminated + || contextToken.kind === 10 /* RegularExpressionLiteral */; + } + } + return false; + } + /** + * Aggregates relevant symbols for completion in object literals and object binding patterns. + * Relevant symbols are stored in the captured 'symbols' variable. + * + * @returns true if 'symbols' was successfully populated; false otherwise. + */ + function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { + // We're looking up possible property names from contextual/inferred/declared type. + isMemberCompletion = true; + var typeForObject; + var existingMembers; + if (objectLikeContainer.kind === 165 /* ObjectLiteralExpression */) { + // We are completing on contextual types, but may also include properties + // other than those within the declared type. + isNewIdentifierLocation = true; + typeForObject = typeChecker.getContextualType(objectLikeContainer); + existingMembers = objectLikeContainer.properties; + } + else if (objectLikeContainer.kind === 161 /* ObjectBindingPattern */) { + // We are *only* completing on properties from the type being destructured. + isNewIdentifierLocation = false; + var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); + if (ts.isVariableLike(rootDeclaration)) { + // We don't want to complete using the type acquired by the shape + // of the binding pattern; we are only interested in types acquired + // through type declaration or inference. + if (rootDeclaration.initializer || rootDeclaration.type) { + typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + existingMembers = objectLikeContainer.elements; + } + } + else { + ts.Debug.fail("Root declaration is not variable-like."); + } + } + else { + ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); + } + if (!typeForObject) { + return false; + } + var typeMembers = typeChecker.getPropertiesOfType(typeForObject); + if (typeMembers && typeMembers.length > 0) { + // Add filtered items to the completion list + symbols = filterObjectMembersList(typeMembers, existingMembers); + } + return true; + } + /** + * Aggregates relevant symbols for completion in import clauses and export clauses + * whose declarations have a module specifier; for instance, symbols will be aggregated for + * + * import { | } from "moduleName"; + * export { a as foo, | } from "moduleName"; + * + * but not for + * + * export { | }; + * + * Relevant symbols are stored in the captured 'symbols' variable. + * + * @returns true if 'symbols' was successfully populated; false otherwise. + */ + function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { + var declarationKind = namedImportsOrExports.kind === 225 /* NamedImports */ ? + 222 /* ImportDeclaration */ : + 228 /* ExportDeclaration */; + var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); + var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; + if (!moduleSpecifier) { + return false; + } + isMemberCompletion = true; + isNewIdentifierLocation = false; + var exports; + var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importOrExportDeclaration.moduleSpecifier); + if (moduleSpecifierSymbol) { + exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol); + } + symbols = exports ? filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements) : emptyArray; + return true; + } + /** + * Returns the immediate owning object literal or binding pattern of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetObjectLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 15 /* OpenBraceToken */: // let x = { | + case 24 /* CommaToken */: + var parent_10 = contextToken.parent; + if (parent_10 && (parent_10.kind === 165 /* ObjectLiteralExpression */ || parent_10.kind === 161 /* ObjectBindingPattern */)) { + return parent_10; + } + break; + } + } + return undefined; + } + /** + * Returns the containing list of named imports or exports of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetNamedImportsOrExportsForCompletion(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 15 /* OpenBraceToken */: // import { | + case 24 /* CommaToken */: + switch (contextToken.parent.kind) { + case 225 /* NamedImports */: + case 229 /* NamedExports */: + return contextToken.parent; + } + } + } + return undefined; + } + function tryGetContainingJsxElement(contextToken) { + if (contextToken) { + var parent_11 = contextToken.parent; + switch (contextToken.kind) { + case 26 /* LessThanSlashToken */: + case 39 /* SlashToken */: + case 69 /* Identifier */: + case 238 /* JsxAttribute */: + case 239 /* JsxSpreadAttribute */: + if (parent_11 && (parent_11.kind === 234 /* JsxSelfClosingElement */ || parent_11.kind === 235 /* JsxOpeningElement */)) { + return parent_11; + } + else if (parent_11.kind === 238 /* JsxAttribute */) { + return parent_11.parent; + } + break; + // The context token is the closing } or " of an attribute, which means + // its parent is a JsxExpression, whose parent is a JsxAttribute, + // whose parent is a JsxOpeningLikeElement + case 9 /* StringLiteral */: + if (parent_11 && ((parent_11.kind === 238 /* JsxAttribute */) || (parent_11.kind === 239 /* JsxSpreadAttribute */))) { + return parent_11.parent; + } + break; + case 16 /* CloseBraceToken */: + if (parent_11 && + parent_11.kind === 240 /* JsxExpression */ && + parent_11.parent && + (parent_11.parent.kind === 238 /* JsxAttribute */)) { + return parent_11.parent.parent; + } + if (parent_11 && parent_11.kind === 239 /* JsxSpreadAttribute */) { + return parent_11.parent; + } + break; + } + } + return undefined; + } + function isFunction(kind) { + switch (kind) { + case 173 /* FunctionExpression */: + case 174 /* ArrowFunction */: + case 213 /* FunctionDeclaration */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 147 /* CallSignature */: + case 148 /* ConstructSignature */: + case 149 /* IndexSignature */: + return true; + } + return false; + } + /** + * @returns true if we are certain that the currently edited location must define a new location; false otherwise. + */ + function isSolelyIdentifierDefinitionLocation(contextToken) { + var containingNodeKind = contextToken.parent.kind; + switch (contextToken.kind) { + case 24 /* CommaToken */: + return containingNodeKind === 211 /* VariableDeclaration */ || + containingNodeKind === 212 /* VariableDeclarationList */ || + containingNodeKind === 193 /* VariableStatement */ || + containingNodeKind === 217 /* EnumDeclaration */ || + isFunction(containingNodeKind) || + containingNodeKind === 214 /* ClassDeclaration */ || + containingNodeKind === 186 /* ClassExpression */ || + containingNodeKind === 215 /* InterfaceDeclaration */ || + containingNodeKind === 162 /* ArrayBindingPattern */ || + containingNodeKind === 216 /* TypeAliasDeclaration */; // type Map, K, | + case 21 /* DotToken */: + return containingNodeKind === 162 /* ArrayBindingPattern */; // var [.| + case 54 /* ColonToken */: + return containingNodeKind === 163 /* BindingElement */; // var {x :html| + case 19 /* OpenBracketToken */: + return containingNodeKind === 162 /* ArrayBindingPattern */; // var [x| + case 17 /* OpenParenToken */: + return containingNodeKind === 244 /* CatchClause */ || + isFunction(containingNodeKind); + case 15 /* OpenBraceToken */: + return containingNodeKind === 217 /* EnumDeclaration */ || + containingNodeKind === 215 /* InterfaceDeclaration */ || + containingNodeKind === 155 /* TypeLiteral */; // let x : { | + case 23 /* SemicolonToken */: + return containingNodeKind === 140 /* PropertySignature */ && + contextToken.parent && contextToken.parent.parent && + (contextToken.parent.parent.kind === 215 /* InterfaceDeclaration */ || + contextToken.parent.parent.kind === 155 /* TypeLiteral */); // let x : { a; | + case 25 /* LessThanToken */: + return containingNodeKind === 214 /* ClassDeclaration */ || + containingNodeKind === 186 /* ClassExpression */ || + containingNodeKind === 215 /* InterfaceDeclaration */ || + containingNodeKind === 216 /* TypeAliasDeclaration */ || + isFunction(containingNodeKind); + case 113 /* StaticKeyword */: + return containingNodeKind === 141 /* PropertyDeclaration */; + case 22 /* DotDotDotToken */: + return containingNodeKind === 138 /* Parameter */ || + (contextToken.parent && contextToken.parent.parent && + contextToken.parent.parent.kind === 162 /* ArrayBindingPattern */); // var [...z| + case 112 /* PublicKeyword */: + case 110 /* PrivateKeyword */: + case 111 /* ProtectedKeyword */: + return containingNodeKind === 138 /* Parameter */; + case 116 /* AsKeyword */: + return containingNodeKind === 226 /* ImportSpecifier */ || + containingNodeKind === 230 /* ExportSpecifier */ || + containingNodeKind === 224 /* NamespaceImport */; + case 73 /* ClassKeyword */: + case 81 /* EnumKeyword */: + case 107 /* InterfaceKeyword */: + case 87 /* FunctionKeyword */: + case 102 /* VarKeyword */: + case 123 /* GetKeyword */: + case 129 /* SetKeyword */: + case 89 /* ImportKeyword */: + case 108 /* LetKeyword */: + case 74 /* ConstKeyword */: + case 114 /* YieldKeyword */: + case 132 /* TypeKeyword */: + return true; + } + // Previous token may have been a keyword that was converted to an identifier. + switch (contextToken.getText()) { + case "abstract": + case "async": + case "class": + case "const": + case "declare": + case "enum": + case "function": + case "interface": + case "let": + case "private": + case "protected": + case "public": + case "static": + case "var": + case "yield": + return true; + } + return false; + } + function isDotOfNumericLiteral(contextToken) { + if (contextToken.kind === 8 /* NumericLiteral */) { + var text = contextToken.getFullText(); + return text.charAt(text.length - 1) === "."; + } + return false; + } + /** + * Filters out completion suggestions for named imports or exports. + * + * @param exportsOfModule The list of symbols which a module exposes. + * @param namedImportsOrExports The list of existing import/export specifiers in the import/export clause. + * + * @returns Symbols to be suggested at an import/export clause, barring those whose named imports/exports + * do not occur at the current position and have not otherwise been typed. + */ + function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { + var exisingImportsOrExports = {}; + for (var _i = 0; _i < namedImportsOrExports.length; _i++) { + var element = namedImportsOrExports[_i]; + // If this is the current item we are editing right now, do not filter it out + if (element.getStart() <= position && position <= element.getEnd()) { + continue; + } + var name_32 = element.propertyName || element.name; + exisingImportsOrExports[name_32.text] = true; + } + if (ts.isEmpty(exisingImportsOrExports)) { + return exportsOfModule; + } + return ts.filter(exportsOfModule, function (e) { return !ts.lookUp(exisingImportsOrExports, e.name); }); + } + /** + * Filters out completion suggestions for named imports or exports. + * + * @returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations + * do not occur at the current position and have not otherwise been typed. + */ + function filterObjectMembersList(contextualMemberSymbols, existingMembers) { + if (!existingMembers || existingMembers.length === 0) { + return contextualMemberSymbols; + } + var existingMemberNames = {}; + for (var _i = 0; _i < existingMembers.length; _i++) { + var m = existingMembers[_i]; + // Ignore omitted expressions for missing members + if (m.kind !== 245 /* PropertyAssignment */ && + m.kind !== 246 /* ShorthandPropertyAssignment */ && + m.kind !== 163 /* BindingElement */) { + continue; + } + // If this is the current item we are editing right now, do not filter it out + if (m.getStart() <= position && position <= m.getEnd()) { + continue; + } + var existingName = void 0; + if (m.kind === 163 /* BindingElement */ && m.propertyName) { + existingName = m.propertyName.text; + } + else { + // TODO(jfreeman): Account for computed property name + // NOTE: if one only performs this step when m.name is an identifier, + // things like '__proto__' are not filtered out. + existingName = m.name.text; + } + existingMemberNames[existingName] = true; + } + return ts.filter(contextualMemberSymbols, function (m) { return !ts.lookUp(existingMemberNames, m.name); }); + } + /** + * Filters out completion suggestions from 'symbols' according to existing JSX attributes. + * + * @returns Symbols to be suggested in a JSX element, barring those whose attributes + * do not occur at the current position and have not otherwise been typed. + */ + function filterJsxAttributes(symbols, attributes) { + var seenNames = {}; + for (var _i = 0; _i < attributes.length; _i++) { + var attr = attributes[_i]; + // If this is the current item we are editing right now, do not filter it out + if (attr.getStart() <= position && position <= attr.getEnd()) { + continue; + } + if (attr.kind === 238 /* JsxAttribute */) { + seenNames[attr.name.text] = true; + } + } + return ts.filter(symbols, function (a) { return !ts.lookUp(seenNames, a.name); }); + } + } + function getCompletionsAtPosition(fileName, position) { + synchronizeHostData(); + var completionData = getCompletionData(fileName, position); + if (!completionData) { + return undefined; + } + var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isRightOfDot = completionData.isRightOfDot, isJsDocTagName = completionData.isJsDocTagName; + var entries; + if (isJsDocTagName) { + // If the current position is a jsDoc tag name, only tag names should be provided for completion + return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: getAllJsDocCompletionEntries() }; + } + if (isRightOfDot && ts.isJavaScript(fileName)) { + entries = getCompletionEntriesFromSymbols(symbols); + ts.addRange(entries, getJavaScriptCompletionEntries()); + } + else { + if (!symbols || symbols.length === 0) { + return undefined; + } + entries = getCompletionEntriesFromSymbols(symbols); + } + // Add keywords if this is not a member completion list + if (!isMemberCompletion && !isJsDocTagName) { + ts.addRange(entries, keywordCompletions); + } + return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + function getJavaScriptCompletionEntries() { + var entries = []; + var allNames = {}; + var target = program.getCompilerOptions().target; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var nameTable = getNameTable(sourceFile); + for (var name_33 in nameTable) { + if (!allNames[name_33]) { + allNames[name_33] = name_33; + var displayName = getCompletionEntryDisplayName(name_33, target, /*performCharacterChecks:*/ true); + if (displayName) { + var entry = { + name: displayName, + kind: ScriptElementKind.warning, + kindModifiers: "", + sortText: "1" + }; + entries.push(entry); + } + } + } + } + return entries; + } + function getAllJsDocCompletionEntries() { + return jsDocCompletionEntries || (jsDocCompletionEntries = ts.map(jsDocTagNames, function (tagName) { + return { + name: tagName, + kind: ScriptElementKind.keyword, + kindModifiers: "", + sortText: "0" + }; + })); + } + function createCompletionEntry(symbol, location) { + // Try to get a valid display name for this symbol, if we could not find one, then ignore it. + // We would like to only show things that can be added after a dot, so for instance numeric properties can + // not be accessed with a dot (a.1 <- invalid) + var displayName = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, /*performCharacterChecks:*/ true, location); + if (!displayName) { + return undefined; + } + // TODO(drosen): Right now we just permit *all* semantic meanings when calling + // 'getSymbolKind' which is permissible given that it is backwards compatible; but + // really we should consider passing the meaning for the node so that we don't report + // that a suggestion for a value is an interface. We COULD also just do what + // 'getSymbolModifiers' does, which is to use the first declaration. + // Use a 'sortText' of 0' so that all symbol completion entries come before any other + // entries (like JavaScript identifier entries). + return { + name: displayName, + kind: getSymbolKind(symbol, location), + kindModifiers: getSymbolModifiers(symbol), + sortText: "0" + }; + } + function getCompletionEntriesFromSymbols(symbols) { + var start = new Date().getTime(); + var entries = []; + if (symbols) { + var nameToSymbol = {}; + for (var _i = 0; _i < symbols.length; _i++) { + var symbol = symbols[_i]; + var entry = createCompletionEntry(symbol, location); + if (entry) { + var id = ts.escapeIdentifier(entry.name); + if (!ts.lookUp(nameToSymbol, id)) { + entries.push(entry); + nameToSymbol[id] = symbol; + } + } + } + } + log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (new Date().getTime() - start)); + return entries; + } + } + function getCompletionEntryDetails(fileName, position, entryName) { + synchronizeHostData(); + // Compute all the completion symbols again. + var completionData = getCompletionData(fileName, position); + if (completionData) { + var symbols = completionData.symbols, location_2 = completionData.location; + // Find the symbol with the matching entry name. + var target = program.getCompilerOptions().target; + // We don't need to perform character checks here because we're only comparing the + // name against 'entryName' (which is known to be good), not building a new + // completion entry. + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, target, /*performCharacterChecks:*/ false, location_2) === entryName ? s : undefined; }); + if (symbol) { + var _a = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getValidSourceFile(fileName), location_2, location_2, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind; + return { + name: entryName, + kindModifiers: getSymbolModifiers(symbol), + kind: symbolKind, + displayParts: displayParts, + documentation: documentation + }; + } + } + // Didn't find a symbol with this name. See if we can find a keyword instead. + var keywordCompletion = ts.forEach(keywordCompletions, function (c) { return c.name === entryName; }); + if (keywordCompletion) { + return { + name: entryName, + kind: ScriptElementKind.keyword, + kindModifiers: ScriptElementKindModifier.none, + displayParts: [ts.displayPart(entryName, SymbolDisplayPartKind.keyword)], + documentation: undefined + }; + } + return undefined; + } + // TODO(drosen): use contextual SemanticMeaning. + function getSymbolKind(symbol, location) { + var flags = symbol.getFlags(); + if (flags & 32 /* Class */) + return ts.getDeclarationOfKind(symbol, 186 /* ClassExpression */) ? + ScriptElementKind.localClassElement : ScriptElementKind.classElement; + if (flags & 384 /* Enum */) + return ScriptElementKind.enumElement; + if (flags & 524288 /* TypeAlias */) + return ScriptElementKind.typeElement; + if (flags & 64 /* Interface */) + return ScriptElementKind.interfaceElement; + if (flags & 262144 /* TypeParameter */) + return ScriptElementKind.typeParameterElement; + var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, flags, location); + if (result === ScriptElementKind.unknown) { + if (flags & 262144 /* TypeParameter */) + return ScriptElementKind.typeParameterElement; + if (flags & 8 /* EnumMember */) + return ScriptElementKind.variableElement; + if (flags & 8388608 /* Alias */) + return ScriptElementKind.alias; + if (flags & 1536 /* Module */) + return ScriptElementKind.moduleElement; + } + return result; + } + function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, flags, location) { + var typeChecker = program.getTypeChecker(); + if (typeChecker.isUndefinedSymbol(symbol)) { + return ScriptElementKind.variableElement; + } + if (typeChecker.isArgumentsSymbol(symbol)) { + return ScriptElementKind.localVariableElement; + } + if (flags & 3 /* Variable */) { + if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { + return ScriptElementKind.parameterElement; + } + else if (symbol.valueDeclaration && ts.isConst(symbol.valueDeclaration)) { + return ScriptElementKind.constElement; + } + else if (ts.forEach(symbol.declarations, ts.isLet)) { + return ScriptElementKind.letElement; + } + return isLocalVariableOrFunction(symbol) ? ScriptElementKind.localVariableElement : ScriptElementKind.variableElement; + } + if (flags & 16 /* Function */) + return isLocalVariableOrFunction(symbol) ? ScriptElementKind.localFunctionElement : ScriptElementKind.functionElement; + if (flags & 32768 /* GetAccessor */) + return ScriptElementKind.memberGetAccessorElement; + if (flags & 65536 /* SetAccessor */) + return ScriptElementKind.memberSetAccessorElement; + if (flags & 8192 /* Method */) + return ScriptElementKind.memberFunctionElement; + if (flags & 16384 /* Constructor */) + return ScriptElementKind.constructorImplementationElement; + if (flags & 4 /* Property */) { + if (flags & 268435456 /* SyntheticProperty */) { + // If union property is result of union of non method (property/accessors/variables), it is labeled as property + var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { + var rootSymbolFlags = rootSymbol.getFlags(); + if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) { + return ScriptElementKind.memberVariableElement; + } + ts.Debug.assert(!!(rootSymbolFlags & 8192 /* Method */)); + }); + if (!unionPropertyKind) { + // If this was union of all methods, + //make sure it has call signatures before we can label it as method + var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); + if (typeOfUnionProperty.getCallSignatures().length) { + return ScriptElementKind.memberFunctionElement; + } + return ScriptElementKind.memberVariableElement; + } + return unionPropertyKind; + } + return ScriptElementKind.memberVariableElement; + } + return ScriptElementKind.unknown; + } + function getSymbolModifiers(symbol) { + return symbol && symbol.declarations && symbol.declarations.length > 0 + ? ts.getNodeModifiers(symbol.declarations[0]) + : ScriptElementKindModifier.none; + } + // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location + function getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { + if (semanticMeaning === void 0) { semanticMeaning = getMeaningFromLocation(location); } + var typeChecker = program.getTypeChecker(); + var displayParts = []; + var documentation; + var symbolFlags = symbol.flags; + var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, symbolFlags, location); + var hasAddedSymbolInfo; + var type; + // Class at constructor site need to be shown as constructor apart from property,method, vars + if (symbolKind !== ScriptElementKind.unknown || symbolFlags & 32 /* Class */ || symbolFlags & 8388608 /* Alias */) { + // If it is accessor they are allowed only if location is at name of the accessor + if (symbolKind === ScriptElementKind.memberGetAccessorElement || symbolKind === ScriptElementKind.memberSetAccessorElement) { + symbolKind = ScriptElementKind.memberVariableElement; + } + var signature; + type = typeChecker.getTypeOfSymbolAtLocation(symbol, location); + if (type) { + if (location.parent && location.parent.kind === 166 /* PropertyAccessExpression */) { + var right = location.parent.name; + // Either the location is on the right of a property access, or on the left and the right is missing + if (right === location || (right && right.getFullWidth() === 0)) { + location = location.parent; + } + } + // try get the call/construct signature from the type if it matches + var callExpression; + if (location.kind === 168 /* CallExpression */ || location.kind === 169 /* NewExpression */) { + callExpression = location; + } + else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { + callExpression = location.parent; + } + if (callExpression) { + var candidateSignatures = []; + signature = typeChecker.getResolvedSignature(callExpression, candidateSignatures); + if (!signature && candidateSignatures.length) { + // Use the first candidate: + signature = candidateSignatures[0]; + } + var useConstructSignatures = callExpression.kind === 169 /* NewExpression */ || callExpression.expression.kind === 95 /* SuperKeyword */; + var allSignatures = useConstructSignatures ? type.getConstructSignatures() : type.getCallSignatures(); + if (!ts.contains(allSignatures, signature.target) && !ts.contains(allSignatures, signature)) { + // Get the first signature if there is one -- allSignatures may contain + // either the original signature or its target, so check for either + signature = allSignatures.length ? allSignatures[0] : undefined; + } + if (signature) { + if (useConstructSignatures && (symbolFlags & 32 /* Class */)) { + // Constructor + symbolKind = ScriptElementKind.constructorImplementationElement; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else if (symbolFlags & 8388608 /* Alias */) { + symbolKind = ScriptElementKind.alias; + pushTypePart(symbolKind); + displayParts.push(ts.spacePart()); + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + addFullSymbolName(symbol); + } + else { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + } + switch (symbolKind) { + case ScriptElementKind.memberVariableElement: + case ScriptElementKind.variableElement: + case ScriptElementKind.constElement: + case ScriptElementKind.letElement: + case ScriptElementKind.parameterElement: + case ScriptElementKind.localVariableElement: + // If it is call or construct signature of lambda's write type name + displayParts.push(ts.punctuationPart(54 /* ColonToken */)); + displayParts.push(ts.spacePart()); + if (useConstructSignatures) { + displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + if (!(type.flags & 65536 /* Anonymous */)) { + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); + } + addSignatureDisplayParts(signature, allSignatures, 8 /* WriteArrowStyleSignature */); + break; + default: + // Just signature + addSignatureDisplayParts(signature, allSignatures); + } + hasAddedSymbolInfo = true; + } + } + else if ((isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304 /* Accessor */)) || + (location.kind === 121 /* ConstructorKeyword */ && location.parent.kind === 144 /* Constructor */)) { + // get the signature from the declaration and write it + var functionDeclaration = location.parent; + var allSignatures = functionDeclaration.kind === 144 /* Constructor */ ? type.getConstructSignatures() : type.getCallSignatures(); + if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); + } + else { + signature = allSignatures[0]; + } + if (functionDeclaration.kind === 144 /* Constructor */) { + // show (constructor) Type(...) signature + symbolKind = ScriptElementKind.constructorImplementationElement; + addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); + } + else { + // (function/method) symbol(..signature) + addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 147 /* CallSignature */ && + !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); + } + addSignatureDisplayParts(signature, allSignatures); + hasAddedSymbolInfo = true; + } + } + } + if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo) { + if (ts.getDeclarationOfKind(symbol, 186 /* ClassExpression */)) { + // Special case for class expressions because we would like to indicate that + // the class name is local to the class body (similar to function expression) + // (local class) class + pushTypePart(ScriptElementKind.localClassElement); + } + else { + // Class declaration has name which is not local. + displayParts.push(ts.keywordPart(73 /* ClassKeyword */)); + } + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + } + if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.keywordPart(107 /* InterfaceKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + } + if (symbolFlags & 524288 /* TypeAlias */) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.keywordPart(132 /* TypeKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + writeTypeParametersOfSymbol(symbol, sourceFile); + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration)); + } + if (symbolFlags & 384 /* Enum */) { + addNewLineIfDisplayPartsExist(); + if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { + displayParts.push(ts.keywordPart(74 /* ConstKeyword */)); + displayParts.push(ts.spacePart()); + } + displayParts.push(ts.keywordPart(81 /* EnumKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + if (symbolFlags & 1536 /* Module */) { + addNewLineIfDisplayPartsExist(); + var declaration = ts.getDeclarationOfKind(symbol, 218 /* ModuleDeclaration */); + var isNamespace = declaration && declaration.name && declaration.name.kind === 69 /* Identifier */; + displayParts.push(ts.keywordPart(isNamespace ? 126 /* NamespaceKeyword */ : 125 /* ModuleKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + displayParts.push(ts.textPart("type parameter")); + displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(90 /* InKeyword */)); + displayParts.push(ts.spacePart()); + if (symbol.parent) { + // Class/Interface type parameter + addFullSymbolName(symbol.parent, enclosingDeclaration); + writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); + } + else { + // Method/function type parameter + var container = ts.getContainingFunction(location); + if (container) { + var signatureDeclaration = ts.getDeclarationOfKind(symbol, 137 /* TypeParameter */).parent; + var signature = typeChecker.getSignatureFromDeclaration(signatureDeclaration); + if (signatureDeclaration.kind === 148 /* ConstructSignature */) { + displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + else if (signatureDeclaration.kind !== 147 /* CallSignature */ && signatureDeclaration.name) { + addFullSymbolName(signatureDeclaration.symbol); + } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); + } + else { + // Type aliash type parameter + // For example + // type list = T[]; // Both T will go through same code path + var declaration = ts.getDeclarationOfKind(symbol, 137 /* TypeParameter */).parent; + displayParts.push(ts.keywordPart(132 /* TypeKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(declaration.symbol); + writeTypeParametersOfSymbol(declaration.symbol, sourceFile); + } + } + } + if (symbolFlags & 8 /* EnumMember */) { + addPrefixForAnyFunctionOrVar(symbol, "enum member"); + var declaration = symbol.declarations[0]; + if (declaration.kind === 247 /* EnumMember */) { + var constantValue = typeChecker.getConstantValue(declaration); + if (constantValue !== undefined) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.displayPart(constantValue.toString(), SymbolDisplayPartKind.numericLiteral)); + } + } + } + if (symbolFlags & 8388608 /* Alias */) { + addNewLineIfDisplayPartsExist(); + displayParts.push(ts.keywordPart(89 /* ImportKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + ts.forEach(symbol.declarations, function (declaration) { + if (declaration.kind === 221 /* ImportEqualsDeclaration */) { + var importEqualsDeclaration = declaration; + if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.keywordPart(127 /* RequireKeyword */)); + displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + displayParts.push(ts.displayPart(ts.getTextOfNode(ts.getExternalModuleImportEqualsDeclarationExpression(importEqualsDeclaration)), SymbolDisplayPartKind.stringLiteral)); + displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + } + else { + var internalAliasSymbol = typeChecker.getSymbolAtLocation(importEqualsDeclaration.moduleReference); + if (internalAliasSymbol) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.operatorPart(56 /* EqualsToken */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(internalAliasSymbol, enclosingDeclaration); + } + } + return true; + } + }); + } + if (!hasAddedSymbolInfo) { + if (symbolKind !== ScriptElementKind.unknown) { + if (type) { + addPrefixForAnyFunctionOrVar(symbol, symbolKind); + // For properties, variables and local vars: show the type + if (symbolKind === ScriptElementKind.memberVariableElement || + symbolFlags & 3 /* Variable */ || + symbolKind === ScriptElementKind.localVariableElement) { + displayParts.push(ts.punctuationPart(54 /* ColonToken */)); + displayParts.push(ts.spacePart()); + // If the type is type parameter, format it specially + if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(type, writer, enclosingDeclaration); + }); + ts.addRange(displayParts, typeParameterParts); + } + else { + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, type, enclosingDeclaration)); + } + } + else if (symbolFlags & 16 /* Function */ || + symbolFlags & 8192 /* Method */ || + symbolFlags & 16384 /* Constructor */ || + symbolFlags & 131072 /* Signature */ || + symbolFlags & 98304 /* Accessor */ || + symbolKind === ScriptElementKind.memberFunctionElement) { + var allSignatures = type.getCallSignatures(); + addSignatureDisplayParts(allSignatures[0], allSignatures); + } + } + } + else { + symbolKind = getSymbolKind(symbol, location); + } + } + if (!documentation) { + documentation = symbol.getDocumentationComment(); + } + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind }; + function addNewLineIfDisplayPartsExist() { + if (displayParts.length) { + displayParts.push(ts.lineBreakPart()); + } + } + function addFullSymbolName(symbol, enclosingDeclaration) { + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); + ts.addRange(displayParts, fullSymbolDisplayParts); + } + function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { + addNewLineIfDisplayPartsExist(); + if (symbolKind) { + pushTypePart(symbolKind); + displayParts.push(ts.spacePart()); + addFullSymbolName(symbol); + } + } + function pushTypePart(symbolKind) { + switch (symbolKind) { + case ScriptElementKind.variableElement: + case ScriptElementKind.functionElement: + case ScriptElementKind.letElement: + case ScriptElementKind.constElement: + case ScriptElementKind.constructorImplementationElement: + displayParts.push(ts.textOrKeywordPart(symbolKind)); + return; + default: + displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + displayParts.push(ts.textOrKeywordPart(symbolKind)); + displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + return; + } + } + function addSignatureDisplayParts(signature, allSignatures, flags) { + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); + if (allSignatures.length > 1) { + displayParts.push(ts.spacePart()); + displayParts.push(ts.punctuationPart(17 /* OpenParenToken */)); + displayParts.push(ts.operatorPart(35 /* PlusToken */)); + displayParts.push(ts.displayPart((allSignatures.length - 1).toString(), SymbolDisplayPartKind.numericLiteral)); + displayParts.push(ts.spacePart()); + displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); + displayParts.push(ts.punctuationPart(18 /* CloseParenToken */)); + } + documentation = signature.getDocumentationComment(); + } + function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { + var typeParameterParts = ts.mapToDisplayParts(function (writer) { + typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration); + }); + ts.addRange(displayParts, typeParameterParts); + } + } + function getQuickInfoAtPosition(fileName, position) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var node = ts.getTouchingPropertyName(sourceFile, position); + if (!node) { + return undefined; + } + if (isLabelName(node)) { + return undefined; + } + var typeChecker = program.getTypeChecker(); + var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) { + // Try getting just type at this position and show + switch (node.kind) { + case 69 /* Identifier */: + case 166 /* PropertyAccessExpression */: + case 135 /* QualifiedName */: + case 97 /* ThisKeyword */: + case 95 /* SuperKeyword */: + // For the identifiers/this/super etc get the type at position + var type = typeChecker.getTypeAtLocation(node); + if (type) { + return { + kind: ScriptElementKind.unknown, + kindModifiers: ScriptElementKindModifier.none, + textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), + displayParts: ts.typeToDisplayParts(typeChecker, type, getContainerNode(node)), + documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined + }; + } + } + return undefined; + } + var displayPartsDocumentationsAndKind = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, sourceFile, getContainerNode(node), node); + return { + kind: displayPartsDocumentationsAndKind.symbolKind, + kindModifiers: getSymbolModifiers(symbol), + textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), + displayParts: displayPartsDocumentationsAndKind.displayParts, + documentation: displayPartsDocumentationsAndKind.documentation + }; + } + function createDefinitionInfo(node, symbolKind, symbolName, containerName) { + return { + fileName: node.getSourceFile().fileName, + textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()), + kind: symbolKind, + name: symbolName, + containerKind: undefined, + containerName: containerName + }; + } + function getDefinitionFromSymbol(symbol, node) { + var typeChecker = program.getTypeChecker(); + var result = []; + var declarations = symbol.getDeclarations(); + var symbolName = typeChecker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol + var symbolKind = getSymbolKind(symbol, node); + var containerSymbol = symbol.parent; + var containerName = containerSymbol ? typeChecker.symbolToString(containerSymbol, node) : ""; + if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && + !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { + // Just add all the declarations. + ts.forEach(declarations, function (declaration) { + result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); + }); + } + return result; + function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { + // Applicable only if we are in a new expression, or we are on a constructor declaration + // and in either case the symbol has a construct signature definition, i.e. class + if (isNewExpressionTarget(location) || location.kind === 121 /* ConstructorKeyword */) { + if (symbol.flags & 32 /* Class */) { + // Find the first class-like declaration and try to get the construct signature. + for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isClassLike(declaration)) { + return tryAddSignature(declaration.members, + /*selectConstructors*/ true, symbolKind, symbolName, containerName, result); + } + } + ts.Debug.fail("Expected declaration to have at least one class-like declaration"); + } + } + return false; + } + function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { + if (isCallExpressionTarget(location) || isNewExpressionTarget(location) || isNameOfFunctionDeclaration(location)) { + return tryAddSignature(symbol.declarations, /*selectConstructors*/ false, symbolKind, symbolName, containerName, result); + } + return false; + } + function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { + var declarations = []; + var definition; + ts.forEach(signatureDeclarations, function (d) { + if ((selectConstructors && d.kind === 144 /* Constructor */) || + (!selectConstructors && (d.kind === 213 /* FunctionDeclaration */ || d.kind === 143 /* MethodDeclaration */ || d.kind === 142 /* MethodSignature */))) { + declarations.push(d); + if (d.body) + definition = d; + } + }); + if (definition) { + result.push(createDefinitionInfo(definition, symbolKind, symbolName, containerName)); + return true; + } + else if (declarations.length) { + result.push(createDefinitionInfo(ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); + return true; + } + return false; + } + } + /// Goto definition + function getDefinitionAtPosition(fileName, position) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var node = ts.getTouchingPropertyName(sourceFile, position); + if (!node) { + return undefined; + } + // Labels + if (isJumpStatementTarget(node)) { + var labelName = node.text; + var label = getTargetLabel(node.parent, node.text); + return label ? [createDefinitionInfo(label, ScriptElementKind.label, labelName, /*containerName*/ undefined)] : undefined; + } + /// Triple slash reference comments + var comment = ts.forEach(sourceFile.referencedFiles, function (r) { return (r.pos <= position && position < r.end) ? r : undefined; }); + if (comment) { + var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); + if (referenceFile) { + return [{ + fileName: referenceFile.fileName, + textSpan: ts.createTextSpanFromBounds(0, 0), + kind: ScriptElementKind.scriptElement, + name: comment.fileName, + containerName: undefined, + containerKind: undefined + }]; + } + return undefined; + } + var typeChecker = program.getTypeChecker(); + var symbol = typeChecker.getSymbolAtLocation(node); + // Could not find a symbol e.g. node is string or number keyword, + // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol + if (!symbol) { + return undefined; + } + // If this is an alias, and the request came at the declaration location + // get the aliased symbol instead. This allows for goto def on an import e.g. + // import {A, B} from "mod"; + // to jump to the implementation directly. + if (symbol.flags & 8388608 /* Alias */) { + var declaration = symbol.declarations[0]; + if (node.kind === 69 /* Identifier */ && node.parent === declaration) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + } + // Because name in short-hand property assignment has two different meanings: property name and property value, + // using go-to-definition at such position should go to the variable declaration of the property value rather than + // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition + // is performed at the location of property access, we would like to go to definition of the property in the short-hand + // assignment. This case and others are handled by the following code. + if (node.parent.kind === 246 /* ShorthandPropertyAssignment */) { + var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); + if (!shorthandSymbol) { + return []; + } + var shorthandDeclarations = shorthandSymbol.getDeclarations(); + var shorthandSymbolKind = getSymbolKind(shorthandSymbol, node); + var shorthandSymbolName = typeChecker.symbolToString(shorthandSymbol); + var shorthandContainerName = typeChecker.symbolToString(symbol.parent, node); + return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind, shorthandSymbolName, shorthandContainerName); }); + } + return getDefinitionFromSymbol(symbol, node); + } + /// Goto type + function getTypeDefinitionAtPosition(fileName, position) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var node = ts.getTouchingPropertyName(sourceFile, position); + if (!node) { + return undefined; + } + var typeChecker = program.getTypeChecker(); + var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) { + return undefined; + } + var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + if (!type) { + return undefined; + } + if (type.flags & 16384 /* Union */) { + var result = []; + ts.forEach(type.types, function (t) { + if (t.symbol) { + ts.addRange(/*to*/ result, /*from*/ getDefinitionFromSymbol(t.symbol, node)); + } + }); + return result; + } + if (!type.symbol) { + return undefined; + } + return getDefinitionFromSymbol(type.symbol, node); + } + function getOccurrencesAtPosition(fileName, position) { + var results = getOccurrencesAtPositionCore(fileName, position); + if (results) { + var sourceFile = getCanonicalFileName(ts.normalizeSlashes(fileName)); + // Get occurrences only supports reporting occurrences for the file queried. So + // filter down to that list. + results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile; }); + } + return results; + } + function getDocumentHighlights(fileName, position, filesToSearch) { + synchronizeHostData(); + filesToSearch = ts.map(filesToSearch, ts.normalizeSlashes); + var sourceFilesToSearch = ts.filter(program.getSourceFiles(), function (f) { return ts.contains(filesToSearch, f.fileName); }); + var sourceFile = getValidSourceFile(fileName); + var node = ts.getTouchingWord(sourceFile, position); + if (!node) { + return undefined; + } + return getSemanticDocumentHighlights(node) || getSyntacticDocumentHighlights(node); + function getHighlightSpanForNode(node) { + var start = node.getStart(); + var end = node.getEnd(); + return { + fileName: sourceFile.fileName, + textSpan: ts.createTextSpanFromBounds(start, end), + kind: HighlightSpanKind.none + }; + } + function getSemanticDocumentHighlights(node) { + if (node.kind === 69 /* Identifier */ || + node.kind === 97 /* ThisKeyword */ || + node.kind === 95 /* SuperKeyword */ || + isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || + isNameOfExternalModuleImportOrDeclaration(node)) { + var referencedSymbols = getReferencedSymbolsForNode(node, sourceFilesToSearch, /*findInStrings:*/ false, /*findInComments:*/ false); + return convertReferencedSymbols(referencedSymbols); + } + return undefined; + function convertReferencedSymbols(referencedSymbols) { + if (!referencedSymbols) { + return undefined; + } + var fileNameToDocumentHighlights = {}; + var result = []; + for (var _i = 0; _i < referencedSymbols.length; _i++) { + var referencedSymbol = referencedSymbols[_i]; + for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { + var referenceEntry = _b[_a]; + var fileName_1 = referenceEntry.fileName; + var documentHighlights = ts.getProperty(fileNameToDocumentHighlights, fileName_1); + if (!documentHighlights) { + documentHighlights = { fileName: fileName_1, highlightSpans: [] }; + fileNameToDocumentHighlights[fileName_1] = documentHighlights; + result.push(documentHighlights); + } + documentHighlights.highlightSpans.push({ + textSpan: referenceEntry.textSpan, + kind: referenceEntry.isWriteAccess ? HighlightSpanKind.writtenReference : HighlightSpanKind.reference + }); + } + } + return result; + } + } + function getSyntacticDocumentHighlights(node) { + var fileName = sourceFile.fileName; + var highlightSpans = getHighlightSpans(node); + if (!highlightSpans || highlightSpans.length === 0) { + return undefined; + } + return [{ fileName: fileName, highlightSpans: highlightSpans }]; + // returns true if 'node' is defined and has a matching 'kind'. + function hasKind(node, kind) { + return node !== undefined && node.kind === kind; + } + // Null-propagating 'parent' function. + function parent(node) { + return node && node.parent; + } + function getHighlightSpans(node) { + if (node) { + switch (node.kind) { + case 88 /* IfKeyword */: + case 80 /* ElseKeyword */: + if (hasKind(node.parent, 196 /* IfStatement */)) { + return getIfElseOccurrences(node.parent); + } + break; + case 94 /* ReturnKeyword */: + if (hasKind(node.parent, 204 /* ReturnStatement */)) { + return getReturnOccurrences(node.parent); + } + break; + case 98 /* ThrowKeyword */: + if (hasKind(node.parent, 208 /* ThrowStatement */)) { + return getThrowOccurrences(node.parent); + } + break; + case 72 /* CatchKeyword */: + if (hasKind(parent(parent(node)), 209 /* TryStatement */)) { + return getTryCatchFinallyOccurrences(node.parent.parent); + } + break; + case 100 /* TryKeyword */: + case 85 /* FinallyKeyword */: + if (hasKind(parent(node), 209 /* TryStatement */)) { + return getTryCatchFinallyOccurrences(node.parent); + } + break; + case 96 /* SwitchKeyword */: + if (hasKind(node.parent, 206 /* SwitchStatement */)) { + return getSwitchCaseDefaultOccurrences(node.parent); + } + break; + case 71 /* CaseKeyword */: + case 77 /* DefaultKeyword */: + if (hasKind(parent(parent(parent(node))), 206 /* SwitchStatement */)) { + return getSwitchCaseDefaultOccurrences(node.parent.parent.parent); + } + break; + case 70 /* BreakKeyword */: + case 75 /* ContinueKeyword */: + if (hasKind(node.parent, 203 /* BreakStatement */) || hasKind(node.parent, 202 /* ContinueStatement */)) { + return getBreakOrContinueStatementOccurrences(node.parent); + } + break; + case 86 /* ForKeyword */: + if (hasKind(node.parent, 199 /* ForStatement */) || + hasKind(node.parent, 200 /* ForInStatement */) || + hasKind(node.parent, 201 /* ForOfStatement */)) { + return getLoopBreakContinueOccurrences(node.parent); + } + break; + case 104 /* WhileKeyword */: + case 79 /* DoKeyword */: + if (hasKind(node.parent, 198 /* WhileStatement */) || hasKind(node.parent, 197 /* DoStatement */)) { + return getLoopBreakContinueOccurrences(node.parent); + } + break; + case 121 /* ConstructorKeyword */: + if (hasKind(node.parent, 144 /* Constructor */)) { + return getConstructorOccurrences(node.parent); + } + break; + case 123 /* GetKeyword */: + case 129 /* SetKeyword */: + if (hasKind(node.parent, 145 /* GetAccessor */) || hasKind(node.parent, 146 /* SetAccessor */)) { + return getGetAndSetOccurrences(node.parent); + } + break; + default: + if (ts.isModifier(node.kind) && node.parent && + (ts.isDeclaration(node.parent) || node.parent.kind === 193 /* VariableStatement */)) { + return getModifierOccurrences(node.kind, node.parent); + } + } + } + return undefined; + } + /** + * Aggregates all throw-statements within this node *without* crossing + * into function boundaries and try-blocks with catch-clauses. + */ + function aggregateOwnedThrowStatements(node) { + var statementAccumulator = []; + aggregate(node); + return statementAccumulator; + function aggregate(node) { + if (node.kind === 208 /* ThrowStatement */) { + statementAccumulator.push(node); + } + else if (node.kind === 209 /* TryStatement */) { + var tryStatement = node; + if (tryStatement.catchClause) { + aggregate(tryStatement.catchClause); + } + else { + // Exceptions thrown within a try block lacking a catch clause + // are "owned" in the current context. + aggregate(tryStatement.tryBlock); + } + if (tryStatement.finallyBlock) { + aggregate(tryStatement.finallyBlock); + } + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, aggregate); + } + } + ; + } + /** + * For lack of a better name, this function takes a throw statement and returns the + * nearest ancestor that is a try-block (whose try statement has a catch clause), + * function-block, or source file. + */ + function getThrowStatementOwner(throwStatement) { + var child = throwStatement; + while (child.parent) { + var parent_12 = child.parent; + if (ts.isFunctionBlock(parent_12) || parent_12.kind === 248 /* SourceFile */) { + return parent_12; + } + // A throw-statement is only owned by a try-statement if the try-statement has + // a catch clause, and if the throw-statement occurs within the try block. + if (parent_12.kind === 209 /* TryStatement */) { + var tryStatement = parent_12; + if (tryStatement.tryBlock === child && tryStatement.catchClause) { + return child; + } + } + child = parent_12; + } + return undefined; + } + function aggregateAllBreakAndContinueStatements(node) { + var statementAccumulator = []; + aggregate(node); + return statementAccumulator; + function aggregate(node) { + if (node.kind === 203 /* BreakStatement */ || node.kind === 202 /* ContinueStatement */) { + statementAccumulator.push(node); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, aggregate); + } + } + ; + } + function ownsBreakOrContinueStatement(owner, statement) { + var actualOwner = getBreakOrContinueOwner(statement); + return actualOwner && actualOwner === owner; + } + function getBreakOrContinueOwner(statement) { + for (var node_2 = statement.parent; node_2; node_2 = node_2.parent) { + switch (node_2.kind) { + case 206 /* SwitchStatement */: + if (statement.kind === 202 /* ContinueStatement */) { + continue; + } + // Fall through. + case 199 /* ForStatement */: + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + case 198 /* WhileStatement */: + case 197 /* DoStatement */: + if (!statement.label || isLabeledBy(node_2, statement.label.text)) { + return node_2; + } + break; + default: + // Don't cross function boundaries. + if (ts.isFunctionLike(node_2)) { + return undefined; + } + break; + } + } + return undefined; + } + function getModifierOccurrences(modifier, declaration) { + var container = declaration.parent; + // Make sure we only highlight the keyword when it makes sense to do so. + if (ts.isAccessibilityModifier(modifier)) { + if (!(container.kind === 214 /* ClassDeclaration */ || + container.kind === 186 /* ClassExpression */ || + (declaration.kind === 138 /* Parameter */ && hasKind(container, 144 /* Constructor */)))) { + return undefined; + } + } + else if (modifier === 113 /* StaticKeyword */) { + if (!(container.kind === 214 /* ClassDeclaration */ || container.kind === 186 /* ClassExpression */)) { + return undefined; + } + } + else if (modifier === 82 /* ExportKeyword */ || modifier === 122 /* DeclareKeyword */) { + if (!(container.kind === 219 /* ModuleBlock */ || container.kind === 248 /* SourceFile */)) { + return undefined; + } + } + else if (modifier === 115 /* AbstractKeyword */) { + if (!(container.kind === 214 /* ClassDeclaration */ || declaration.kind === 214 /* ClassDeclaration */)) { + return undefined; + } + } + else { + // unsupported modifier + return undefined; + } + var keywords = []; + var modifierFlag = getFlagFromModifier(modifier); + var nodes; + switch (container.kind) { + case 219 /* ModuleBlock */: + case 248 /* SourceFile */: + // Container is either a class declaration or the declaration is a classDeclaration + if (modifierFlag & 256 /* Abstract */) { + nodes = declaration.members.concat(declaration); + } + else { + nodes = container.statements; + } + break; + case 144 /* Constructor */: + nodes = container.parameters.concat(container.parent.members); + break; + case 214 /* ClassDeclaration */: + case 186 /* ClassExpression */: + nodes = container.members; + // If we're an accessibility modifier, we're in an instance member and should search + // the constructor's parameter list for instance members as well. + if (modifierFlag & 112 /* AccessibilityModifier */) { + var constructor = ts.forEach(container.members, function (member) { + return member.kind === 144 /* Constructor */ && member; + }); + if (constructor) { + nodes = nodes.concat(constructor.parameters); + } + } + else if (modifierFlag & 256 /* Abstract */) { + nodes = nodes.concat(container); + } + break; + default: + ts.Debug.fail("Invalid container kind."); + } + ts.forEach(nodes, function (node) { + if (node.modifiers && node.flags & modifierFlag) { + ts.forEach(node.modifiers, function (child) { return pushKeywordIf(keywords, child, modifier); }); + } + }); + return ts.map(keywords, getHighlightSpanForNode); + function getFlagFromModifier(modifier) { + switch (modifier) { + case 112 /* PublicKeyword */: + return 16 /* Public */; + case 110 /* PrivateKeyword */: + return 32 /* Private */; + case 111 /* ProtectedKeyword */: + return 64 /* Protected */; + case 113 /* StaticKeyword */: + return 128 /* Static */; + case 82 /* ExportKeyword */: + return 1 /* Export */; + case 122 /* DeclareKeyword */: + return 2 /* Ambient */; + case 115 /* AbstractKeyword */: + return 256 /* Abstract */; + default: + ts.Debug.fail(); + } + } + } + function pushKeywordIf(keywordList, token) { + var expected = []; + for (var _i = 2; _i < arguments.length; _i++) { + expected[_i - 2] = arguments[_i]; + } + if (token && ts.contains(expected, token.kind)) { + keywordList.push(token); + return true; + } + return false; + } + function getGetAndSetOccurrences(accessorDeclaration) { + var keywords = []; + tryPushAccessorKeyword(accessorDeclaration.symbol, 145 /* GetAccessor */); + tryPushAccessorKeyword(accessorDeclaration.symbol, 146 /* SetAccessor */); + return ts.map(keywords, getHighlightSpanForNode); + function tryPushAccessorKeyword(accessorSymbol, accessorKind) { + var accessor = ts.getDeclarationOfKind(accessorSymbol, accessorKind); + if (accessor) { + ts.forEach(accessor.getChildren(), function (child) { return pushKeywordIf(keywords, child, 123 /* GetKeyword */, 129 /* SetKeyword */); }); + } + } + } + function getConstructorOccurrences(constructorDeclaration) { + var declarations = constructorDeclaration.symbol.getDeclarations(); + var keywords = []; + ts.forEach(declarations, function (declaration) { + ts.forEach(declaration.getChildren(), function (token) { + return pushKeywordIf(keywords, token, 121 /* ConstructorKeyword */); + }); + }); + return ts.map(keywords, getHighlightSpanForNode); + } + function getLoopBreakContinueOccurrences(loopNode) { + var keywords = []; + if (pushKeywordIf(keywords, loopNode.getFirstToken(), 86 /* ForKeyword */, 104 /* WhileKeyword */, 79 /* DoKeyword */)) { + // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. + if (loopNode.kind === 197 /* DoStatement */) { + var loopTokens = loopNode.getChildren(); + for (var i = loopTokens.length - 1; i >= 0; i--) { + if (pushKeywordIf(keywords, loopTokens[i], 104 /* WhileKeyword */)) { + break; + } + } + } + } + var breaksAndContinues = aggregateAllBreakAndContinueStatements(loopNode.statement); + ts.forEach(breaksAndContinues, function (statement) { + if (ownsBreakOrContinueStatement(loopNode, statement)) { + pushKeywordIf(keywords, statement.getFirstToken(), 70 /* BreakKeyword */, 75 /* ContinueKeyword */); + } + }); + return ts.map(keywords, getHighlightSpanForNode); + } + function getBreakOrContinueStatementOccurrences(breakOrContinueStatement) { + var owner = getBreakOrContinueOwner(breakOrContinueStatement); + if (owner) { + switch (owner.kind) { + case 199 /* ForStatement */: + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + case 197 /* DoStatement */: + case 198 /* WhileStatement */: + return getLoopBreakContinueOccurrences(owner); + case 206 /* SwitchStatement */: + return getSwitchCaseDefaultOccurrences(owner); + } + } + return undefined; + } + function getSwitchCaseDefaultOccurrences(switchStatement) { + var keywords = []; + pushKeywordIf(keywords, switchStatement.getFirstToken(), 96 /* SwitchKeyword */); + // Go through each clause in the switch statement, collecting the 'case'/'default' keywords. + ts.forEach(switchStatement.caseBlock.clauses, function (clause) { + pushKeywordIf(keywords, clause.getFirstToken(), 71 /* CaseKeyword */, 77 /* DefaultKeyword */); + var breaksAndContinues = aggregateAllBreakAndContinueStatements(clause); + ts.forEach(breaksAndContinues, function (statement) { + if (ownsBreakOrContinueStatement(switchStatement, statement)) { + pushKeywordIf(keywords, statement.getFirstToken(), 70 /* BreakKeyword */); + } + }); + }); + return ts.map(keywords, getHighlightSpanForNode); + } + function getTryCatchFinallyOccurrences(tryStatement) { + var keywords = []; + pushKeywordIf(keywords, tryStatement.getFirstToken(), 100 /* TryKeyword */); + if (tryStatement.catchClause) { + pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 72 /* CatchKeyword */); + } + if (tryStatement.finallyBlock) { + var finallyKeyword = ts.findChildOfKind(tryStatement, 85 /* FinallyKeyword */, sourceFile); + pushKeywordIf(keywords, finallyKeyword, 85 /* FinallyKeyword */); + } + return ts.map(keywords, getHighlightSpanForNode); + } + function getThrowOccurrences(throwStatement) { + var owner = getThrowStatementOwner(throwStatement); + if (!owner) { + return undefined; + } + var keywords = []; + ts.forEach(aggregateOwnedThrowStatements(owner), function (throwStatement) { + pushKeywordIf(keywords, throwStatement.getFirstToken(), 98 /* ThrowKeyword */); + }); + // If the "owner" is a function, then we equate 'return' and 'throw' statements in their + // ability to "jump out" of the function, and include occurrences for both. + if (ts.isFunctionBlock(owner)) { + ts.forEachReturnStatement(owner, function (returnStatement) { + pushKeywordIf(keywords, returnStatement.getFirstToken(), 94 /* ReturnKeyword */); + }); + } + return ts.map(keywords, getHighlightSpanForNode); + } + function getReturnOccurrences(returnStatement) { + var func = ts.getContainingFunction(returnStatement); + // If we didn't find a containing function with a block body, bail out. + if (!(func && hasKind(func.body, 192 /* Block */))) { + return undefined; + } + var keywords = []; + ts.forEachReturnStatement(func.body, function (returnStatement) { + pushKeywordIf(keywords, returnStatement.getFirstToken(), 94 /* ReturnKeyword */); + }); + // Include 'throw' statements that do not occur within a try block. + ts.forEach(aggregateOwnedThrowStatements(func.body), function (throwStatement) { + pushKeywordIf(keywords, throwStatement.getFirstToken(), 98 /* ThrowKeyword */); + }); + return ts.map(keywords, getHighlightSpanForNode); + } + function getIfElseOccurrences(ifStatement) { + var keywords = []; + // Traverse upwards through all parent if-statements linked by their else-branches. + while (hasKind(ifStatement.parent, 196 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { + ifStatement = ifStatement.parent; + } + // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. + while (ifStatement) { + var children = ifStatement.getChildren(); + pushKeywordIf(keywords, children[0], 88 /* IfKeyword */); + // Generally the 'else' keyword is second-to-last, so we traverse backwards. + for (var i = children.length - 1; i >= 0; i--) { + if (pushKeywordIf(keywords, children[i], 80 /* ElseKeyword */)) { + break; + } + } + if (!hasKind(ifStatement.elseStatement, 196 /* IfStatement */)) { + break; + } + ifStatement = ifStatement.elseStatement; + } + var result = []; + // We'd like to highlight else/ifs together if they are only separated by whitespace + // (i.e. the keywords are separated by no comments, no newlines). + for (var i = 0; i < keywords.length; i++) { + if (keywords[i].kind === 80 /* ElseKeyword */ && i < keywords.length - 1) { + var elseKeyword = keywords[i]; + var ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword. + var shouldCombindElseAndIf = true; + // Avoid recalculating getStart() by iterating backwards. + for (var j = ifKeyword.getStart() - 1; j >= elseKeyword.end; j--) { + if (!ts.isWhiteSpace(sourceFile.text.charCodeAt(j))) { + shouldCombindElseAndIf = false; + break; + } + } + if (shouldCombindElseAndIf) { + result.push({ + fileName: fileName, + textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), + kind: HighlightSpanKind.reference + }); + i++; // skip the next keyword + continue; + } + } + // Ordinary case: just highlight the keyword. + result.push(getHighlightSpanForNode(keywords[i])); + } + return result; + } + } + } + /// References and Occurrences + function getOccurrencesAtPositionCore(fileName, position) { + synchronizeHostData(); + return convertDocumentHighlights(getDocumentHighlights(fileName, position, [fileName])); + function convertDocumentHighlights(documentHighlights) { + if (!documentHighlights) { + return undefined; + } + var result = []; + for (var _i = 0; _i < documentHighlights.length; _i++) { + var entry = documentHighlights[_i]; + for (var _a = 0, _b = entry.highlightSpans; _a < _b.length; _a++) { + var highlightSpan = _b[_a]; + result.push({ + fileName: entry.fileName, + textSpan: highlightSpan.textSpan, + isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference + }); + } + } + return result; + } + } + function convertReferences(referenceSymbols) { + if (!referenceSymbols) { + return undefined; + } + var referenceEntries = []; + for (var _i = 0; _i < referenceSymbols.length; _i++) { + var referenceSymbol = referenceSymbols[_i]; + ts.addRange(referenceEntries, referenceSymbol.references); + } + return referenceEntries; + } + function findRenameLocations(fileName, position, findInStrings, findInComments) { + var referencedSymbols = findReferencedSymbols(fileName, position, findInStrings, findInComments); + return convertReferences(referencedSymbols); + } + function getReferencesAtPosition(fileName, position) { + var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false); + return convertReferences(referencedSymbols); + } + function findReferences(fileName, position) { + var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false); + // Only include referenced symbols that have a valid definition. + return ts.filter(referencedSymbols, function (rs) { return !!rs.definition; }); + } + function findReferencedSymbols(fileName, position, findInStrings, findInComments) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var node = ts.getTouchingPropertyName(sourceFile, position); + if (!node) { + return undefined; + } + if (node.kind !== 69 /* Identifier */ && + // TODO (drosen): This should be enabled in a later release - currently breaks rename. + //node.kind !== SyntaxKind.ThisKeyword && + //node.kind !== SyntaxKind.SuperKeyword && + !isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && + !isNameOfExternalModuleImportOrDeclaration(node)) { + return undefined; + } + ts.Debug.assert(node.kind === 69 /* Identifier */ || node.kind === 8 /* NumericLiteral */ || node.kind === 9 /* StringLiteral */); + return getReferencedSymbolsForNode(node, program.getSourceFiles(), findInStrings, findInComments); + } + function getReferencedSymbolsForNode(node, sourceFiles, findInStrings, findInComments) { + var typeChecker = program.getTypeChecker(); + // Labels + if (isLabelName(node)) { + if (isJumpStatementTarget(node)) { + var labelDefinition = getTargetLabel(node.parent, node.text); + // if we have a label definition, look within its statement for references, if not, then + // the label is undefined and we have no results.. + return labelDefinition ? getLabelReferencesInNode(labelDefinition.parent, labelDefinition) : undefined; + } + else { + // it is a label definition and not a target, search within the parent labeledStatement + return getLabelReferencesInNode(node.parent, node); + } + } + if (node.kind === 97 /* ThisKeyword */) { + return getReferencesForThisKeyword(node, sourceFiles); + } + if (node.kind === 95 /* SuperKeyword */) { + return getReferencesForSuperKeyword(node); + } + var symbol = typeChecker.getSymbolAtLocation(node); + // Could not find a symbol e.g. unknown identifier + if (!symbol) { + // Can't have references to something that we have no symbol for. + return undefined; + } + var declarations = symbol.declarations; + // The symbol was an internal symbol and does not have a declaration e.g. undefined symbol + if (!declarations || !declarations.length) { + return undefined; + } + var result; + // Compute the meaning from the location and the symbol it references + var searchMeaning = getIntersectingMeaningFromDeclarations(getMeaningFromLocation(node), declarations); + // Get the text to search for. + // Note: if this is an external module symbol, the name doesn't include quotes. + var declaredName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); + // Try to get the smallest valid scope that we can limit our search to; + // otherwise we'll need to search globally (i.e. include each file). + var scope = getSymbolScope(symbol); + // Maps from a symbol ID to the ReferencedSymbol entry in 'result'. + var symbolToIndex = []; + if (scope) { + result = []; + getReferencesInNode(scope, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); + } + else { + var internedName = getInternedName(symbol, node, declarations); + for (var _i = 0; _i < sourceFiles.length; _i++) { + var sourceFile = sourceFiles[_i]; + cancellationToken.throwIfCancellationRequested(); + var nameTable = getNameTable(sourceFile); + if (ts.lookUp(nameTable, internedName)) { + result = result || []; + getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); + } + } + } + return result; + function getDefinition(symbol) { + var info = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, node.getSourceFile(), getContainerNode(node), node); + var name = ts.map(info.displayParts, function (p) { return p.text; }).join(""); + var declarations = symbol.declarations; + if (!declarations || declarations.length === 0) { + return undefined; + } + return { + containerKind: "", + containerName: "", + name: name, + kind: info.symbolKind, + fileName: declarations[0].getSourceFile().fileName, + textSpan: ts.createTextSpan(declarations[0].getStart(), 0) + }; + } + function isImportOrExportSpecifierImportSymbol(symbol) { + return (symbol.flags & 8388608 /* Alias */) && ts.forEach(symbol.declarations, function (declaration) { + return declaration.kind === 226 /* ImportSpecifier */ || declaration.kind === 230 /* ExportSpecifier */; + }); + } + function getInternedName(symbol, location, declarations) { + // If this is an export or import specifier it could have been renamed using the 'as' syntax. + // If so we want to search for whatever under the cursor. + if (ts.isImportOrExportSpecifierName(location)) { + return location.getText(); + } + // Try to get the local symbol if we're dealing with an 'export default' + // since that symbol has the "true" name. + var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); + symbol = localExportDefaultSymbol || symbol; + return ts.stripQuotes(symbol.name); + } + /** + * Determines the smallest scope in which a symbol may have named references. + * Note that not every construct has been accounted for. This function can + * probably be improved. + * + * @returns undefined if the scope cannot be determined, implying that + * a reference to a symbol can occur anywhere. + */ + function getSymbolScope(symbol) { + // If this is the symbol of a named function expression or named class expression, + // then named references are limited to its own scope. + var valueDeclaration = symbol.valueDeclaration; + if (valueDeclaration && (valueDeclaration.kind === 173 /* FunctionExpression */ || valueDeclaration.kind === 186 /* ClassExpression */)) { + return valueDeclaration; + } + // If this is private property or method, the scope is the containing class + if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { + var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 32 /* Private */) ? d : undefined; }); + if (privateDeclaration) { + return ts.getAncestor(privateDeclaration, 214 /* ClassDeclaration */); + } + } + // If the symbol is an import we would like to find it if we are looking for what it imports. + // So consider it visibile outside its declaration scope. + if (symbol.flags & 8388608 /* Alias */) { + return undefined; + } + // if this symbol is visible from its parent container, e.g. exported, then bail out + // if symbol correspond to the union property - bail out + if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) { + return undefined; + } + var scope = undefined; + var declarations = symbol.getDeclarations(); + if (declarations) { + for (var _i = 0; _i < declarations.length; _i++) { + var declaration = declarations[_i]; + var container = getContainerNode(declaration); + if (!container) { + return undefined; + } + if (scope && scope !== container) { + // Different declarations have different containers, bail out + return undefined; + } + if (container.kind === 248 /* SourceFile */ && !ts.isExternalModule(container)) { + // This is a global variable and not an external module, any declaration defined + // within this scope is visible outside the file + return undefined; + } + // The search scope is the container node + scope = container; + } + } + return scope; + } + function getPossibleSymbolReferencePositions(sourceFile, symbolName, start, end) { + var positions = []; + /// TODO: Cache symbol existence for files to save text search + // Also, need to make this work for unicode escapes. + // Be resilient in the face of a symbol with no name or zero length name + if (!symbolName || !symbolName.length) { + return positions; + } + var text = sourceFile.text; + var sourceLength = text.length; + var symbolNameLength = symbolName.length; + var position = text.indexOf(symbolName, start); + while (position >= 0) { + cancellationToken.throwIfCancellationRequested(); + // If we are past the end, stop looking + if (position > end) + break; + // We found a match. Make sure it's not part of a larger word (i.e. the char + // before and after it have to be a non-identifier char). + var endPosition = position + symbolNameLength; + if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 2 /* Latest */)) && + (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 2 /* Latest */))) { + // Found a real match. Keep searching. + positions.push(position); + } + position = text.indexOf(symbolName, position + symbolNameLength + 1); + } + return positions; + } + function getLabelReferencesInNode(container, targetLabel) { + var references = []; + var sourceFile = container.getSourceFile(); + var labelName = targetLabel.text; + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container.getStart(), container.getEnd()); + ts.forEach(possiblePositions, function (position) { + cancellationToken.throwIfCancellationRequested(); + var node = ts.getTouchingWord(sourceFile, position); + if (!node || node.getWidth() !== labelName.length) { + return; + } + // Only pick labels that are either the target label, or have a target that is the target label + if (node === targetLabel || + (isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel)) { + references.push(getReferenceEntryFromNode(node)); + } + }); + var definition = { + containerKind: "", + containerName: "", + fileName: targetLabel.getSourceFile().fileName, + kind: ScriptElementKind.label, + name: labelName, + textSpan: ts.createTextSpanFromBounds(targetLabel.getStart(), targetLabel.getEnd()) + }; + return [{ definition: definition, references: references }]; + } + function isValidReferencePosition(node, searchSymbolName) { + if (node) { + // Compare the length so we filter out strict superstrings of the symbol we are looking for + switch (node.kind) { + case 69 /* Identifier */: + return node.getWidth() === searchSymbolName.length; + case 9 /* StringLiteral */: + if (isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || + isNameOfExternalModuleImportOrDeclaration(node)) { + // For string literals we have two additional chars for the quotes + return node.getWidth() === searchSymbolName.length + 2; + } + break; + case 8 /* NumericLiteral */: + if (isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { + return node.getWidth() === searchSymbolName.length; + } + break; + } + } + return false; + } + /** Search within node "container" for references for a search value, where the search value is defined as a + * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). + * searchLocation: a node where the search value + */ + function getReferencesInNode(container, searchSymbol, searchText, searchLocation, searchMeaning, findInStrings, findInComments, result, symbolToIndex) { + var sourceFile = container.getSourceFile(); + var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*= 0) { + var referencedSymbol = getReferencedSymbol(shorthandValueSymbol); + referencedSymbol.references.push(getReferenceEntryFromNode(referenceSymbolDeclaration.name)); + } + } + }); + } + return; + function getReferencedSymbol(symbol) { + var symbolId = ts.getSymbolId(symbol); + var index = symbolToIndex[symbolId]; + if (index === undefined) { + index = result.length; + symbolToIndex[symbolId] = index; + result.push({ + definition: getDefinition(symbol), + references: [] + }); + } + return result[index]; + } + function isInNonReferenceComment(sourceFile, position) { + return ts.isInCommentHelper(sourceFile, position, isNonReferenceComment); + function isNonReferenceComment(c) { + var commentText = sourceFile.text.substring(c.pos, c.end); + return !tripleSlashDirectivePrefixRegex.test(commentText); + } + } + } + function getReferencesForSuperKeyword(superKeyword) { + var searchSpaceNode = ts.getSuperContainer(superKeyword, /*includeFunctions*/ false); + if (!searchSpaceNode) { + return undefined; + } + // Whether 'super' occurs in a static context within a class. + var staticFlag = 128 /* Static */; + switch (searchSpaceNode.kind) { + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 144 /* Constructor */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + staticFlag &= searchSpaceNode.flags; + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class + break; + default: + return undefined; + } + var references = []; + var sourceFile = searchSpaceNode.getSourceFile(); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + ts.forEach(possiblePositions, function (position) { + cancellationToken.throwIfCancellationRequested(); + var node = ts.getTouchingWord(sourceFile, position); + if (!node || node.kind !== 95 /* SuperKeyword */) { + return; + } + var container = ts.getSuperContainer(node, /*includeFunctions*/ false); + // If we have a 'super' container, we must have an enclosing class. + // Now make sure the owning class is the same as the search-space + // and has the same static qualifier as the original 'super's owner. + if (container && (128 /* Static */ & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { + references.push(getReferenceEntryFromNode(node)); + } + }); + var definition = getDefinition(searchSpaceNode.symbol); + return [{ definition: definition, references: references }]; + } + function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles) { + var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); + // Whether 'this' occurs in a static context within a class. + var staticFlag = 128 /* Static */; + switch (searchSpaceNode.kind) { + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + if (ts.isObjectLiteralMethod(searchSpaceNode)) { + break; + } + // fall through + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 144 /* Constructor */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + staticFlag &= searchSpaceNode.flags; + searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class + break; + case 248 /* SourceFile */: + if (ts.isExternalModule(searchSpaceNode)) { + return undefined; + } + // Fall through + case 213 /* FunctionDeclaration */: + case 173 /* FunctionExpression */: + break; + // Computed properties in classes are not handled here because references to this are illegal, + // so there is no point finding references to them. + default: + return undefined; + } + var references = []; + var possiblePositions; + if (searchSpaceNode.kind === 248 /* SourceFile */) { + ts.forEach(sourceFiles, function (sourceFile) { + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); + getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); + }); + } + else { + var sourceFile = searchSpaceNode.getSourceFile(); + possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", searchSpaceNode.getStart(), searchSpaceNode.getEnd()); + getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, references); + } + return [{ + definition: { + containerKind: "", + containerName: "", + fileName: node.getSourceFile().fileName, + kind: ScriptElementKind.variableElement, + name: "this", + textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()) + }, + references: references + }]; + function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { + ts.forEach(possiblePositions, function (position) { + cancellationToken.throwIfCancellationRequested(); + var node = ts.getTouchingWord(sourceFile, position); + if (!node || node.kind !== 97 /* ThisKeyword */) { + return; + } + var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); + switch (searchSpaceNode.kind) { + case 173 /* FunctionExpression */: + case 213 /* FunctionDeclaration */: + if (searchSpaceNode.symbol === container.symbol) { + result.push(getReferenceEntryFromNode(node)); + } + break; + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { + result.push(getReferenceEntryFromNode(node)); + } + break; + case 186 /* ClassExpression */: + case 214 /* ClassDeclaration */: + // Make sure the container belongs to the same class + // and has the appropriate static modifier from the original container. + if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 128 /* Static */) === staticFlag) { + result.push(getReferenceEntryFromNode(node)); + } + break; + case 248 /* SourceFile */: + if (container.kind === 248 /* SourceFile */ && !ts.isExternalModule(container)) { + result.push(getReferenceEntryFromNode(node)); + } + break; + } + }); + } + } + function populateSearchSymbolSet(symbol, location) { + // The search set contains at least the current symbol + var result = [symbol]; + // If the symbol is an alias, add what it alaises to the list + if (isImportOrExportSpecifierImportSymbol(symbol)) { + result.push(typeChecker.getAliasedSymbol(symbol)); + } + // If the location is in a context sensitive location (i.e. in an object literal) try + // to get a contextual type for it, and add the property symbol from the contextual + // type to the search set + if (isNameOfPropertyAssignment(location)) { + ts.forEach(getPropertySymbolsFromContextualType(location), function (contextualSymbol) { + ts.addRange(result, typeChecker.getRootSymbols(contextualSymbol)); + }); + /* Because in short-hand property assignment, location has two meaning : property name and as value of the property + * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of + * property name and variable declaration of the identifier. + * Like in below example, when querying for all references for an identifier 'name', of the property assignment, the language service + * should show both 'name' in 'obj' and 'name' in variable declaration + * let name = "Foo"; + * let obj = { name }; + * In order to do that, we will populate the search set with the value symbol of the identifier as a value of the property assignment + * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration + * will be included correctly. + */ + var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(location.parent); + if (shorthandValueSymbol) { + result.push(shorthandValueSymbol); + } + } + // If this is a union property, add all the symbols from all its source symbols in all unioned types. + // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list + ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { + if (rootSymbol !== symbol) { + result.push(rootSymbol); + } + // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions + if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result); + } + }); + return result; + } + function getPropertySymbolsFromBaseTypes(symbol, propertyName, result) { + if (symbol && symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + ts.forEach(symbol.getDeclarations(), function (declaration) { + if (declaration.kind === 214 /* ClassDeclaration */) { + getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); + ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); + } + else if (declaration.kind === 215 /* InterfaceDeclaration */) { + ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); + } + }); + } + return; + function getPropertySymbolFromTypeReference(typeReference) { + if (typeReference) { + var type = typeChecker.getTypeAtLocation(typeReference); + if (type) { + var propertySymbol = typeChecker.getPropertyOfType(type, propertyName); + if (propertySymbol) { + result.push(propertySymbol); + } + // Visit the typeReference as well to see if it directly or indirectly use that property + getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result); + } + } + } + } + function getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation) { + if (searchSymbols.indexOf(referenceSymbol) >= 0) { + return referenceSymbol; + } + // If the reference symbol is an alias, check if what it is aliasing is one of the search + // symbols. + if (isImportOrExportSpecifierImportSymbol(referenceSymbol)) { + var aliasedSymbol = typeChecker.getAliasedSymbol(referenceSymbol); + if (searchSymbols.indexOf(aliasedSymbol) >= 0) { + return aliasedSymbol; + } + } + // If the reference location is in an object literal, try to get the contextual type for the + // object literal, lookup the property symbol in the contextual type, and use this symbol to + // compare to our searchSymbol + if (isNameOfPropertyAssignment(referenceLocation)) { + return ts.forEach(getPropertySymbolsFromContextualType(referenceLocation), function (contextualSymbol) { + return ts.forEach(typeChecker.getRootSymbols(contextualSymbol), function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); + }); + } + // Unwrap symbols to get to the root (e.g. transient symbols as a result of widening) + // Or a union property, use its underlying unioned symbols + return ts.forEach(typeChecker.getRootSymbols(referenceSymbol), function (rootSymbol) { + // if it is in the list, then we are done + if (searchSymbols.indexOf(rootSymbol) >= 0) { + return rootSymbol; + } + // Finally, try all properties with the same name in any type the containing type extended or implemented, and + // see if any is in the list + if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { + var result_3 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_3); + return ts.forEach(result_3, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); + } + return undefined; + }); + } + function getPropertySymbolsFromContextualType(node) { + if (isNameOfPropertyAssignment(node)) { + var objectLiteral = node.parent.parent; + var contextualType = typeChecker.getContextualType(objectLiteral); + var name_34 = node.text; + if (contextualType) { + if (contextualType.flags & 16384 /* Union */) { + // This is a union type, first see if the property we are looking for is a union property (i.e. exists in all types) + // if not, search the constituent types for the property + var unionProperty = contextualType.getProperty(name_34); + if (unionProperty) { + return [unionProperty]; + } + else { + var result_4 = []; + ts.forEach(contextualType.types, function (t) { + var symbol = t.getProperty(name_34); + if (symbol) { + result_4.push(symbol); + } + }); + return result_4; + } + } + else { + var symbol_1 = contextualType.getProperty(name_34); + if (symbol_1) { + return [symbol_1]; + } + } + } + } + return undefined; + } + /** Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations + * of the corresponding symbol. e.g. if we are searching for "Foo" in value position, but "Foo" references a class + * then we need to widen the search to include type positions as well. + * On the contrary, if we are searching for "Bar" in type position and we trace bar to an interface, and an uninstantiated + * module, we want to keep the search limited to only types, as the two declarations (interface and uninstantiated module) + * do not intersect in any of the three spaces. + */ + function getIntersectingMeaningFromDeclarations(meaning, declarations) { + if (declarations) { + var lastIterationMeaning; + do { + // The result is order-sensitive, for instance if initialMeaning === Namespace, and declarations = [class, instantiated module] + // we need to consider both as they initialMeaning intersects with the module in the namespace space, and the module + // intersects with the class in the value space. + // To achieve that we will keep iterating until the result stabilizes. + // Remember the last meaning + lastIterationMeaning = meaning; + for (var _i = 0; _i < declarations.length; _i++) { + var declaration = declarations[_i]; + var declarationMeaning = getMeaningFromDeclaration(declaration); + if (declarationMeaning & meaning) { + meaning |= declarationMeaning; + } + } + } while (meaning !== lastIterationMeaning); + } + return meaning; + } + } + function getReferenceEntryFromNode(node) { + var start = node.getStart(); + var end = node.getEnd(); + if (node.kind === 9 /* StringLiteral */) { + start += 1; + end -= 1; + } + return { + fileName: node.getSourceFile().fileName, + textSpan: ts.createTextSpanFromBounds(start, end), + isWriteAccess: isWriteAccess(node) + }; + } + /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ + function isWriteAccess(node) { + if (node.kind === 69 /* Identifier */ && ts.isDeclarationName(node)) { + return true; + } + var parent = node.parent; + if (parent) { + if (parent.kind === 180 /* PostfixUnaryExpression */ || parent.kind === 179 /* PrefixUnaryExpression */) { + return true; + } + else if (parent.kind === 181 /* BinaryExpression */ && parent.left === node) { + var operator = parent.operatorToken.kind; + return 56 /* FirstAssignment */ <= operator && operator <= 68 /* LastAssignment */; + } + } + return false; + } + /// NavigateTo + function getNavigateToItems(searchValue, maxResultCount) { + synchronizeHostData(); + return ts.NavigateTo.getNavigateToItems(program, cancellationToken, searchValue, maxResultCount); + } + function containErrors(diagnostics) { + return ts.forEach(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); + } + function getEmitOutput(fileName) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var outputFiles = []; + function writeFile(fileName, data, writeByteOrderMark) { + outputFiles.push({ + name: fileName, + writeByteOrderMark: writeByteOrderMark, + text: data + }); + } + var emitOutput = program.emit(sourceFile, writeFile, cancellationToken); + return { + outputFiles: outputFiles, + emitSkipped: emitOutput.emitSkipped + }; + } + function getMeaningFromDeclaration(node) { + switch (node.kind) { + case 138 /* Parameter */: + case 211 /* VariableDeclaration */: + case 163 /* BindingElement */: + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + case 245 /* PropertyAssignment */: + case 246 /* ShorthandPropertyAssignment */: + case 247 /* EnumMember */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 144 /* Constructor */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 213 /* FunctionDeclaration */: + case 173 /* FunctionExpression */: + case 174 /* ArrowFunction */: + case 244 /* CatchClause */: + return 1 /* Value */; + case 137 /* TypeParameter */: + case 215 /* InterfaceDeclaration */: + case 216 /* TypeAliasDeclaration */: + case 155 /* TypeLiteral */: + return 2 /* Type */; + case 214 /* ClassDeclaration */: + case 217 /* EnumDeclaration */: + return 1 /* Value */ | 2 /* Type */; + case 218 /* ModuleDeclaration */: + if (node.name.kind === 9 /* StringLiteral */) { + return 4 /* Namespace */ | 1 /* Value */; + } + else if (ts.getModuleInstanceState(node) === 1 /* Instantiated */) { + return 4 /* Namespace */ | 1 /* Value */; + } + else { + return 4 /* Namespace */; + } + case 225 /* NamedImports */: + case 226 /* ImportSpecifier */: + case 221 /* ImportEqualsDeclaration */: + case 222 /* ImportDeclaration */: + case 227 /* ExportAssignment */: + case 228 /* ExportDeclaration */: + return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + // An external module can be a Value + case 248 /* SourceFile */: + return 4 /* Namespace */ | 1 /* Value */; + } + return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + ts.Debug.fail("Unknown declaration type"); + } + function isTypeReference(node) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + return node.parent.kind === 151 /* TypeReference */ || + (node.parent.kind === 188 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || + node.kind === 97 /* ThisKeyword */ && !ts.isExpression(node); + } + function isNamespaceReference(node) { + return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); + } + function isPropertyAccessNamespaceReference(node) { + var root = node; + var isLastClause = true; + if (root.parent.kind === 166 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 166 /* PropertyAccessExpression */) { + root = root.parent; + } + isLastClause = root.name === node; + } + if (!isLastClause && root.parent.kind === 188 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 243 /* HeritageClause */) { + var decl = root.parent.parent.parent; + return (decl.kind === 214 /* ClassDeclaration */ && root.parent.parent.token === 106 /* ImplementsKeyword */) || + (decl.kind === 215 /* InterfaceDeclaration */ && root.parent.parent.token === 83 /* ExtendsKeyword */); + } + return false; + } + function isQualifiedNameNamespaceReference(node) { + var root = node; + var isLastClause = true; + if (root.parent.kind === 135 /* QualifiedName */) { + while (root.parent && root.parent.kind === 135 /* QualifiedName */) { + root = root.parent; + } + isLastClause = root.right === node; + } + return root.parent.kind === 151 /* TypeReference */ && !isLastClause; + } + function isInRightSideOfImport(node) { + while (node.parent.kind === 135 /* QualifiedName */) { + node = node.parent; + } + return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; + } + function getMeaningFromRightHandSideOfImportEquals(node) { + ts.Debug.assert(node.kind === 69 /* Identifier */); + // import a = |b|; // Namespace + // import a = |b.c|; // Value, type, namespace + // import a = |b.c|.d; // Namespace + if (node.parent.kind === 135 /* QualifiedName */ && + node.parent.right === node && + node.parent.parent.kind === 221 /* ImportEqualsDeclaration */) { + return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + } + return 4 /* Namespace */; + } + function getMeaningFromLocation(node) { + if (node.parent.kind === 227 /* ExportAssignment */) { + return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + } + else if (isInRightSideOfImport(node)) { + return getMeaningFromRightHandSideOfImportEquals(node); + } + else if (ts.isDeclarationName(node)) { + return getMeaningFromDeclaration(node.parent); + } + else if (isTypeReference(node)) { + return 2 /* Type */; + } + else if (isNamespaceReference(node)) { + return 4 /* Namespace */; + } + else { + return 1 /* Value */; + } + } + // Signature help + /** + * This is a semantic operation. + */ + function getSignatureHelpItems(fileName, position) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, cancellationToken); + } + /// Syntactic features + function getSourceFile(fileName) { + return syntaxTreeCache.getCurrentSourceFile(fileName); + } + function getNameOrDottedNameSpan(fileName, startPos, endPos) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + // Get node at the location + var node = ts.getTouchingPropertyName(sourceFile, startPos); + if (!node) { + return; + } + switch (node.kind) { + case 166 /* PropertyAccessExpression */: + case 135 /* QualifiedName */: + case 9 /* StringLiteral */: + case 84 /* FalseKeyword */: + case 99 /* TrueKeyword */: + case 93 /* NullKeyword */: + case 95 /* SuperKeyword */: + case 97 /* ThisKeyword */: + case 69 /* Identifier */: + break; + // Cant create the text span + default: + return; + } + var nodeForStartPos = node; + while (true) { + if (isRightSideOfPropertyAccess(nodeForStartPos) || isRightSideOfQualifiedName(nodeForStartPos)) { + // If on the span is in right side of the the property or qualified name, return the span from the qualified name pos to end of this node + nodeForStartPos = nodeForStartPos.parent; + } + else if (isNameOfModuleDeclaration(nodeForStartPos)) { + // If this is name of a module declarations, check if this is right side of dotted module name + // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of + // Then this name is name from dotted module + if (nodeForStartPos.parent.parent.kind === 218 /* ModuleDeclaration */ && + nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { + // Use parent module declarations name for start pos + nodeForStartPos = nodeForStartPos.parent.parent.name; + } + else { + // We have to use this name for start pos + break; + } + } + else { + // Is not a member expression so we have found the node for start pos + break; + } + } + return ts.createTextSpanFromBounds(nodeForStartPos.getStart(), node.getEnd()); + } + function getBreakpointStatementAtPosition(fileName, position) { + // doesn't use compiler - no need to synchronize with host + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); + } + function getNavigationBarItems(fileName) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts.NavigationBar.getNavigationBarItems(sourceFile); + } + function getSemanticClassifications(fileName, span) { + return convertClassifications(getEncodedSemanticClassifications(fileName, span)); + } + function checkForClassificationCancellation(kind) { + // We don't want to actually call back into our host on every node to find out if we've + // been canceled. That would be an enormous amount of chattyness, along with the all + // the overhead of marshalling the data to/from the host. So instead we pick a few + // reasonable node kinds to bother checking on. These node kinds represent high level + // constructs that we would expect to see commonly, but just at a far less frequent + // interval. + // + // For example, in checker.ts (around 750k) we only have around 600 of these constructs. + // That means we're calling back into the host around every 1.2k of the file we process. + // Lib.d.ts has similar numbers. + switch (kind) { + case 218 /* ModuleDeclaration */: + case 214 /* ClassDeclaration */: + case 215 /* InterfaceDeclaration */: + case 213 /* FunctionDeclaration */: + cancellationToken.throwIfCancellationRequested(); + } + } + function getEncodedSemanticClassifications(fileName, span) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var typeChecker = program.getTypeChecker(); + var result = []; + var classifiableNames = program.getClassifiableNames(); + processNode(sourceFile); + return { spans: result, endOfLineState: 0 /* None */ }; + function pushClassification(start, length, type) { + result.push(start); + result.push(length); + result.push(type); + } + function classifySymbol(symbol, meaningAtPosition) { + var flags = symbol.getFlags(); + if ((flags & 788448 /* Classifiable */) === 0 /* None */) { + return; + } + if (flags & 32 /* Class */) { + return 11 /* className */; + } + else if (flags & 384 /* Enum */) { + return 12 /* enumName */; + } + else if (flags & 524288 /* TypeAlias */) { + return 16 /* typeAliasName */; + } + else if (meaningAtPosition & 2 /* Type */) { + if (flags & 64 /* Interface */) { + return 13 /* interfaceName */; + } + else if (flags & 262144 /* TypeParameter */) { + return 15 /* typeParameterName */; + } + } + else if (flags & 1536 /* Module */) { + // Only classify a module as such if + // - It appears in a namespace context. + // - There exists a module declaration which actually impacts the value side. + if (meaningAtPosition & 4 /* Namespace */ || + (meaningAtPosition & 1 /* Value */ && hasValueSideModule(symbol))) { + return 14 /* moduleName */; + } + } + return undefined; + /** + * Returns true if there exists a module that introduces entities on the value side. + */ + function hasValueSideModule(symbol) { + return ts.forEach(symbol.declarations, function (declaration) { + return declaration.kind === 218 /* ModuleDeclaration */ && + ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; + }); + } + } + function processNode(node) { + // Only walk into nodes that intersect the requested span. + if (node && ts.textSpanIntersectsWith(span, node.getFullStart(), node.getFullWidth())) { + var kind = node.kind; + checkForClassificationCancellation(kind); + if (kind === 69 /* Identifier */ && !ts.nodeIsMissing(node)) { + var identifier = node; + // Only bother calling into the typechecker if this is an identifier that + // could possibly resolve to a type name. This makes classification run + // in a third of the time it would normally take. + if (classifiableNames[identifier.text]) { + var symbol = typeChecker.getSymbolAtLocation(node); + if (symbol) { + var type = classifySymbol(symbol, getMeaningFromLocation(node)); + if (type) { + pushClassification(node.getStart(), node.getWidth(), type); + } + } + } + } + ts.forEachChild(node, processNode); + } + } + } + function getClassificationTypeName(type) { + switch (type) { + case 1 /* comment */: return ClassificationTypeNames.comment; + case 2 /* identifier */: return ClassificationTypeNames.identifier; + case 3 /* keyword */: return ClassificationTypeNames.keyword; + case 4 /* numericLiteral */: return ClassificationTypeNames.numericLiteral; + case 5 /* operator */: return ClassificationTypeNames.operator; + case 6 /* stringLiteral */: return ClassificationTypeNames.stringLiteral; + case 8 /* whiteSpace */: return ClassificationTypeNames.whiteSpace; + case 9 /* text */: return ClassificationTypeNames.text; + case 10 /* punctuation */: return ClassificationTypeNames.punctuation; + case 11 /* className */: return ClassificationTypeNames.className; + case 12 /* enumName */: return ClassificationTypeNames.enumName; + case 13 /* interfaceName */: return ClassificationTypeNames.interfaceName; + case 14 /* moduleName */: return ClassificationTypeNames.moduleName; + case 15 /* typeParameterName */: return ClassificationTypeNames.typeParameterName; + case 16 /* typeAliasName */: return ClassificationTypeNames.typeAliasName; + case 17 /* parameterName */: return ClassificationTypeNames.parameterName; + case 18 /* docCommentTagName */: return ClassificationTypeNames.docCommentTagName; + } + } + function convertClassifications(classifications) { + ts.Debug.assert(classifications.spans.length % 3 === 0); + var dense = classifications.spans; + var result = []; + for (var i = 0, n = dense.length; i < n; i += 3) { + result.push({ + textSpan: ts.createTextSpan(dense[i], dense[i + 1]), + classificationType: getClassificationTypeName(dense[i + 2]) + }); + } + return result; + } + function getSyntacticClassifications(fileName, span) { + return convertClassifications(getEncodedSyntacticClassifications(fileName, span)); + } + function getEncodedSyntacticClassifications(fileName, span) { + // doesn't use compiler - no need to synchronize with host + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var spanStart = span.start; + var spanLength = span.length; + // Make a scanner we can get trivia from. + var triviaScanner = ts.createScanner(2 /* Latest */, /*skipTrivia:*/ false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(2 /* Latest */, /*skipTrivia:*/ false, sourceFile.languageVariant, sourceFile.text); + var result = []; + processElement(sourceFile); + return { spans: result, endOfLineState: 0 /* None */ }; + function pushClassification(start, length, type) { + result.push(start); + result.push(length); + result.push(type); + } + function classifyLeadingTriviaAndGetTokenStart(token) { + triviaScanner.setTextPos(token.pos); + while (true) { + var start = triviaScanner.getTextPos(); + // only bother scanning if we have something that could be trivia. + if (!ts.couldStartTrivia(sourceFile.text, start)) { + return start; + } + var kind = triviaScanner.scan(); + var end = triviaScanner.getTextPos(); + var width = end - start; + // The moment we get something that isn't trivia, then stop processing. + if (!ts.isTrivia(kind)) { + return start; + } + // Don't bother with newlines/whitespace. + if (kind === 4 /* NewLineTrivia */ || kind === 5 /* WhitespaceTrivia */) { + continue; + } + // Only bother with the trivia if it at least intersects the span of interest. + if (ts.isComment(kind)) { + classifyComment(token, kind, start, width); + // Classifying a comment might cause us to reuse the trivia scanner + // (because of jsdoc comments). So after we classify the comment make + // sure we set the scanner position back to where it needs to be. + triviaScanner.setTextPos(end); + continue; + } + if (kind === 7 /* ConflictMarkerTrivia */) { + var text = sourceFile.text; + var ch = text.charCodeAt(start); + // for the <<<<<<< and >>>>>>> markers, we just add them in as comments + // in the classification stream. + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + pushClassification(start, width, 1 /* comment */); + continue; + } + // for the ======== add a comment for the first line, and then lex all + // subsequent lines up until the end of the conflict marker. + ts.Debug.assert(ch === 61 /* equals */); + classifyDisabledMergeCode(text, start, end); + } + } + } + function classifyComment(token, kind, start, width) { + if (kind === 3 /* MultiLineCommentTrivia */) { + // See if this is a doc comment. If so, we'll classify certain portions of it + // specially. + var docCommentAndDiagnostics = ts.parseIsolatedJSDocComment(sourceFile.text, start, width); + if (docCommentAndDiagnostics && docCommentAndDiagnostics.jsDocComment) { + docCommentAndDiagnostics.jsDocComment.parent = token; + classifyJSDocComment(docCommentAndDiagnostics.jsDocComment); + return; + } + } + // Simple comment. Just add as is. + pushCommentRange(start, width); + } + function pushCommentRange(start, width) { + pushClassification(start, width, 1 /* comment */); + } + function classifyJSDocComment(docComment) { + var pos = docComment.pos; + for (var _i = 0, _a = docComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + // As we walk through each tag, classify the portion of text from the end of + // the last tag (or the start of the entire doc comment) as 'comment'. + if (tag.pos !== pos) { + pushCommentRange(pos, tag.pos - pos); + } + pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10 /* punctuation */); + pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); + pos = tag.tagName.end; + switch (tag.kind) { + case 267 /* JSDocParameterTag */: + processJSDocParameterTag(tag); + break; + case 270 /* JSDocTemplateTag */: + processJSDocTemplateTag(tag); + break; + case 269 /* JSDocTypeTag */: + processElement(tag.typeExpression); + break; + case 268 /* JSDocReturnTag */: + processElement(tag.typeExpression); + break; + } + pos = tag.end; + } + if (pos !== docComment.end) { + pushCommentRange(pos, docComment.end - pos); + } + return; + function processJSDocParameterTag(tag) { + if (tag.preParameterName) { + pushCommentRange(pos, tag.preParameterName.pos - pos); + pushClassification(tag.preParameterName.pos, tag.preParameterName.end - tag.preParameterName.pos, 17 /* parameterName */); + pos = tag.preParameterName.end; + } + if (tag.typeExpression) { + pushCommentRange(pos, tag.typeExpression.pos - pos); + processElement(tag.typeExpression); + pos = tag.typeExpression.end; + } + if (tag.postParameterName) { + pushCommentRange(pos, tag.postParameterName.pos - pos); + pushClassification(tag.postParameterName.pos, tag.postParameterName.end - tag.postParameterName.pos, 17 /* parameterName */); + pos = tag.postParameterName.end; + } + } + } + function processJSDocTemplateTag(tag) { + for (var _i = 0, _a = tag.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + processElement(child); + } + } + function classifyDisabledMergeCode(text, start, end) { + // Classify the line that the ======= marker is on as a comment. Then just lex + // all further tokens and add them to the result. + for (var i = start; i < end; i++) { + if (ts.isLineBreak(text.charCodeAt(i))) { + break; + } + } + pushClassification(start, i - start, 1 /* comment */); + mergeConflictScanner.setTextPos(i); + while (mergeConflictScanner.getTextPos() < end) { + classifyDisabledCodeToken(); + } + } + function classifyDisabledCodeToken() { + var start = mergeConflictScanner.getTextPos(); + var tokenKind = mergeConflictScanner.scan(); + var end = mergeConflictScanner.getTextPos(); + var type = classifyTokenType(tokenKind); + if (type) { + pushClassification(start, end - start, type); + } + } + function classifyToken(token) { + if (ts.nodeIsMissing(token)) { + return; + } + var tokenStart = classifyLeadingTriviaAndGetTokenStart(token); + var tokenWidth = token.end - tokenStart; + ts.Debug.assert(tokenWidth >= 0); + if (tokenWidth > 0) { + var type = classifyTokenType(token.kind, token); + if (type) { + pushClassification(tokenStart, tokenWidth, type); + } + } + } + // for accurate classification, the actual token should be passed in. however, for + // cases like 'disabled merge code' classification, we just get the token kind and + // classify based on that instead. + function classifyTokenType(tokenKind, token) { + if (ts.isKeyword(tokenKind)) { + return 3 /* keyword */; + } + // Special case < and > If they appear in a generic context they are punctuation, + // not operators. + if (tokenKind === 25 /* LessThanToken */ || tokenKind === 27 /* GreaterThanToken */) { + // If the node owning the token has a type argument list or type parameter list, then + // we can effectively assume that a '<' and '>' belong to those lists. + if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { + return 10 /* punctuation */; + } + } + if (ts.isPunctuation(tokenKind)) { + if (token) { + if (tokenKind === 56 /* EqualsToken */) { + // the '=' in a variable declaration is special cased here. + if (token.parent.kind === 211 /* VariableDeclaration */ || + token.parent.kind === 141 /* PropertyDeclaration */ || + token.parent.kind === 138 /* Parameter */) { + return 5 /* operator */; + } + } + if (token.parent.kind === 181 /* BinaryExpression */ || + token.parent.kind === 179 /* PrefixUnaryExpression */ || + token.parent.kind === 180 /* PostfixUnaryExpression */ || + token.parent.kind === 182 /* ConditionalExpression */) { + return 5 /* operator */; + } + } + return 10 /* punctuation */; + } + else if (tokenKind === 8 /* NumericLiteral */) { + return 4 /* numericLiteral */; + } + else if (tokenKind === 9 /* StringLiteral */) { + return 6 /* stringLiteral */; + } + else if (tokenKind === 10 /* RegularExpressionLiteral */) { + // TODO: we should get another classification type for these literals. + return 6 /* stringLiteral */; + } + else if (ts.isTemplateLiteralKind(tokenKind)) { + // TODO (drosen): we should *also* get another classification type for these literals. + return 6 /* stringLiteral */; + } + else if (tokenKind === 69 /* Identifier */) { + if (token) { + switch (token.parent.kind) { + case 214 /* ClassDeclaration */: + if (token.parent.name === token) { + return 11 /* className */; + } + return; + case 137 /* TypeParameter */: + if (token.parent.name === token) { + return 15 /* typeParameterName */; + } + return; + case 215 /* InterfaceDeclaration */: + if (token.parent.name === token) { + return 13 /* interfaceName */; + } + return; + case 217 /* EnumDeclaration */: + if (token.parent.name === token) { + return 12 /* enumName */; + } + return; + case 218 /* ModuleDeclaration */: + if (token.parent.name === token) { + return 14 /* moduleName */; + } + return; + case 138 /* Parameter */: + if (token.parent.name === token) { + return 17 /* parameterName */; + } + return; + } + } + return 2 /* identifier */; + } + } + function processElement(element) { + if (!element) { + return; + } + // Ignore nodes that don't intersect the original span to classify. + if (ts.decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) { + checkForClassificationCancellation(element.kind); + var children = element.getChildren(sourceFile); + for (var i = 0, n = children.length; i < n; i++) { + var child = children[i]; + if (ts.isToken(child)) { + classifyToken(child); + } + else { + // Recurse into our child nodes. + processElement(child); + } + } + } + } + } + function getOutliningSpans(fileName) { + // doesn't use compiler - no need to synchronize with host + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts.OutliningElementsCollector.collectElements(sourceFile); + } + function getBraceMatchingAtPosition(fileName, position) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var result = []; + var token = ts.getTouchingToken(sourceFile, position); + if (token.getStart(sourceFile) === position) { + var matchKind = getMatchingTokenKind(token); + // Ensure that there is a corresponding token to match ours. + if (matchKind) { + var parentElement = token.parent; + var childNodes = parentElement.getChildren(sourceFile); + for (var _i = 0; _i < childNodes.length; _i++) { + var current = childNodes[_i]; + if (current.kind === matchKind) { + var range1 = ts.createTextSpan(token.getStart(sourceFile), token.getWidth(sourceFile)); + var range2 = ts.createTextSpan(current.getStart(sourceFile), current.getWidth(sourceFile)); + // We want to order the braces when we return the result. + if (range1.start < range2.start) { + result.push(range1, range2); + } + else { + result.push(range2, range1); + } + break; + } + } + } + } + return result; + function getMatchingTokenKind(token) { + switch (token.kind) { + case 15 /* OpenBraceToken */: return 16 /* CloseBraceToken */; + case 17 /* OpenParenToken */: return 18 /* CloseParenToken */; + case 19 /* OpenBracketToken */: return 20 /* CloseBracketToken */; + case 25 /* LessThanToken */: return 27 /* GreaterThanToken */; + case 16 /* CloseBraceToken */: return 15 /* OpenBraceToken */; + case 18 /* CloseParenToken */: return 17 /* OpenParenToken */; + case 20 /* CloseBracketToken */: return 19 /* OpenBracketToken */; + case 27 /* GreaterThanToken */: return 25 /* LessThanToken */; + } + return undefined; + } + } + function getIndentationAtPosition(fileName, position, editorOptions) { + var start = new Date().getTime(); + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + log("getIndentationAtPosition: getCurrentSourceFile: " + (new Date().getTime() - start)); + start = new Date().getTime(); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); + log("getIndentationAtPosition: computeIndentation : " + (new Date().getTime() - start)); + return result; + } + function getFormattingEditsForRange(fileName, start, end, options) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options); + } + function getFormattingEditsForDocument(fileName, options) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options); + } + function getFormattingEditsAfterKeystroke(fileName, position, key, options) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + if (key === "}") { + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options); + } + else if (key === ";") { + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options); + } + else if (key === "\n") { + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options); + } + return []; + } + /** + * Checks if position points to a valid position to add JSDoc comments, and if so, + * returns the appropriate template. Otherwise returns an empty string. + * Valid positions are + * - outside of comments, statements, and expressions, and + * - preceding a: + * - function/constructor/method declaration + * - class declarations + * - variable statements + * - namespace declarations + * + * Hosts should ideally check that: + * - The line is all whitespace up to 'position' before performing the insertion. + * - If the keystroke sequence "/\*\*" induced the call, we also check that the next + * non-whitespace character is '*', which (approximately) indicates whether we added + * the second '*' to complete an existing (JSDoc) comment. + * @param fileName The file in which to perform the check. + * @param position The (character-indexed) position in the file where the check should + * be performed. + */ + function getDocCommentTemplateAtPosition(fileName, position) { + var start = new Date().getTime(); + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + // Check if in a context where we don't want to perform any insertion + if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { + return undefined; + } + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var tokenStart = tokenAtPos.getStart(); + if (!tokenAtPos || tokenStart < position) { + return undefined; + } + // TODO: add support for: + // - enums/enum members + // - interfaces + // - property declarations + // - potentially property assignments + var commentOwner; + findOwner: for (commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { + switch (commentOwner.kind) { + case 213 /* FunctionDeclaration */: + case 143 /* MethodDeclaration */: + case 144 /* Constructor */: + case 214 /* ClassDeclaration */: + case 193 /* VariableStatement */: + break findOwner; + case 248 /* SourceFile */: + return undefined; + case 218 /* ModuleDeclaration */: + // If in walking up the tree, we hit a a nested namespace declaration, + // then we must be somewhere within a dotted namespace name; however we don't + // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. + if (commentOwner.parent.kind === 218 /* ModuleDeclaration */) { + return undefined; + } + break findOwner; + } + } + if (!commentOwner || commentOwner.getStart() < position) { + return undefined; + } + var parameters = getParametersForJsDocOwningNode(commentOwner); + var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); + var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; + var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character); + // TODO: call a helper method instead once PR #4133 gets merged in. + var newLine = host.getNewLine ? host.getNewLine() : "\r\n"; + var docParams = ""; + for (var i = 0, numParams = parameters.length; i < numParams; i++) { + var currentName = parameters[i].name; + var paramName = currentName.kind === 69 /* Identifier */ ? + currentName.text : + "param" + i; + docParams += indentationStr + " * @param " + paramName + newLine; + } + // A doc comment consists of the following + // * The opening comment line + // * the first line (without a param) for the object's untagged info (this is also where the caret ends up) + // * the '@param'-tagged lines + // * TODO: other tags. + // * the closing comment line + // * if the caret was directly in front of the object, then we add an extra line and indentation. + var preamble = "/**" + newLine + + indentationStr + " * "; + var result = preamble + newLine + + docParams + + indentationStr + " */" + + (tokenStart === position ? newLine + indentationStr : ""); + return { newText: result, caretOffset: preamble.length }; + } + function getParametersForJsDocOwningNode(commentOwner) { + if (ts.isFunctionLike(commentOwner)) { + return commentOwner.parameters; + } + if (commentOwner.kind === 193 /* VariableStatement */) { + var varStatement = commentOwner; + var varDeclarations = varStatement.declarationList.declarations; + if (varDeclarations.length === 1 && varDeclarations[0].initializer) { + return getParametersFromRightHandSideOfAssignment(varDeclarations[0].initializer); + } + } + return emptyArray; + } + /** + * Digs into an an initializer or RHS operand of an assignment operation + * to get the parameters of an apt signature corresponding to a + * function expression or a class expression. + * + * @param rightHandSide the expression which may contain an appropriate set of parameters + * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. + */ + function getParametersFromRightHandSideOfAssignment(rightHandSide) { + while (rightHandSide.kind === 172 /* ParenthesizedExpression */) { + rightHandSide = rightHandSide.expression; + } + switch (rightHandSide.kind) { + case 173 /* FunctionExpression */: + case 174 /* ArrowFunction */: + return rightHandSide.parameters; + case 186 /* ClassExpression */: + for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 144 /* Constructor */) { + return member.parameters; + } + } + break; + } + return emptyArray; + } + function getTodoComments(fileName, descriptors) { + // Note: while getting todo comments seems like a syntactic operation, we actually + // treat it as a semantic operation here. This is because we expect our host to call + // this on every single file. If we treat this syntactically, then that will cause + // us to populate and throw away the tree in our syntax tree cache for each file. By + // treating this as a semantic operation, we can access any tree without throwing + // anything away. + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + cancellationToken.throwIfCancellationRequested(); + var fileContents = sourceFile.text; + var result = []; + if (descriptors.length > 0) { + var regExp = getTodoCommentsRegExp(); + var matchArray; + while (matchArray = regExp.exec(fileContents)) { + cancellationToken.throwIfCancellationRequested(); + // If we got a match, here is what the match array will look like. Say the source text is: + // + // " // hack 1" + // + // The result array with the regexp: will be: + // + // ["// hack 1", "// ", "hack 1", undefined, "hack"] + // + // Here are the relevant capture groups: + // 0) The full match for the entire regexp. + // 1) The preamble to the message portion. + // 2) The message portion. + // 3...N) The descriptor that was matched - by index. 'undefined' for each + // descriptor that didn't match. an actual value if it did match. + // + // i.e. 'undefined' in position 3 above means TODO(jason) didn't match. + // "hack" in position 4 means HACK did match. + var firstDescriptorCaptureIndex = 3; + ts.Debug.assert(matchArray.length === descriptors.length + firstDescriptorCaptureIndex); + var preamble = matchArray[1]; + var matchPosition = matchArray.index + preamble.length; + // OK, we have found a match in the file. This is only an acceptable match if + // it is contained within a comment. + var token = ts.getTokenAtPosition(sourceFile, matchPosition); + if (!isInsideComment(sourceFile, token, matchPosition)) { + continue; + } + var descriptor = undefined; + for (var i = 0, n = descriptors.length; i < n; i++) { + if (matchArray[i + firstDescriptorCaptureIndex]) { + descriptor = descriptors[i]; + } + } + ts.Debug.assert(descriptor !== undefined); + // We don't want to match something like 'TODOBY', so we make sure a non + // letter/digit follows the match. + if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) { + continue; + } + var message = matchArray[2]; + result.push({ + descriptor: descriptor, + message: message, + position: matchPosition + }); + } + } + return result; + function escapeRegExp(str) { + return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); + } + function getTodoCommentsRegExp() { + // NOTE: ?: means 'non-capture group'. It allows us to have groups without having to + // filter them out later in the final result array. + // TODO comments can appear in one of the following forms: + // + // 1) // TODO or /////////// TODO + // + // 2) /* TODO or /********** TODO + // + // 3) /* + // * TODO + // */ + // + // The following three regexps are used to match the start of the text up to the TODO + // comment portion. + var singleLineCommentStart = /(?:\/\/+\s*)/.source; + var multiLineCommentStart = /(?:\/\*+\s*)/.source; + var anyNumberOfSpacesAndAsterixesAtStartOfLine = /(?:^(?:\s|\*)*)/.source; + // Match any of the above three TODO comment start regexps. + // Note that the outermost group *is* a capture group. We want to capture the preamble + // so that we can determine the starting position of the TODO comment match. + var preamble = "(" + anyNumberOfSpacesAndAsterixesAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; + // Takes the descriptors and forms a regexp that matches them as if they were literals. + // For example, if the descriptors are "TODO(jason)" and "HACK", then this will be: + // + // (?:(TODO\(jason\))|(HACK)) + // + // Note that the outermost group is *not* a capture group, but the innermost groups + // *are* capture groups. By capturing the inner literals we can determine after + // matching which descriptor we are dealing with. + var literals = "(?:" + ts.map(descriptors, function (d) { return "(" + escapeRegExp(d.text) + ")"; }).join("|") + ")"; + // After matching a descriptor literal, the following regexp matches the rest of the + // text up to the end of the line (or */). + var endOfLineOrEndOfComment = /(?:$|\*\/)/.source; + var messageRemainder = /(?:.*?)/.source; + // This is the portion of the match we'll return as part of the TODO comment result. We + // match the literal portion up to the end of the line or end of comment. + var messagePortion = "(" + literals + messageRemainder + ")"; + var regExpString = preamble + messagePortion + endOfLineOrEndOfComment; + // The final regexp will look like this: + // /((?:\/\/+\s*)|(?:\/\*+\s*)|(?:^(?:\s|\*)*))((?:(TODO\(jason\))|(HACK))(?:.*?))(?:$|\*\/)/gim + // The flags of the regexp are important here. + // 'g' is so that we are doing a global search and can find matches several times + // in the input. + // + // 'i' is for case insensitivity (We do this to match C# TODO comment code). + // + // 'm' is so we can find matches in a multi-line input. + return new RegExp(regExpString, "gim"); + } + function isLetterOrDigit(char) { + return (char >= 97 /* a */ && char <= 122 /* z */) || + (char >= 65 /* A */ && char <= 90 /* Z */) || + (char >= 48 /* _0 */ && char <= 57 /* _9 */); + } + } + function getRenameInfo(fileName, position) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var typeChecker = program.getTypeChecker(); + var node = ts.getTouchingWord(sourceFile, position); + // Can only rename an identifier. + if (node && node.kind === 69 /* Identifier */) { + var symbol = typeChecker.getSymbolAtLocation(node); + // Only allow a symbol to be renamed if it actually has at least one declaration. + if (symbol) { + var declarations = symbol.getDeclarations(); + if (declarations && declarations.length > 0) { + // Disallow rename for elements that are defined in the standard TypeScript library. + var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); + if (defaultLibFileName) { + for (var _i = 0; _i < declarations.length; _i++) { + var current = declarations[_i]; + var sourceFile_2 = current.getSourceFile(); + var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)); + if (sourceFile_2 && getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)) === getCanonicalFileName(ts.normalizePath(defaultLibFileName))) { + return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library.key)); + } + } + } + var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); + var kind = getSymbolKind(symbol, node); + if (kind) { + return { + canRename: true, + localizedErrorMessage: undefined, + displayName: displayName, + fullDisplayName: typeChecker.getFullyQualifiedName(symbol), + kind: kind, + kindModifiers: getSymbolModifiers(symbol), + triggerSpan: ts.createTextSpan(node.getStart(), node.getWidth()) + }; + } + } + } + } + return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_this_element.key)); + function getRenameInfoError(localizedErrorMessage) { + return { + canRename: false, + localizedErrorMessage: localizedErrorMessage, + displayName: undefined, + fullDisplayName: undefined, + kind: undefined, + kindModifiers: undefined, + triggerSpan: undefined + }; + } + } + return { + dispose: dispose, + cleanupSemanticCache: cleanupSemanticCache, + getSyntacticDiagnostics: getSyntacticDiagnostics, + getSemanticDiagnostics: getSemanticDiagnostics, + getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, + getSyntacticClassifications: getSyntacticClassifications, + getSemanticClassifications: getSemanticClassifications, + getEncodedSyntacticClassifications: getEncodedSyntacticClassifications, + getEncodedSemanticClassifications: getEncodedSemanticClassifications, + getCompletionsAtPosition: getCompletionsAtPosition, + getCompletionEntryDetails: getCompletionEntryDetails, + getSignatureHelpItems: getSignatureHelpItems, + getQuickInfoAtPosition: getQuickInfoAtPosition, + getDefinitionAtPosition: getDefinitionAtPosition, + getTypeDefinitionAtPosition: getTypeDefinitionAtPosition, + getReferencesAtPosition: getReferencesAtPosition, + findReferences: findReferences, + getOccurrencesAtPosition: getOccurrencesAtPosition, + getDocumentHighlights: getDocumentHighlights, + getNameOrDottedNameSpan: getNameOrDottedNameSpan, + getBreakpointStatementAtPosition: getBreakpointStatementAtPosition, + getNavigateToItems: getNavigateToItems, + getRenameInfo: getRenameInfo, + findRenameLocations: findRenameLocations, + getNavigationBarItems: getNavigationBarItems, + getOutliningSpans: getOutliningSpans, + getTodoComments: getTodoComments, + getBraceMatchingAtPosition: getBraceMatchingAtPosition, + getIndentationAtPosition: getIndentationAtPosition, + getFormattingEditsForRange: getFormattingEditsForRange, + getFormattingEditsForDocument: getFormattingEditsForDocument, + getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, + getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, + getEmitOutput: getEmitOutput, + getSourceFile: getSourceFile, + getProgram: getProgram + }; + } + ts.createLanguageService = createLanguageService; + /* @internal */ + function getNameTable(sourceFile) { + if (!sourceFile.nameTable) { + initializeNameTable(sourceFile); + } + return sourceFile.nameTable; + } + ts.getNameTable = getNameTable; + function initializeNameTable(sourceFile) { + var nameTable = {}; + walk(sourceFile); + sourceFile.nameTable = nameTable; + function walk(node) { + switch (node.kind) { + case 69 /* Identifier */: + nameTable[node.text] = node.text; + break; + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + // We want to store any numbers/strings if they were a name that could be + // related to a declaration. So, if we have 'import x = require("something")' + // then we want 'something' to be in the name table. Similarly, if we have + // "a['propname']" then we want to store "propname" in the name table. + if (ts.isDeclarationName(node) || + node.parent.kind === 232 /* ExternalModuleReference */ || + isArgumentOfElementAccessExpression(node)) { + nameTable[node.text] = node.text; + } + break; + default: + ts.forEachChild(node, walk); + } + } + } + function isArgumentOfElementAccessExpression(node) { + return node && + node.parent && + node.parent.kind === 167 /* ElementAccessExpression */ && + node.parent.argumentExpression === node; + } + /// Classifier + function createClassifier() { + var scanner = ts.createScanner(2 /* Latest */, /*skipTrivia*/ false); + /// We do not have a full parser support to know when we should parse a regex or not + /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where + /// we have a series of divide operator. this list allows us to be more accurate by ruling out + /// locations where a regexp cannot exist. + var noRegexTable = []; + noRegexTable[69 /* Identifier */] = true; + noRegexTable[9 /* StringLiteral */] = true; + noRegexTable[8 /* NumericLiteral */] = true; + noRegexTable[10 /* RegularExpressionLiteral */] = true; + noRegexTable[97 /* ThisKeyword */] = true; + noRegexTable[41 /* PlusPlusToken */] = true; + noRegexTable[42 /* MinusMinusToken */] = true; + noRegexTable[18 /* CloseParenToken */] = true; + noRegexTable[20 /* CloseBracketToken */] = true; + noRegexTable[16 /* CloseBraceToken */] = true; + noRegexTable[99 /* TrueKeyword */] = true; + noRegexTable[84 /* FalseKeyword */] = true; + // Just a stack of TemplateHeads and OpenCurlyBraces, used to perform rudimentary (inexact) + // classification on template strings. Because of the context free nature of templates, + // the only precise way to classify a template portion would be by propagating the stack across + // lines, just as we do with the end-of-line state. However, this is a burden for implementers, + // and the behavior is entirely subsumed by the syntactic classifier anyway, so we instead + // flatten any nesting when the template stack is non-empty and encode it in the end-of-line state. + // Situations in which this fails are + // 1) When template strings are nested across different lines: + // `hello ${ `world + // ` }` + // + // Where on the second line, you will get the closing of a template, + // a closing curly, and a new template. + // + // 2) When substitution expressions have curly braces and the curly brace falls on the next line: + // `hello ${ () => { + // return "world" } } ` + // + // Where on the second line, you will get the 'return' keyword, + // a string literal, and a template end consisting of '} } `'. + var templateStack = []; + /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ + function canFollow(keyword1, keyword2) { + if (ts.isAccessibilityModifier(keyword1)) { + if (keyword2 === 123 /* GetKeyword */ || + keyword2 === 129 /* SetKeyword */ || + keyword2 === 121 /* ConstructorKeyword */ || + keyword2 === 113 /* StaticKeyword */) { + // Allow things like "public get", "public constructor" and "public static". + // These are all legal. + return true; + } + // Any other keyword following "public" is actually an identifier an not a real + // keyword. + return false; + } + // Assume any other keyword combination is legal. This can be refined in the future + // if there are more cases we want the classifier to be better at. + return true; + } + function convertClassifications(classifications, text) { + var entries = []; + var dense = classifications.spans; + var lastEnd = 0; + for (var i = 0, n = dense.length; i < n; i += 3) { + var start = dense[i]; + var length_3 = dense[i + 1]; + var type = dense[i + 2]; + // Make a whitespace entry between the last item and this one. + if (lastEnd >= 0) { + var whitespaceLength_1 = start - lastEnd; + if (whitespaceLength_1 > 0) { + entries.push({ length: whitespaceLength_1, classification: TokenClass.Whitespace }); + } + } + entries.push({ length: length_3, classification: convertClassification(type) }); + lastEnd = start + length_3; + } + var whitespaceLength = text.length - lastEnd; + if (whitespaceLength > 0) { + entries.push({ length: whitespaceLength, classification: TokenClass.Whitespace }); + } + return { entries: entries, finalLexState: classifications.endOfLineState }; + } + function convertClassification(type) { + switch (type) { + case 1 /* comment */: return TokenClass.Comment; + case 3 /* keyword */: return TokenClass.Keyword; + case 4 /* numericLiteral */: return TokenClass.NumberLiteral; + case 5 /* operator */: return TokenClass.Operator; + case 6 /* stringLiteral */: return TokenClass.StringLiteral; + case 8 /* whiteSpace */: return TokenClass.Whitespace; + case 10 /* punctuation */: return TokenClass.Punctuation; + case 2 /* identifier */: + case 11 /* className */: + case 12 /* enumName */: + case 13 /* interfaceName */: + case 14 /* moduleName */: + case 15 /* typeParameterName */: + case 16 /* typeAliasName */: + case 9 /* text */: + case 17 /* parameterName */: + default: + return TokenClass.Identifier; + } + } + function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { + return convertClassifications(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); + } + // If there is a syntactic classifier ('syntacticClassifierAbsent' is false), + // we will be more conservative in order to avoid conflicting with the syntactic classifier. + function getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent) { + var offset = 0; + var token = 0 /* Unknown */; + var lastNonTriviaToken = 0 /* Unknown */; + // Empty out the template stack for reuse. + while (templateStack.length > 0) { + templateStack.pop(); + } + // If we're in a string literal, then prepend: "\ + // (and a newline). That way when we lex we'll think we're still in a string literal. + // + // If we're in a multiline comment, then prepend: /* + // (and a newline). That way when we lex we'll think we're still in a multiline comment. + switch (lexState) { + case 3 /* InDoubleQuoteStringLiteral */: + text = '"\\\n' + text; + offset = 3; + break; + case 2 /* InSingleQuoteStringLiteral */: + text = "'\\\n" + text; + offset = 3; + break; + case 1 /* InMultiLineCommentTrivia */: + text = "/*\n" + text; + offset = 3; + break; + case 4 /* InTemplateHeadOrNoSubstitutionTemplate */: + text = "`\n" + text; + offset = 2; + break; + case 5 /* InTemplateMiddleOrTail */: + text = "}\n" + text; + offset = 2; + // fallthrough + case 6 /* InTemplateSubstitutionPosition */: + templateStack.push(12 /* TemplateHead */); + break; + } + scanner.setText(text); + var result = { + endOfLineState: 0 /* None */, + spans: [] + }; + // We can run into an unfortunate interaction between the lexical and syntactic classifier + // when the user is typing something generic. Consider the case where the user types: + // + // Foo tokens. It's a weak heuristic, but should + // work well enough in practice. + var angleBracketStack = 0; + do { + token = scanner.scan(); + if (!ts.isTrivia(token)) { + if ((token === 39 /* SlashToken */ || token === 61 /* SlashEqualsToken */) && !noRegexTable[lastNonTriviaToken]) { + if (scanner.reScanSlashToken() === 10 /* RegularExpressionLiteral */) { + token = 10 /* RegularExpressionLiteral */; + } + } + else if (lastNonTriviaToken === 21 /* DotToken */ && isKeyword(token)) { + token = 69 /* Identifier */; + } + else if (isKeyword(lastNonTriviaToken) && isKeyword(token) && !canFollow(lastNonTriviaToken, token)) { + // We have two keywords in a row. Only treat the second as a keyword if + // it's a sequence that could legally occur in the language. Otherwise + // treat it as an identifier. This way, if someone writes "private var" + // we recognize that 'var' is actually an identifier here. + token = 69 /* Identifier */; + } + else if (lastNonTriviaToken === 69 /* Identifier */ && + token === 25 /* LessThanToken */) { + // Could be the start of something generic. Keep track of that by bumping + // up the current count of generic contexts we may be in. + angleBracketStack++; + } + else if (token === 27 /* GreaterThanToken */ && angleBracketStack > 0) { + // If we think we're currently in something generic, then mark that that + // generic entity is complete. + angleBracketStack--; + } + else if (token === 117 /* AnyKeyword */ || + token === 130 /* StringKeyword */ || + token === 128 /* NumberKeyword */ || + token === 120 /* BooleanKeyword */ || + token === 131 /* SymbolKeyword */) { + if (angleBracketStack > 0 && !syntacticClassifierAbsent) { + // If it looks like we're could be in something generic, don't classify this + // as a keyword. We may just get overwritten by the syntactic classifier, + // causing a noisy experience for the user. + token = 69 /* Identifier */; + } + } + else if (token === 12 /* TemplateHead */) { + templateStack.push(token); + } + else if (token === 15 /* OpenBraceToken */) { + // If we don't have anything on the template stack, + // then we aren't trying to keep track of a previously scanned template head. + if (templateStack.length > 0) { + templateStack.push(token); + } + } + else if (token === 16 /* CloseBraceToken */) { + // If we don't have anything on the template stack, + // then we aren't trying to keep track of a previously scanned template head. + if (templateStack.length > 0) { + var lastTemplateStackToken = ts.lastOrUndefined(templateStack); + if (lastTemplateStackToken === 12 /* TemplateHead */) { + token = scanner.reScanTemplateToken(); + // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us. + if (token === 14 /* TemplateTail */) { + templateStack.pop(); + } + else { + ts.Debug.assert(token === 13 /* TemplateMiddle */, "Should have been a template middle. Was " + token); + } + } + else { + ts.Debug.assert(lastTemplateStackToken === 15 /* OpenBraceToken */, "Should have been an open brace. Was: " + token); + templateStack.pop(); + } + } + } + lastNonTriviaToken = token; + } + processToken(); + } while (token !== 1 /* EndOfFileToken */); + return result; + function processToken() { + var start = scanner.getTokenPos(); + var end = scanner.getTextPos(); + addResult(start, end, classFromKind(token)); + if (end >= text.length) { + if (token === 9 /* StringLiteral */) { + // Check to see if we finished up on a multiline string literal. + var tokenText = scanner.getTokenText(); + if (scanner.isUnterminated()) { + var lastCharIndex = tokenText.length - 1; + var numBackslashes = 0; + while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) { + numBackslashes++; + } + // If we have an odd number of backslashes, then the multiline string is unclosed + if (numBackslashes & 1) { + var quoteChar = tokenText.charCodeAt(0); + result.endOfLineState = quoteChar === 34 /* doubleQuote */ + ? 3 /* InDoubleQuoteStringLiteral */ + : 2 /* InSingleQuoteStringLiteral */; + } + } + } + else if (token === 3 /* MultiLineCommentTrivia */) { + // Check to see if the multiline comment was unclosed. + if (scanner.isUnterminated()) { + result.endOfLineState = 1 /* InMultiLineCommentTrivia */; + } + } + else if (ts.isTemplateLiteralKind(token)) { + if (scanner.isUnterminated()) { + if (token === 14 /* TemplateTail */) { + result.endOfLineState = 5 /* InTemplateMiddleOrTail */; + } + else if (token === 11 /* NoSubstitutionTemplateLiteral */) { + result.endOfLineState = 4 /* InTemplateHeadOrNoSubstitutionTemplate */; + } + else { + ts.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #" + token); + } + } + } + else if (templateStack.length > 0 && ts.lastOrUndefined(templateStack) === 12 /* TemplateHead */) { + result.endOfLineState = 6 /* InTemplateSubstitutionPosition */; + } + } + } + function addResult(start, end, classification) { + if (classification === 8 /* whiteSpace */) { + // Don't bother with whitespace classifications. They're not needed. + return; + } + if (start === 0 && offset > 0) { + // We're classifying the first token, and this was a case where we prepended + // text. We should consider the start of this token to be at the start of + // the original text. + start += offset; + } + // All our tokens are in relation to the augmented text. Move them back to be + // relative to the original text. + start -= offset; + end -= offset; + var length = end - start; + if (length > 0) { + result.spans.push(start); + result.spans.push(length); + result.spans.push(classification); + } + } + } + function isBinaryExpressionOperatorToken(token) { + switch (token) { + case 37 /* AsteriskToken */: + case 39 /* SlashToken */: + case 40 /* PercentToken */: + case 35 /* PlusToken */: + case 36 /* MinusToken */: + case 43 /* LessThanLessThanToken */: + case 44 /* GreaterThanGreaterThanToken */: + case 45 /* GreaterThanGreaterThanGreaterThanToken */: + case 25 /* LessThanToken */: + case 27 /* GreaterThanToken */: + case 28 /* LessThanEqualsToken */: + case 29 /* GreaterThanEqualsToken */: + case 91 /* InstanceOfKeyword */: + case 90 /* InKeyword */: + case 116 /* AsKeyword */: + case 30 /* EqualsEqualsToken */: + case 31 /* ExclamationEqualsToken */: + case 32 /* EqualsEqualsEqualsToken */: + case 33 /* ExclamationEqualsEqualsToken */: + case 46 /* AmpersandToken */: + case 48 /* CaretToken */: + case 47 /* BarToken */: + case 51 /* AmpersandAmpersandToken */: + case 52 /* BarBarToken */: + case 67 /* BarEqualsToken */: + case 66 /* AmpersandEqualsToken */: + case 68 /* CaretEqualsToken */: + case 63 /* LessThanLessThanEqualsToken */: + case 64 /* GreaterThanGreaterThanEqualsToken */: + case 65 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 57 /* PlusEqualsToken */: + case 58 /* MinusEqualsToken */: + case 59 /* AsteriskEqualsToken */: + case 61 /* SlashEqualsToken */: + case 62 /* PercentEqualsToken */: + case 56 /* EqualsToken */: + case 24 /* CommaToken */: + return true; + default: + return false; + } + } + function isPrefixUnaryExpressionOperatorToken(token) { + switch (token) { + case 35 /* PlusToken */: + case 36 /* MinusToken */: + case 50 /* TildeToken */: + case 49 /* ExclamationToken */: + case 41 /* PlusPlusToken */: + case 42 /* MinusMinusToken */: + return true; + default: + return false; + } + } + function isKeyword(token) { + return token >= 70 /* FirstKeyword */ && token <= 134 /* LastKeyword */; + } + function classFromKind(token) { + if (isKeyword(token)) { + return 3 /* keyword */; + } + else if (isBinaryExpressionOperatorToken(token) || isPrefixUnaryExpressionOperatorToken(token)) { + return 5 /* operator */; + } + else if (token >= 15 /* FirstPunctuation */ && token <= 68 /* LastPunctuation */) { + return 10 /* punctuation */; + } + switch (token) { + case 8 /* NumericLiteral */: + return 4 /* numericLiteral */; + case 9 /* StringLiteral */: + return 6 /* stringLiteral */; + case 10 /* RegularExpressionLiteral */: + return 7 /* regularExpressionLiteral */; + case 7 /* ConflictMarkerTrivia */: + case 3 /* MultiLineCommentTrivia */: + case 2 /* SingleLineCommentTrivia */: + return 1 /* comment */; + case 5 /* WhitespaceTrivia */: + case 4 /* NewLineTrivia */: + return 8 /* whiteSpace */; + case 69 /* Identifier */: + default: + if (ts.isTemplateLiteralKind(token)) { + return 6 /* stringLiteral */; + } + return 2 /* identifier */; + } + } + return { + getClassificationsForLine: getClassificationsForLine, + getEncodedLexicalClassifications: getEncodedLexicalClassifications + }; + } + ts.createClassifier = createClassifier; + /** + * Get the path of the default library files (lib.d.ts) as distributed with the typescript + * node package. + * The functionality is not supported if the ts module is consumed outside of a node module. + */ + function getDefaultLibFilePath(options) { + // Check __dirname is defined and that we are on a node.js system. + if (typeof __dirname !== "undefined") { + return __dirname + ts.directorySeparator + ts.getDefaultLibFileName(options); + } + throw new Error("getDefaultLibFilePath is only supported when consumed as a node module. "); + } + ts.getDefaultLibFilePath = getDefaultLibFilePath; + function initializeServices() { + ts.objectAllocator = { + getNodeConstructor: function (kind) { + function Node() { + } + var proto = kind === 248 /* SourceFile */ ? new SourceFileObject() : new NodeObject(); + proto.kind = kind; + proto.pos = -1; + proto.end = -1; + proto.flags = 0; + proto.parent = undefined; + Node.prototype = proto; + return Node; + }, + getSymbolConstructor: function () { return SymbolObject; }, + getTypeConstructor: function () { return TypeObject; }, + getSignatureConstructor: function () { return SignatureObject; } + }; + } + initializeServices(); +})(ts || (ts = {})); +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. +/// +/* @internal */ +var ts; +(function (ts) { + var BreakpointResolver; + (function (BreakpointResolver) { + /** + * Get the breakpoint span in given sourceFile + */ + function spanInSourceFileAtLocation(sourceFile, position) { + // Cannot set breakpoint in dts file + if (sourceFile.flags & 8192 /* DeclarationFile */) { + return undefined; + } + var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); + var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; + if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart()).line > lineOfPosition) { + // Get previous token if the token is returned starts on new line + // eg: let x =10; |--- cursor is here + // let y = 10; + // token at position will return let keyword on second line as the token but we would like to use + // token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line + tokenAtLocation = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); + // Its a blank line + if (!tokenAtLocation || sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getEnd()).line !== lineOfPosition) { + return undefined; + } + } + // Cannot set breakpoint in ambient declarations + if (ts.isInAmbientContext(tokenAtLocation)) { + return undefined; + } + // Get the span in the node based on its syntax + return spanInNode(tokenAtLocation); + function textSpan(startNode, endNode) { + return ts.createTextSpanFromBounds(startNode.getStart(), (endNode || startNode).getEnd()); + } + function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { + if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart()).line) { + return spanInNode(node); + } + return spanInNode(otherwiseOnNode); + } + function spanInPreviousNode(node) { + return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); + } + function spanInNextNode(node) { + return spanInNode(ts.findNextToken(node, node.parent)); + } + function spanInNode(node) { + if (node) { + if (ts.isExpression(node)) { + if (node.parent.kind === 197 /* DoStatement */) { + // Set span as if on while keyword + return spanInPreviousNode(node); + } + if (node.parent.kind === 199 /* ForStatement */) { + // For now lets set the span on this expression, fix it later + return textSpan(node); + } + if (node.parent.kind === 181 /* BinaryExpression */ && node.parent.operatorToken.kind === 24 /* CommaToken */) { + // if this is comma expression, the breakpoint is possible in this expression + return textSpan(node); + } + if (node.parent.kind === 174 /* ArrowFunction */ && node.parent.body === node) { + // If this is body of arrow function, it is allowed to have the breakpoint + return textSpan(node); + } + } + switch (node.kind) { + case 193 /* VariableStatement */: + // Span on first variable declaration + return spanInVariableDeclaration(node.declarationList.declarations[0]); + case 211 /* VariableDeclaration */: + case 141 /* PropertyDeclaration */: + case 140 /* PropertySignature */: + return spanInVariableDeclaration(node); + case 138 /* Parameter */: + return spanInParameterDeclaration(node); + case 213 /* FunctionDeclaration */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 144 /* Constructor */: + case 173 /* FunctionExpression */: + case 174 /* ArrowFunction */: + return spanInFunctionDeclaration(node); + case 192 /* Block */: + if (ts.isFunctionBlock(node)) { + return spanInFunctionBlock(node); + } + // Fall through + case 219 /* ModuleBlock */: + return spanInBlock(node); + case 244 /* CatchClause */: + return spanInBlock(node.block); + case 195 /* ExpressionStatement */: + // span on the expression + return textSpan(node.expression); + case 204 /* ReturnStatement */: + // span on return keyword and expression if present + return textSpan(node.getChildAt(0), node.expression); + case 198 /* WhileStatement */: + // Span on while(...) + return textSpan(node, ts.findNextToken(node.expression, node)); + case 197 /* DoStatement */: + // span in statement of the do statement + return spanInNode(node.statement); + case 210 /* DebuggerStatement */: + // span on debugger keyword + return textSpan(node.getChildAt(0)); + case 196 /* IfStatement */: + // set on if(..) span + return textSpan(node, ts.findNextToken(node.expression, node)); + case 207 /* LabeledStatement */: + // span in statement + return spanInNode(node.statement); + case 203 /* BreakStatement */: + case 202 /* ContinueStatement */: + // On break or continue keyword and label if present + return textSpan(node.getChildAt(0), node.label); + case 199 /* ForStatement */: + return spanInForStatement(node); + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + // span on for (a in ...) + return textSpan(node, ts.findNextToken(node.expression, node)); + case 206 /* SwitchStatement */: + // span on switch(...) + return textSpan(node, ts.findNextToken(node.expression, node)); + case 241 /* CaseClause */: + case 242 /* DefaultClause */: + // span in first statement of the clause + return spanInNode(node.statements[0]); + case 209 /* TryStatement */: + // span in try block + return spanInBlock(node.tryBlock); + case 208 /* ThrowStatement */: + // span in throw ... + return textSpan(node, node.expression); + case 227 /* ExportAssignment */: + // span on export = id + return textSpan(node, node.expression); + case 221 /* ImportEqualsDeclaration */: + // import statement without including semicolon + return textSpan(node, node.moduleReference); + case 222 /* ImportDeclaration */: + // import statement without including semicolon + return textSpan(node, node.moduleSpecifier); + case 228 /* ExportDeclaration */: + // import statement without including semicolon + return textSpan(node, node.moduleSpecifier); + case 218 /* ModuleDeclaration */: + // span on complete module if it is instantiated + if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return undefined; + } + case 214 /* ClassDeclaration */: + case 217 /* EnumDeclaration */: + case 247 /* EnumMember */: + case 168 /* CallExpression */: + case 169 /* NewExpression */: + // span on complete node + return textSpan(node); + case 205 /* WithStatement */: + // span in statement + return spanInNode(node.statement); + // No breakpoint in interface, type alias + case 215 /* InterfaceDeclaration */: + case 216 /* TypeAliasDeclaration */: + return undefined; + // Tokens: + case 23 /* SemicolonToken */: + case 1 /* EndOfFileToken */: + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile)); + case 24 /* CommaToken */: + return spanInPreviousNode(node); + case 15 /* OpenBraceToken */: + return spanInOpenBraceToken(node); + case 16 /* CloseBraceToken */: + return spanInCloseBraceToken(node); + case 17 /* OpenParenToken */: + return spanInOpenParenToken(node); + case 18 /* CloseParenToken */: + return spanInCloseParenToken(node); + case 54 /* ColonToken */: + return spanInColonToken(node); + case 27 /* GreaterThanToken */: + case 25 /* LessThanToken */: + return spanInGreaterThanOrLessThanToken(node); + // Keywords: + case 104 /* WhileKeyword */: + return spanInWhileKeyword(node); + case 80 /* ElseKeyword */: + case 72 /* CatchKeyword */: + case 85 /* FinallyKeyword */: + return spanInNextNode(node); + default: + // If this is name of property assignment, set breakpoint in the initializer + if (node.parent.kind === 245 /* PropertyAssignment */ && node.parent.name === node) { + return spanInNode(node.parent.initializer); + } + // Breakpoint in type assertion goes to its operand + if (node.parent.kind === 171 /* TypeAssertionExpression */ && node.parent.type === node) { + return spanInNode(node.parent.expression); + } + // return type of function go to previous token + if (ts.isFunctionLike(node.parent) && node.parent.type === node) { + return spanInPreviousNode(node); + } + // Default go to parent to set the breakpoint + return spanInNode(node.parent); + } + } + function spanInVariableDeclaration(variableDeclaration) { + // If declaration of for in statement, just set the span in parent + if (variableDeclaration.parent.parent.kind === 200 /* ForInStatement */ || + variableDeclaration.parent.parent.kind === 201 /* ForOfStatement */) { + return spanInNode(variableDeclaration.parent.parent); + } + var isParentVariableStatement = variableDeclaration.parent.parent.kind === 193 /* VariableStatement */; + var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === 199 /* ForStatement */ && ts.contains(variableDeclaration.parent.parent.initializer.declarations, variableDeclaration); + var declarations = isParentVariableStatement + ? variableDeclaration.parent.parent.declarationList.declarations + : isDeclarationOfForStatement + ? variableDeclaration.parent.parent.initializer.declarations + : undefined; + // Breakpoint is possible in variableDeclaration only if there is initialization + if (variableDeclaration.initializer || (variableDeclaration.flags & 1 /* Export */)) { + if (declarations && declarations[0] === variableDeclaration) { + if (isParentVariableStatement) { + // First declaration - include let keyword + return textSpan(variableDeclaration.parent, variableDeclaration); + } + else { + ts.Debug.assert(isDeclarationOfForStatement); + // Include let keyword from for statement declarations in the span + return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); + } + } + else { + // Span only on this declaration + return textSpan(variableDeclaration); + } + } + else if (declarations && declarations[0] !== variableDeclaration) { + // If we cant set breakpoint on this declaration, set it on previous one + var indexOfCurrentDeclaration = ts.indexOf(declarations, variableDeclaration); + return spanInVariableDeclaration(declarations[indexOfCurrentDeclaration - 1]); + } + } + function canHaveSpanInParameterDeclaration(parameter) { + // Breakpoint is possible on parameter only if it has initializer, is a rest parameter, or has public or private modifier + return !!parameter.initializer || parameter.dotDotDotToken !== undefined || + !!(parameter.flags & 16 /* Public */) || !!(parameter.flags & 32 /* Private */); + } + function spanInParameterDeclaration(parameter) { + if (canHaveSpanInParameterDeclaration(parameter)) { + return textSpan(parameter); + } + else { + var functionDeclaration = parameter.parent; + var indexOfParameter = ts.indexOf(functionDeclaration.parameters, parameter); + if (indexOfParameter) { + // Not a first parameter, go to previous parameter + return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); + } + else { + // Set breakpoint in the function declaration body + return spanInNode(functionDeclaration.body); + } + } + } + function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { + return !!(functionDeclaration.flags & 1 /* Export */) || + (functionDeclaration.parent.kind === 214 /* ClassDeclaration */ && functionDeclaration.kind !== 144 /* Constructor */); + } + function spanInFunctionDeclaration(functionDeclaration) { + // No breakpoints in the function signature + if (!functionDeclaration.body) { + return undefined; + } + if (canFunctionHaveSpanInWholeDeclaration(functionDeclaration)) { + // Set the span on whole function declaration + return textSpan(functionDeclaration); + } + // Set span in function body + return spanInNode(functionDeclaration.body); + } + function spanInFunctionBlock(block) { + var nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken(); + if (canFunctionHaveSpanInWholeDeclaration(block.parent)) { + return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock); + } + return spanInNode(nodeForSpanInBlock); + } + function spanInBlock(block) { + switch (block.parent.kind) { + case 218 /* ModuleDeclaration */: + if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { + return undefined; + } + // Set on parent if on same line otherwise on first statement + case 198 /* WhileStatement */: + case 196 /* IfStatement */: + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); + // Set span on previous token if it starts on same line otherwise on the first statement of the block + case 199 /* ForStatement */: + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); + } + // Default action is to set on first statement + return spanInNode(block.statements[0]); + } + function spanInForStatement(forStatement) { + if (forStatement.initializer) { + if (forStatement.initializer.kind === 212 /* VariableDeclarationList */) { + var variableDeclarationList = forStatement.initializer; + if (variableDeclarationList.declarations.length > 0) { + return spanInNode(variableDeclarationList.declarations[0]); + } + } + else { + return spanInNode(forStatement.initializer); + } + } + if (forStatement.condition) { + return textSpan(forStatement.condition); + } + if (forStatement.incrementor) { + return textSpan(forStatement.incrementor); + } + } + // Tokens: + function spanInOpenBraceToken(node) { + switch (node.parent.kind) { + case 217 /* EnumDeclaration */: + var enumDeclaration = node.parent; + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); + case 214 /* ClassDeclaration */: + var classDeclaration = node.parent; + return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); + case 220 /* CaseBlock */: + return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); + } + // Default to parent node + return spanInNode(node.parent); + } + function spanInCloseBraceToken(node) { + switch (node.parent.kind) { + case 219 /* ModuleBlock */: + // If this is not instantiated module block no bp span + if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { + return undefined; + } + case 217 /* EnumDeclaration */: + case 214 /* ClassDeclaration */: + // Span on close brace token + return textSpan(node); + case 192 /* Block */: + if (ts.isFunctionBlock(node.parent)) { + // Span on close brace token + return textSpan(node); + } + // fall through. + case 244 /* CatchClause */: + return spanInNode(ts.lastOrUndefined(node.parent.statements)); + ; + case 220 /* CaseBlock */: + // breakpoint in last statement of the last clause + var caseBlock = node.parent; + var lastClause = ts.lastOrUndefined(caseBlock.clauses); + if (lastClause) { + return spanInNode(ts.lastOrUndefined(lastClause.statements)); + } + return undefined; + // Default to parent node + default: + return spanInNode(node.parent); + } + } + function spanInOpenParenToken(node) { + if (node.parent.kind === 197 /* DoStatement */) { + // Go to while keyword and do action instead + return spanInPreviousNode(node); + } + // Default to parent node + return spanInNode(node.parent); + } + function spanInCloseParenToken(node) { + // Is this close paren token of parameter list, set span in previous token + switch (node.parent.kind) { + case 173 /* FunctionExpression */: + case 213 /* FunctionDeclaration */: + case 174 /* ArrowFunction */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 144 /* Constructor */: + case 198 /* WhileStatement */: + case 197 /* DoStatement */: + case 199 /* ForStatement */: + return spanInPreviousNode(node); + // Default to parent node + default: + return spanInNode(node.parent); + } + // Default to parent node + return spanInNode(node.parent); + } + function spanInColonToken(node) { + // Is this : specifying return annotation of the function declaration + if (ts.isFunctionLike(node.parent) || node.parent.kind === 245 /* PropertyAssignment */) { + return spanInPreviousNode(node); + } + return spanInNode(node.parent); + } + function spanInGreaterThanOrLessThanToken(node) { + if (node.parent.kind === 171 /* TypeAssertionExpression */) { + return spanInNode(node.parent.expression); + } + return spanInNode(node.parent); + } + function spanInWhileKeyword(node) { + if (node.parent.kind === 197 /* DoStatement */) { + // Set span on while expression + return textSpan(node, ts.findNextToken(node.parent.expression, node.parent)); + } + // Default to parent node + return spanInNode(node.parent); + } + } + } + BreakpointResolver.spanInSourceFileAtLocation = spanInSourceFileAtLocation; + })(BreakpointResolver = ts.BreakpointResolver || (ts.BreakpointResolver = {})); +})(ts || (ts = {})); +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/// +/* @internal */ +var debugObjectHost = this; +/* @internal */ +var ts; +(function (ts) { + function logInternalError(logger, err) { + if (logger) { + logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message); + } + } + var ScriptSnapshotShimAdapter = (function () { + function ScriptSnapshotShimAdapter(scriptSnapshotShim) { + this.scriptSnapshotShim = scriptSnapshotShim; + this.lineStartPositions = null; + } + ScriptSnapshotShimAdapter.prototype.getText = function (start, end) { + return this.scriptSnapshotShim.getText(start, end); + }; + ScriptSnapshotShimAdapter.prototype.getLength = function () { + return this.scriptSnapshotShim.getLength(); + }; + ScriptSnapshotShimAdapter.prototype.getChangeRange = function (oldSnapshot) { + var oldSnapshotShim = oldSnapshot; + var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim); + // TODO: should this be '==='? + if (encoded == null) { + return null; + } + var decoded = JSON.parse(encoded); + return ts.createTextChangeRange(ts.createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); + }; + ScriptSnapshotShimAdapter.prototype.dispose = function () { + // if scriptSnapshotShim is a COM object then property check becomes method call with no arguments + // 'in' does not have this effect + if ("dispose" in this.scriptSnapshotShim) { + this.scriptSnapshotShim.dispose(); + } + }; + return ScriptSnapshotShimAdapter; + })(); + var LanguageServiceShimHostAdapter = (function () { + function LanguageServiceShimHostAdapter(shimHost) { + var _this = this; + this.shimHost = shimHost; + this.loggingEnabled = false; + this.tracingEnabled = false; + // if shimHost is a COM object then property check will become method call with no arguments. + // 'in' does not have this effect. + if ("getModuleResolutionsForFile" in this.shimHost) { + this.resolveModuleNames = function (moduleNames, containingFile) { + var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); + return ts.map(moduleNames, function (name) { + var result = ts.lookUp(resolutionsInFile, name); + return result ? { resolvedFileName: result } : undefined; + }); + }; + } + } + LanguageServiceShimHostAdapter.prototype.log = function (s) { + if (this.loggingEnabled) { + this.shimHost.log(s); + } + }; + LanguageServiceShimHostAdapter.prototype.trace = function (s) { + if (this.tracingEnabled) { + this.shimHost.trace(s); + } + }; + LanguageServiceShimHostAdapter.prototype.error = function (s) { + this.shimHost.error(s); + }; + LanguageServiceShimHostAdapter.prototype.getProjectVersion = function () { + if (!this.shimHost.getProjectVersion) { + // shimmed host does not support getProjectVersion + return undefined; + } + return this.shimHost.getProjectVersion(); + }; + LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { + return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; + }; + LanguageServiceShimHostAdapter.prototype.getCompilationSettings = function () { + var settingsJson = this.shimHost.getCompilationSettings(); + // TODO: should this be '==='? + if (settingsJson == null || settingsJson == "") { + throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings"); + return null; + } + return JSON.parse(settingsJson); + }; + LanguageServiceShimHostAdapter.prototype.getScriptFileNames = function () { + var encoded = this.shimHost.getScriptFileNames(); + return this.files = JSON.parse(encoded); + }; + LanguageServiceShimHostAdapter.prototype.getScriptSnapshot = function (fileName) { + // Shim the API changes for 1.5 release. This should be removed once + // TypeScript 1.5 has shipped. + if (this.files && this.files.indexOf(fileName) < 0) { + return undefined; + } + var scriptSnapshot = this.shimHost.getScriptSnapshot(fileName); + return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot); + }; + LanguageServiceShimHostAdapter.prototype.getScriptVersion = function (fileName) { + return this.shimHost.getScriptVersion(fileName); + }; + LanguageServiceShimHostAdapter.prototype.getLocalizedDiagnosticMessages = function () { + var diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages(); + if (diagnosticMessagesJson == null || diagnosticMessagesJson == "") { + return null; + } + try { + return JSON.parse(diagnosticMessagesJson); + } + catch (e) { + this.log(e.description || "diagnosticMessages.generated.json has invalid JSON format"); + return null; + } + }; + LanguageServiceShimHostAdapter.prototype.getCancellationToken = function () { + var hostCancellationToken = this.shimHost.getCancellationToken(); + return new ThrottledCancellationToken(hostCancellationToken); + }; + LanguageServiceShimHostAdapter.prototype.getCurrentDirectory = function () { + return this.shimHost.getCurrentDirectory(); + }; + LanguageServiceShimHostAdapter.prototype.getDefaultLibFileName = function (options) { + // Wrap the API changes for 1.5 release. This try/catch + // should be removed once TypeScript 1.5 has shipped. + try { + return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); + } + catch (e) { + return ""; + } + }; + return LanguageServiceShimHostAdapter; + })(); + ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; + /** A cancellation that throttles calls to the host */ + var ThrottledCancellationToken = (function () { + function ThrottledCancellationToken(hostCancellationToken) { + this.hostCancellationToken = hostCancellationToken; + // Store when we last tried to cancel. Checking cancellation can be expensive (as we have + // to marshall over to the host layer). So we only bother actually checking once enough + // time has passed. + this.lastCancellationCheckTime = 0; + } + ThrottledCancellationToken.prototype.isCancellationRequested = function () { + var time = Date.now(); + var duration = Math.abs(time - this.lastCancellationCheckTime); + if (duration > 10) { + // Check no more than once every 10 ms. + this.lastCancellationCheckTime = time; + return this.hostCancellationToken.isCancellationRequested(); + } + return false; + }; + return ThrottledCancellationToken; + })(); + var CoreServicesShimHostAdapter = (function () { + function CoreServicesShimHostAdapter(shimHost) { + this.shimHost = shimHost; + } + CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extension, exclude) { + // Wrap the API changes for 1.5 release. This try/catch + // should be removed once TypeScript 1.5 has shipped. + // Also consider removing the optional designation for + // the exclude param at this time. + var encoded; + try { + encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); + } + catch (e) { + encoded = this.shimHost.readDirectory(rootDir, extension); + } + return JSON.parse(encoded); + }; + CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { + return this.shimHost.fileExists(fileName); + }; + CoreServicesShimHostAdapter.prototype.readFile = function (fileName) { + return this.shimHost.readFile(fileName); + }; + return CoreServicesShimHostAdapter; + })(); + ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; + function simpleForwardCall(logger, actionDescription, action, logPerformance) { + if (logPerformance) { + logger.log(actionDescription); + var start = Date.now(); + } + var result = action(); + if (logPerformance) { + var end = Date.now(); + logger.log(actionDescription + " completed in " + (end - start) + " msec"); + if (typeof (result) === "string") { + var str = result; + if (str.length > 128) { + str = str.substring(0, 128) + "..."; + } + logger.log(" result.length=" + str.length + ", result='" + JSON.stringify(str) + "'"); + } + } + return result; + } + function forwardJSONCall(logger, actionDescription, action, logPerformance) { + try { + var result = simpleForwardCall(logger, actionDescription, action, logPerformance); + return JSON.stringify({ result: result }); + } + catch (err) { + if (err instanceof ts.OperationCanceledException) { + return JSON.stringify({ canceled: true }); + } + logInternalError(logger, err); + err.description = actionDescription; + return JSON.stringify({ error: err }); + } + } + var ShimBase = (function () { + function ShimBase(factory) { + this.factory = factory; + factory.registerShim(this); + } + ShimBase.prototype.dispose = function (dummy) { + this.factory.unregisterShim(this); + }; + return ShimBase; + })(); + function realizeDiagnostics(diagnostics, newLine) { + return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); + } + ts.realizeDiagnostics = realizeDiagnostics; + function realizeDiagnostic(diagnostic, newLine) { + return { + message: ts.flattenDiagnosticMessageText(diagnostic.messageText, newLine), + start: diagnostic.start, + length: diagnostic.length, + /// TODO: no need for the tolowerCase call + category: ts.DiagnosticCategory[diagnostic.category].toLowerCase(), + code: diagnostic.code + }; + } + var LanguageServiceShimObject = (function (_super) { + __extends(LanguageServiceShimObject, _super); + function LanguageServiceShimObject(factory, host, languageService) { + _super.call(this, factory); + this.host = host; + this.languageService = languageService; + this.logPerformance = false; + this.logger = this.host; + } + LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); + }; + /// DISPOSE + /** + * Ensure (almost) deterministic release of internal Javascript resources when + * some external native objects holds onto us (e.g. Com/Interop). + */ + LanguageServiceShimObject.prototype.dispose = function (dummy) { + this.logger.log("dispose()"); + this.languageService.dispose(); + this.languageService = null; + // force a GC + if (debugObjectHost && debugObjectHost.CollectGarbage) { + debugObjectHost.CollectGarbage(); + this.logger.log("CollectGarbage()"); + } + this.logger = null; + _super.prototype.dispose.call(this, dummy); + }; + /// REFRESH + /** + * Update the list of scripts known to the compiler + */ + LanguageServiceShimObject.prototype.refresh = function (throwOnError) { + this.forwardJSONCall("refresh(" + throwOnError + ")", function () { + return null; + }); + }; + LanguageServiceShimObject.prototype.cleanupSemanticCache = function () { + var _this = this; + this.forwardJSONCall("cleanupSemanticCache()", function () { + _this.languageService.cleanupSemanticCache(); + return null; + }); + }; + LanguageServiceShimObject.prototype.realizeDiagnostics = function (diagnostics) { + var newLine = ts.getNewLineOrDefaultFromHost(this.host); + return ts.realizeDiagnostics(diagnostics, newLine); + }; + LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { + var classifications = _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); + return classifications; + }); + }; + LanguageServiceShimObject.prototype.getSemanticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { + var classifications = _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); + return classifications; + }); + }; + LanguageServiceShimObject.prototype.getEncodedSyntacticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); + }); + }; + LanguageServiceShimObject.prototype.getEncodedSemanticClassifications = function (fileName, start, length) { + var _this = this; + return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); + }); + }; + LanguageServiceShimObject.prototype.getSyntacticDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSyntacticDiagnostics('" + fileName + "')", function () { + var diagnostics = _this.languageService.getSyntacticDiagnostics(fileName); + return _this.realizeDiagnostics(diagnostics); + }); + }; + LanguageServiceShimObject.prototype.getSemanticDiagnostics = function (fileName) { + var _this = this; + return this.forwardJSONCall("getSemanticDiagnostics('" + fileName + "')", function () { + var diagnostics = _this.languageService.getSemanticDiagnostics(fileName); + return _this.realizeDiagnostics(diagnostics); + }); + }; + LanguageServiceShimObject.prototype.getCompilerOptionsDiagnostics = function () { + var _this = this; + return this.forwardJSONCall("getCompilerOptionsDiagnostics()", function () { + var diagnostics = _this.languageService.getCompilerOptionsDiagnostics(); + return _this.realizeDiagnostics(diagnostics); + }); + }; + /// QUICKINFO + /** + * Computes a string representation of the type at the requested position + * in the active file. + */ + LanguageServiceShimObject.prototype.getQuickInfoAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { + var quickInfo = _this.languageService.getQuickInfoAtPosition(fileName, position); + return quickInfo; + }); + }; + /// NAMEORDOTTEDNAMESPAN + /** + * Computes span information of the name or dotted name at the requested position + * in the active file. + */ + LanguageServiceShimObject.prototype.getNameOrDottedNameSpan = function (fileName, startPos, endPos) { + var _this = this; + return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { + var spanInfo = _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); + return spanInfo; + }); + }; + /** + * STATEMENTSPAN + * Computes span information of statement at the requested position in the active file. + */ + LanguageServiceShimObject.prototype.getBreakpointStatementAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { + var spanInfo = _this.languageService.getBreakpointStatementAtPosition(fileName, position); + return spanInfo; + }); + }; + /// SIGNATUREHELP + LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { + var signatureInfo = _this.languageService.getSignatureHelpItems(fileName, position); + return signatureInfo; + }); + }; + /// GOTO DEFINITION + /** + * Computes the definition location and file for the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getDefinitionAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { + return _this.languageService.getDefinitionAtPosition(fileName, position); + }); + }; + /// GOTO Type + /** + * Computes the definition location of the type of the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { + return _this.languageService.getTypeDefinitionAtPosition(fileName, position); + }); + }; + LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { + return _this.languageService.getRenameInfo(fileName, position); + }); + }; + LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments) { + var _this = this; + return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { + return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); + }); + }; + /// GET BRACE MATCHING + LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { + var textRanges = _this.languageService.getBraceMatchingAtPosition(fileName, position); + return textRanges; + }); + }; + /// GET SMART INDENT + LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options /*Services.EditorOptions*/) { + var _this = this; + return this.forwardJSONCall("getIndentationAtPosition('" + fileName + "', " + position + ")", function () { + var localOptions = JSON.parse(options); + return _this.languageService.getIndentationAtPosition(fileName, position, localOptions); + }); + }; + /// GET REFERENCES + LanguageServiceShimObject.prototype.getReferencesAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { + return _this.languageService.getReferencesAtPosition(fileName, position); + }); + }; + LanguageServiceShimObject.prototype.findReferences = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { + return _this.languageService.findReferences(fileName, position); + }); + }; + LanguageServiceShimObject.prototype.getOccurrencesAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { + return _this.languageService.getOccurrencesAtPosition(fileName, position); + }); + }; + LanguageServiceShimObject.prototype.getDocumentHighlights = function (fileName, position, filesToSearch) { + var _this = this; + return this.forwardJSONCall("getDocumentHighlights('" + fileName + "', " + position + ")", function () { + var results = _this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch)); + // workaround for VS document higlighting issue - keep only items from the initial file + var normalizedName = ts.normalizeSlashes(fileName).toLowerCase(); + return ts.filter(results, function (r) { return ts.normalizeSlashes(r.fileName).toLowerCase() === normalizedName; }); + }); + }; + /// COMPLETION LISTS + /** + * Get a string based representation of the completions + * to provide at the given source position and providing a member completion + * list if requested. + */ + LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { + var completion = _this.languageService.getCompletionsAtPosition(fileName, position); + return completion; + }); + }; + /** Get a string based representation of a completion list entry details */ + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName) { + var _this = this; + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", " + entryName + ")", function () { + var details = _this.languageService.getCompletionEntryDetails(fileName, position, entryName); + return details; + }); + }; + LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { + var _this = this; + return this.forwardJSONCall("getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")", function () { + var localOptions = JSON.parse(options); + var edits = _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); + return edits; + }); + }; + LanguageServiceShimObject.prototype.getFormattingEditsForDocument = function (fileName, options /*Services.FormatCodeOptions*/) { + var _this = this; + return this.forwardJSONCall("getFormattingEditsForDocument('" + fileName + "')", function () { + var localOptions = JSON.parse(options); + var edits = _this.languageService.getFormattingEditsForDocument(fileName, localOptions); + return edits; + }); + }; + LanguageServiceShimObject.prototype.getFormattingEditsAfterKeystroke = function (fileName, position, key, options /*Services.FormatCodeOptions*/) { + var _this = this; + return this.forwardJSONCall("getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')", function () { + var localOptions = JSON.parse(options); + var edits = _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); + return edits; + }); + }; + LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position); }); + }; + /// NAVIGATE TO + /** Return a list of symbols that are interesting to navigate to */ + LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount) { + var _this = this; + return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ")", function () { + var items = _this.languageService.getNavigateToItems(searchValue, maxResultCount); + return items; + }); + }; + LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { + var items = _this.languageService.getNavigationBarItems(fileName); + return items; + }); + }; + LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { + var _this = this; + return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { + var items = _this.languageService.getOutliningSpans(fileName); + return items; + }); + }; + LanguageServiceShimObject.prototype.getTodoComments = function (fileName, descriptors) { + var _this = this; + return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { + var items = _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); + return items; + }); + }; + /// Emit + LanguageServiceShimObject.prototype.getEmitOutput = function (fileName) { + var _this = this; + return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { + var output = _this.languageService.getEmitOutput(fileName); + // Shim the API changes for 1.5 release. This should be removed once + // TypeScript 1.5 has shipped. + output.emitOutputStatus = output.emitSkipped ? 1 : 0; + return output; + }); + }; + return LanguageServiceShimObject; + })(ShimBase); + function convertClassifications(classifications) { + return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState }; + } + var ClassifierShimObject = (function (_super) { + __extends(ClassifierShimObject, _super); + function ClassifierShimObject(factory, logger) { + _super.call(this, factory); + this.logger = logger; + this.logPerformance = false; + this.classifier = ts.createClassifier(); + } + ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { + var _this = this; + return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance); + }; + /// COLORIZATION + ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { + var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); + var items = classification.entries; + var result = ""; + for (var i = 0; i < items.length; i++) { + result += items[i].length + "\n"; + result += items[i].classification + "\n"; + } + result += classification.finalLexState; + return result; + }; + return ClassifierShimObject; + })(ShimBase); + var CoreServicesShimObject = (function (_super) { + __extends(CoreServicesShimObject, _super); + function CoreServicesShimObject(factory, logger, host) { + _super.call(this, factory); + this.logger = logger; + this.host = host; + this.logPerformance = false; + } + CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { + return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); + }; + CoreServicesShimObject.prototype.resolveModuleName = function (fileName, moduleName, compilerOptionsJson) { + var _this = this; + return this.forwardJSONCall("resolveModuleName('" + fileName + "')", function () { + var compilerOptions = JSON.parse(compilerOptionsJson); + var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); + return { + resolvedFileName: result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined, + failedLookupLocations: result.failedLookupLocations + }; + }); + }; + CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) { + return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { + var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength())); + var convertResult = { + referencedFiles: [], + importedFiles: [], + ambientExternalModules: result.ambientExternalModules, + isLibFile: result.isLibFile + }; + ts.forEach(result.referencedFiles, function (refFile) { + convertResult.referencedFiles.push({ + path: ts.normalizePath(refFile.fileName), + position: refFile.pos, + length: refFile.end - refFile.pos + }); + }); + ts.forEach(result.importedFiles, function (importedFile) { + convertResult.importedFiles.push({ + path: ts.normalizeSlashes(importedFile.fileName), + position: importedFile.pos, + length: importedFile.end - importedFile.pos + }); + }); + return convertResult; + }); + }; + CoreServicesShimObject.prototype.getTSConfigFileInfo = function (fileName, sourceTextSnapshot) { + var _this = this; + return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () { + var text = sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()); + var result = ts.parseConfigFileTextToJson(fileName, text); + if (result.error) { + return { + options: {}, + files: [], + errors: [realizeDiagnostic(result.error, '\r\n')] + }; + } + var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(ts.normalizeSlashes(fileName))); + return { + options: configFile.options, + files: configFile.fileNames, + errors: realizeDiagnostics(configFile.errors, '\r\n') + }; + }); + }; + CoreServicesShimObject.prototype.getDefaultCompilationSettings = function () { + return this.forwardJSONCall("getDefaultCompilationSettings()", function () { + return ts.getDefaultCompilerOptions(); + }); + }; + return CoreServicesShimObject; + })(ShimBase); + var TypeScriptServicesFactory = (function () { + function TypeScriptServicesFactory() { + this._shims = []; + } + /* + * Returns script API version. + */ + TypeScriptServicesFactory.prototype.getServicesVersion = function () { + return ts.servicesVersion; + }; + TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) { + try { + if (this.documentRegistry === undefined) { + this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + } + var hostAdapter = new LanguageServiceShimHostAdapter(host); + var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry); + return new LanguageServiceShimObject(this, host, languageService); + } + catch (err) { + logInternalError(host, err); + throw err; + } + }; + TypeScriptServicesFactory.prototype.createClassifierShim = function (logger) { + try { + return new ClassifierShimObject(this, logger); + } + catch (err) { + logInternalError(logger, err); + throw err; + } + }; + TypeScriptServicesFactory.prototype.createCoreServicesShim = function (host) { + try { + var adapter = new CoreServicesShimHostAdapter(host); + return new CoreServicesShimObject(this, host, adapter); + } + catch (err) { + logInternalError(host, err); + throw err; + } + }; + TypeScriptServicesFactory.prototype.close = function () { + // Forget all the registered shims + this._shims = []; + this.documentRegistry = ts.createDocumentRegistry(); + }; + TypeScriptServicesFactory.prototype.registerShim = function (shim) { + this._shims.push(shim); + }; + TypeScriptServicesFactory.prototype.unregisterShim = function (shim) { + for (var i = 0, n = this._shims.length; i < n; i++) { + if (this._shims[i] === shim) { + delete this._shims[i]; + return; + } + } + throw new Error("Invalid operation"); + }; + return TypeScriptServicesFactory; + })(); + ts.TypeScriptServicesFactory = TypeScriptServicesFactory; + if (typeof module !== "undefined" && module.exports) { + module.exports = ts; + } +})(ts || (ts = {})); +/// TODO: this is used by VS, clean this up on both sides of the interface +/* @internal */ +var TypeScript; +(function (TypeScript) { + var Services; + (function (Services) { + Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; + })(Services = TypeScript.Services || (TypeScript.Services = {})); +})(TypeScript || (TypeScript = {})); +/* @internal */ +var toolsVersion = "1.7"; diff --git a/testapp/ng2/styles.css b/testapp/ng2/styles.css new file mode 100644 index 000000000..560c36fc7 --- /dev/null +++ b/testapp/ng2/styles.css @@ -0,0 +1,10 @@ +body { + font-family:"Roboto","Helvetica Neue Light","Helvetica Neue",Helvetica,Arial,"Lucida Grande",sans-serif; + font-size:14px;color:#1a2326 +} +.container { + padding-left: 20px; +} +.nav { + padding-bottom: 20px; +} From 9532779dd340b6db860b9aed3beca3a3673e51e4 Mon Sep 17 00:00:00 2001 From: Craig Nishina Date: Mon, 25 Jan 2016 13:57:43 -0800 Subject: [PATCH 061/678] chore(test): fix wait time out error for async angular2 periodic increments test --- spec/ng2/async_spec.js | 45 ++++++++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/spec/ng2/async_spec.js b/spec/ng2/async_spec.js index c4c91a01c..51772db41 100644 --- a/spec/ng2/async_spec.js +++ b/spec/ng2/async_spec.js @@ -55,26 +55,29 @@ describe('async angular2 application', function() { expect(timeout.$('.val').getText()).toEqual('10'); }); - it('should wait for a series of periodic increments', function() { - var timeout = $('#periodicIncrement'); - - // Waits for the val to count to 1 and 2. - var EC = protractor.ExpectedConditions; - timeout.$('.action').click(); - browser.wait(EC.textToBePresentInElement(timeout.$('.val'), '1'), 3000); - timeout.$('.cancel').click(); - - var text = timeout.$('.val').getText(); - browser.driver.sleep(3000); - expect(timeout.$('.val').getText()).toEqual(text); - - timeout.$('.action').click(); - browser.wait(EC.textToBePresentInElement(timeout.$('.val'), '3'), 6000); - timeout.$('.cancel').click(); - - text = timeout.$('.val').getText(); - browser.driver.sleep(3000); - expect(timeout.$('.val').getText()).toEqual(text); - + describe('long async spec', function() { + var originalTimeout; + beforeEach(function() { + originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; + jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000; + }); + + it('should wait for a series of periodic increments', function() { + var timeout = $('#periodicIncrement'); + + // Waits for the val to count 2. + var EC = protractor.ExpectedConditions; + timeout.$('.action').click(); + browser.wait(EC.textToBePresentInElement(timeout.$('.val'), '1'), 4000); + timeout.$('.cancel').click(); + + var text = timeout.$('.val').getText(); + browser.driver.sleep(3000); + expect(timeout.$('.val').getText()).toEqual(text); + }); + + afterEach(function() { + jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; + }); }); }); From b6932560d66730203e0e7b0c65c80a44ad4747de Mon Sep 17 00:00:00 2001 From: Tim Roes Date: Fri, 22 Jan 2016 12:36:26 +0100 Subject: [PATCH 062/678] feat(webdriver): allow configuration of all SeleniumServer arguments You can now pass a complete object of configuration for the SeleniumServer class. This allows enabling loopback on the selenium server. --- docs/referenceConf.js | 4 ++++ lib/driverProviders/local.js | 19 ++++++++++++++----- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/docs/referenceConf.js b/docs/referenceConf.js index 27e141db7..44b8653f2 100644 --- a/docs/referenceConf.js +++ b/docs/referenceConf.js @@ -38,6 +38,10 @@ exports.config = { // seleniumArgs: ['-browserTimeout=60'] // Ignored if seleniumServerJar is null. seleniumArgs: [], + // Can be an object which will be passed to the SeleniumServer class as args. + // If you specify `args` or `port` in this object, it will overwrite the values + // set via `seleniumPort` and `seleniumArgs`. + localSeleniumStandaloneOpts: null, // ChromeDriver location is used to help find the chromedriver binary. // This will be passed to the Selenium jar as the system property // webdriver.chrome.driver. If null, Selenium will diff --git a/lib/driverProviders/local.js b/lib/driverProviders/local.js index c1e37e7d2..6de6ae573 100644 --- a/lib/driverProviders/local.js +++ b/lib/driverProviders/local.js @@ -72,15 +72,24 @@ LocalDriverProvider.prototype.setupEnv = function() { log.puts('Starting selenium standalone server...'); + var serverConf = this.config_.localSeleniumStandaloneOpts || {}; + + // If args or port is not set use seleniumArgs and seleniumPort + // for backward compatibility + if (serverConf.args === undefined) { + serverConf.args = this.config_.seleniumArgs || []; + } + if (serverConf.port === undefined) { + serverConf.port = this.config_.seleniumPort; + } + // configure server if (this.config_.chromeDriver) { - this.config_.seleniumArgs.push('-Dwebdriver.chrome.driver=' + + serverConf.args.push('-Dwebdriver.chrome.driver=' + this.config_.chromeDriver); } - this.server_ = new remote.SeleniumServer(this.config_.seleniumServerJar, { - args: this.config_.seleniumArgs, - port: this.config_.seleniumPort - }); + + this.server_ = new remote.SeleniumServer(this.config_.seleniumServerJar, serverConf); //start local server, grab hosted address, and resolve promise this.server_.start().then(function(url) { From 261b49e1129e0288215d865d5953872c4839877a Mon Sep 17 00:00:00 2001 From: Julie Ralph Date: Tue, 26 Jan 2016 22:32:14 -0800 Subject: [PATCH 063/678] docs(config): add full list of local selenium server args Also, deprecate seleniumPort and seleniumArgs. --- docs/referenceConf.js | 22 ++++++++++++---------- lib/configParser.js | 1 - 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/docs/referenceConf.js b/docs/referenceConf.js index 44b8653f2..aed68ffcc 100644 --- a/docs/referenceConf.js +++ b/docs/referenceConf.js @@ -30,18 +30,20 @@ exports.config = { // Server is found, this will default to // node_modules/protractor/selenium/selenium-server... seleniumServerJar: null, - // The port to start the Selenium Server on, or null if the server should - // find its own unused port. Ignored if seleniumServerJar is null. - seleniumPort: null, - // Additional command line options to pass to selenium. For example, - // if you need to change the browser timeout, use - // seleniumArgs: ['-browserTimeout=60'] - // Ignored if seleniumServerJar is null. - seleniumArgs: [], // Can be an object which will be passed to the SeleniumServer class as args. + // See a full list of options at + // https://github.com/SeleniumHQ/selenium/blob/master/javascript/node/selenium-webdriver/remote/index.js // If you specify `args` or `port` in this object, it will overwrite the values - // set via `seleniumPort` and `seleniumArgs`. - localSeleniumStandaloneOpts: null, + // set via the deprecated config values `seleniumPort` and `seleniumArgs`. + localSeleniumStandaloneOpts: { + // The port to start the Selenium Server on, or null if the server should + // find its own unused port. + port: null, + // Additional command line options to pass to selenium. For example, + // if you need to change the browser timeout, use + // seleniumArgs: ['-browserTimeout=60'] + args: [] + }, // ChromeDriver location is used to help find the chromedriver binary. // This will be passed to the Selenium jar as the system property // webdriver.chrome.driver. If null, Selenium will diff --git a/lib/configParser.js b/lib/configParser.js index 2a58a56bd..0a84d5583 100644 --- a/lib/configParser.js +++ b/lib/configParser.js @@ -32,7 +32,6 @@ var ConfigParser = function() { stackFilter: helper.filterStackTrace, defaultTimeoutInterval: (30 * 1000) }, - seleniumArgs: [], mochaOpts: { ui: 'bdd', reporter: 'list' From 3f3805f9496fb130ae01b3e3278ee1ea7684d8e7 Mon Sep 17 00:00:00 2001 From: Craig Nishina Date: Wed, 27 Jan 2016 15:44:16 -0800 Subject: [PATCH 064/678] feat(attachSession): attach protractor to existing webdriver session Attaching an existing selenium browser session to protractor rather than always creating new one. The session can be passed into the config file as a string via the sessionId. --- docs/referenceConf.js | 4 + lib/cli.js | 1 + lib/configParser.js | 2 + lib/driverProviders/attachSession.js | 58 ++++++++++ lib/runner.js | 6 +- scripts/attachSession.js | 105 ++++++++++++++++++ scripts/test.js | 1 + spec/attachSession.js | 21 ++++ .../attachSession_spec.js | 11 ++ 9 files changed, 208 insertions(+), 1 deletion(-) create mode 100644 lib/driverProviders/attachSession.js create mode 100644 scripts/attachSession.js create mode 100644 spec/attachSession.js create mode 100644 spec/attachSessionProvider/attachSession_spec.js diff --git a/docs/referenceConf.js b/docs/referenceConf.js index aed68ffcc..4c633b928 100644 --- a/docs/referenceConf.js +++ b/docs/referenceConf.js @@ -55,6 +55,10 @@ exports.config = { // connect to an already running instance of Selenium. This usually looks like // seleniumAddress: 'http://localhost:4444/wd/hub' seleniumAddress: null, + // The selenium session id allows Protractor to attach to an existing selenium + // browser session. The selenium session is maintained after the test has + // completed. Ignored if seleniumAddress is null. + seleniumSessionId: null, // ---- 3. To use remote browsers via Sauce Labs ----------------------------- // If sauceUser and sauceKey are specified, seleniumServerJar will be ignored. diff --git a/lib/cli.js b/lib/cli.js index 6a2ac66c7..2742d9b07 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -39,6 +39,7 @@ var optimist = require('optimist'). describe('version', 'Print Protractor version'). describe('browser', 'Browsername, e.g. chrome or firefox'). describe('seleniumAddress', 'A running selenium address to use'). + describe('seleniumSessionId', 'Attaching an existing session id'). describe('seleniumServerJar', 'Location of the standalone selenium jar file'). describe('seleniumPort', 'Optional port for the selenium standalone server'). describe('baseUrl', 'URL to prepend to all relative paths'). diff --git a/lib/configParser.js b/lib/configParser.js index 0a84d5583..69d197a4b 100644 --- a/lib/configParser.js +++ b/lib/configParser.js @@ -32,6 +32,8 @@ var ConfigParser = function() { stackFilter: helper.filterStackTrace, defaultTimeoutInterval: (30 * 1000) }, + seleniumArgs: [], + seleniumSessionId: null, mochaOpts: { ui: 'bdd', reporter: 'list' diff --git a/lib/driverProviders/attachSession.js b/lib/driverProviders/attachSession.js new file mode 100644 index 000000000..99195b6e3 --- /dev/null +++ b/lib/driverProviders/attachSession.js @@ -0,0 +1,58 @@ +/* + * This is an implementation of the Attach Session Driver Provider. + * It is responsible for setting up the account object, tearing + * it down, and setting up the driver correctly. + */ + +var util = require('util'), + q = require('q'), + DriverProvider = require('./driverProvider'), + log = require('../logger'), + webdriver = require('selenium-webdriver'), + executors = require('selenium-webdriver/executors'); + +var AttachedSessionDriverProvider = function(config) { + DriverProvider.call(this, config); +}; +util.inherits(AttachedSessionDriverProvider, DriverProvider); + +/** + * Configure and launch (if applicable) the object's environment. + * @public + * @return {q.promise} A promise which will resolve when the environment is + * ready to test. + */ +AttachedSessionDriverProvider.prototype.setupEnv = function() { + log.puts('Using the selenium server at ' + this.config_.seleniumAddress); + log.puts('Using session id - ' + this.config_.seleniumSessionId); + return q(undefined); +}; + + +/** + * Getting a new driver by attaching an existing session. + * + * @public + * @return {webdriver.WebDriver} webdriver instance + */ +AttachedSessionDriverProvider.prototype.getNewDriver = function() { + var executor = executors.createExecutor(this.config_.seleniumAddress); + var newDriver; + newDriver = new webdriver.WebDriver + .attachToSession(executor, this.config_.seleniumSessionId); + this.drivers_.push(newDriver); + return newDriver; +}; + +/** + * Maintains the existing session and does not quit the driver. + * + * @public + */ +AttachedSessionDriverProvider.prototype.quitDriver = function() { +}; + +// new instance w/ each include +module.exports = function(config) { + return new AttachedSessionDriverProvider(config); +}; diff --git a/lib/runner.js b/lib/runner.js index eeb99a579..51a4b73d9 100644 --- a/lib/runner.js +++ b/lib/runner.js @@ -93,7 +93,11 @@ Runner.prototype.loadDriverProvider_ = function() { if (this.config_.directConnect) { runnerPath = './driverProviders/direct'; } else if (this.config_.seleniumAddress) { - runnerPath = './driverProviders/hosted'; + if (this.config_.seleniumSessionId) { + runnerPath = './driverProviders/attachSession'; + } else { + runnerPath = './driverProviders/hosted'; + } } else if (this.config_.browserstackUser && this.config_.browserstackKey) { runnerPath = './driverProviders/browserstack'; } else if (this.config_.sauceUser && this.config_.sauceKey) { diff --git a/scripts/attachSession.js b/scripts/attachSession.js new file mode 100644 index 000000000..58822b8d5 --- /dev/null +++ b/scripts/attachSession.js @@ -0,0 +1,105 @@ +#!/usr/bin/env node + +'use strict'; + +var http = require('http'), + spawn = require('child_process').spawnSync; + +var sessionId = ''; + +// 1. Create a new selenium session. +var postData = JSON.stringify( + {'desiredCapabilities': {'browserName': 'firefox'}}); +var createOptions = { + hostname: 'localhost', + port: 4444, + path: '/wd/hub/session', + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Content-Length': Buffer.byteLength(postData) + } +}; +var req = http.request(createOptions, function(res) { + res.on('data', setBody); + res.on('end', checkSession); +}); +req.write(postData); +req.end(); + +// 2. After making the request to create a selenium session, read the selenium +// session id. +var setBody = function(chunk) { + var body = chunk.toString(); + sessionId = JSON.parse(body).sessionId; +}; + +// 3. After getting the session id, verify that the selenium session exists. +// If the session exists, run the protractor test. +var checkSession = function() { + var checkOptions = { + hostname: 'localhost', + port: 4444, + path: '/wd/hub/session/' + sessionId, + method: 'GET' + }; + var state = ''; + var req = http.request(checkOptions, function(res) { + res.on('data', function(chunk) { + state = JSON.parse(chunk.toString()).state; + }); + res.on('end', function() { + if (state === 'success') { + var runProtractor = spawn('bin/protractor', + ['spec/attachSession.js', '--seleniumSessionId=' + sessionId]); + console.log(runProtractor.stdout.toString()); + if (runProtractor.status !== 0) { + throw new Error('Protractor did not run properly.'); + } + } + else { + throw new Error('The selenium session was not created.'); + } + checkStoppedSession(); + }); + }); + req.end(); +}; + +// 4. After the protractor test completes, check to see that the session still +// exists. If we can find the session, delete it. +var checkStoppedSession = function() { + var checkOptions = { + hostname: 'localhost', + port: 4444, + path: '/wd/hub/session/' + sessionId, + method: 'GET' + }; + var state = ''; + var req = http.request(checkOptions, function(res) { + res.on('data', function(chunk) { + state = JSON.parse(chunk.toString()).state; + }); + res.on('end', function() { + if (state === 'success') { + deleteSession(); + } + else { + throw new Error('The selenium session should still exist.'); + } + }); + }); + req.end(); +}; + +// 5. Delete the selenium session. +var deleteSession = function() { + var deleteOptions = { + hostname: 'localhost', + port: 4444, + path: '/wd/hub/session/' + sessionId, + method: 'DELETE' + }; + var req = http.request(deleteOptions); + req.end(); +}; diff --git a/scripts/test.js b/scripts/test.js index 0df3988c0..8858fa823 100755 --- a/scripts/test.js +++ b/scripts/test.js @@ -32,6 +32,7 @@ var passingTests = [ 'node lib/cli.js spec/controlLockConf.js', 'node lib/cli.js spec/customFramework.js', 'node lib/cli.js spec/angular2Conf.js', + 'node scripts/attachSession.js', 'node scripts/interactive_tests/interactive_test.js', 'node scripts/interactive_tests/with_base_url.js', // Unit tests diff --git a/spec/attachSession.js b/spec/attachSession.js new file mode 100644 index 000000000..694977e67 --- /dev/null +++ b/spec/attachSession.js @@ -0,0 +1,21 @@ +var env = require('./environment.js'); + +exports.config = { + seleniumAddress: env.seleniumAddress, + + framework: 'jasmine', + + specs: [ + 'attachSessionProvider/attachSession_spec.js' + ], + + capabilities: env.capabilities, + + baseUrl: 'http://localhost:8081', + + // Special option for Angular2, to test against all Angular2 applications + // on the page. This means that Protractor will wait for every app to be + // stable before each action, and search within all apps when finding + // elements. + useAllAngular2AppRoots: true +}; diff --git a/spec/attachSessionProvider/attachSession_spec.js b/spec/attachSessionProvider/attachSession_spec.js new file mode 100644 index 000000000..e69bc614c --- /dev/null +++ b/spec/attachSessionProvider/attachSession_spec.js @@ -0,0 +1,11 @@ +describe('selenium session id', function() { + var URL = '/ng2/#/async'; + + beforeEach(function() { + browser.get(URL); + }); + it('should be able to use an existing session', function() { + var increment = $('#increment'); + expect(increment).toBeDefined(); + }); +}); From aa5ceb576f0283b6591faaa95e342ef3c603c717 Mon Sep 17 00:00:00 2001 From: Vito Liloia Date: Mon, 25 Jan 2016 17:17:45 +0100 Subject: [PATCH 065/678] feat(webdriver): add support for selenium webdriver proxy --- docs/referenceConf.js | 4 ++++ lib/driverProviders/driverProvider.js | 1 + 2 files changed, 5 insertions(+) diff --git a/docs/referenceConf.js b/docs/referenceConf.js index 4c633b928..288a424aa 100644 --- a/docs/referenceConf.js +++ b/docs/referenceConf.js @@ -59,6 +59,10 @@ exports.config = { // browser session. The selenium session is maintained after the test has // completed. Ignored if seleniumAddress is null. seleniumSessionId: null, + // The address of a proxy server to use for the connection to the + // Selenium Server. If not specified no proxy is configured. Looks like + // webDriverProxy: 'http://localhost:3128' + webDriverProxy: null, // ---- 3. To use remote browsers via Sauce Labs ----------------------------- // If sauceUser and sauceKey are specified, seleniumServerJar will be ignored. diff --git a/lib/driverProviders/driverProvider.js b/lib/driverProviders/driverProvider.js index 55f4785b4..ba2e2df10 100644 --- a/lib/driverProviders/driverProvider.js +++ b/lib/driverProviders/driverProvider.js @@ -34,6 +34,7 @@ DriverProvider.prototype.getExistingDrivers = function() { DriverProvider.prototype.getNewDriver = function() { var builder = new webdriver.Builder(). usingServer(this.config_.seleniumAddress). + usingWebDriverProxy(this.config_.webDriverProxy). withCapabilities(this.config_.capabilities); if (this.config_.disableEnvironmentOverrides === true) { builder.disableEnvironmentOverrides(); From 4b792280cc4c7f11b652e67123610c2b1880acf5 Mon Sep 17 00:00:00 2001 From: Craig Nishina Date: Fri, 29 Jan 2016 12:39:28 -0800 Subject: [PATCH 066/678] chore(test): fix npm test to install missing prerequisites --- package.json | 2 +- scripts/pretest.sh | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) create mode 100755 scripts/pretest.sh diff --git a/package.json b/package.json index 1d8c0cee7..c02060011 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,7 @@ }, "main": "lib/protractor.js", "scripts": { - "pretest": "node_modules/.bin/jshint lib spec scripts", + "pretest": "./scripts/pretest.sh", "test": "node scripts/test.js", "start": "node testapp/scripts/web-server.js" }, diff --git a/scripts/pretest.sh b/scripts/pretest.sh new file mode 100755 index 000000000..cd380d4c4 --- /dev/null +++ b/scripts/pretest.sh @@ -0,0 +1,7 @@ +#!/bin/bash +# When running `npm test`, this script is intended to run during pretest step. + +WS=$(pwd) # the protractor directory +$WS/bin/webdriver-manager update # updates the local webdriver manager +$WS/node_modules/.bin/jshint lib spec scripts +cd $WS/website && npm install # installs dependencies for the website From fa0c692414fa98721dff80202ef95e9b3ccadebb Mon Sep 17 00:00:00 2001 From: Sammy Jelin Date: Fri, 29 Jan 2016 17:46:16 -0800 Subject: [PATCH 067/678] feat(config): allow onComplete to return a promise Closes #1944 --- docs/referenceConf.js | 2 ++ lib/frameworks/README.md | 2 ++ lib/frameworks/jasmine.js | 11 +++++++---- lib/frameworks/mocha.js | 11 +++++++---- 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/docs/referenceConf.js b/docs/referenceConf.js index 288a424aa..2ba5b6282 100644 --- a/docs/referenceConf.js +++ b/docs/referenceConf.js @@ -248,6 +248,8 @@ exports.config = { }, // A callback function called once tests are finished. + // onComplete can optionally return a promise, which Protractor will wait for + // before shutting down webdriver. onComplete: function() { // At this point, tests will be done but global objects will still be // available. diff --git a/lib/frameworks/README.md b/lib/frameworks/README.md index 7db48c1df..7ba6f8bc7 100644 --- a/lib/frameworks/README.md +++ b/lib/frameworks/README.md @@ -28,6 +28,8 @@ Requirements - `runner.runTestPreparer` must be called before any tests are run. - `runner.getConfig().onComplete` must be called when tests are finished. + It might return a promise, in which case `exports.run`'s promise should not + resolve until after `onComplete`'s promise resolves. - The returned promise must be resolved when tests are finished and it should return a results object. This object must have a `failedCount` property and optionally a `specResults` object of the following structure: diff --git a/lib/frameworks/jasmine.js b/lib/frameworks/jasmine.js index 0fe6a43d4..2670a586c 100644 --- a/lib/frameworks/jasmine.js +++ b/lib/frameworks/jasmine.js @@ -96,12 +96,15 @@ exports.run = function(runner, specs) { jrunner.onComplete(function(passed) { try { + var completed = q(); if (originalOnComplete) { - originalOnComplete(passed); + completed = q(originalOnComplete(passed)); } - resolve({ - failedCount: reporter.failedCount, - specResults: reporter.testResult + completed.then(function() { + resolve({ + failedCount: reporter.failedCount, + specResults: reporter.testResult + }); }); } catch (err) { reject(err); diff --git a/lib/frameworks/mocha.js b/lib/frameworks/mocha.js index 06711439d..b4ed629b6 100644 --- a/lib/frameworks/mocha.js +++ b/lib/frameworks/mocha.js @@ -52,12 +52,15 @@ exports.run = function(runner, specs) { var mochaRunner = mocha.run(function(failures) { try { + var completed = q(); if (runner.getConfig().onComplete) { - runner.getConfig().onComplete(); + completed = q(runner.getConfig().onComplete()); } - deferred.resolve({ - failedCount: failures, - specResults: testResult + completed.then(function() { + deferred.resolve({ + failedCount: failures, + specResults: testResult + }); }); } catch (err) { deferred.reject(err); From 7b371fcd9e47904dd6e3a226edc70292f08a2547 Mon Sep 17 00:00:00 2001 From: Prayag Verma Date: Tue, 2 Feb 2016 14:11:09 +0530 Subject: [PATCH 068/678] chore(docs): fix typos in page-objects.md Spelling mistake - Additionaly > Additionally --- docs/page-objects.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/page-objects.md b/docs/page-objects.md index 4524b97a8..20990952b 100644 --- a/docs/page-objects.md +++ b/docs/page-objects.md @@ -91,6 +91,6 @@ From the command line, you can then easily switch between running one or the oth protractor protractor.conf.js --suite homepage -Additionaly, you can run specific suites of tests with the command: +Additionally, you can run specific suites of tests with the command: protractor protractor.conf.js --suite homepage,search From 7ce4919740cfbc53dfd0e9c8e9c258af257e8381 Mon Sep 17 00:00:00 2001 From: Craig Nishina Date: Fri, 29 Jan 2016 12:39:28 -0800 Subject: [PATCH 069/678] chore(test): fix npm test to install missing prerequisites --- package.json | 4 +++- scripts/pretest.sh | 6 ++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index c02060011..ceea06720 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,9 @@ "mocha": "2.3.4", "express": "~4.13.3", "body-parser": "1.14.2", - "rimraf": "~2.5.0" + "rimraf": "~2.5.0", + "lodash": "^2.4.1", + "marked": "^0.3.3" }, "repository": { "type": "git", diff --git a/scripts/pretest.sh b/scripts/pretest.sh index cd380d4c4..f09d412ab 100755 --- a/scripts/pretest.sh +++ b/scripts/pretest.sh @@ -1,7 +1,5 @@ #!/bin/bash # When running `npm test`, this script is intended to run during pretest step. -WS=$(pwd) # the protractor directory -$WS/bin/webdriver-manager update # updates the local webdriver manager -$WS/node_modules/.bin/jshint lib spec scripts -cd $WS/website && npm install # installs dependencies for the website +bin/webdriver-manager update # updates the local webdriver manager +node_modules/.bin/jshint lib spec scripts From e0ef426395f2910ef1d4c1298c46caf58d8e11f6 Mon Sep 17 00:00:00 2001 From: Andres Dominguez Date: Sat, 6 Feb 2016 11:29:03 -0500 Subject: [PATCH 070/678] feat(website): Add style guide to the website Added style guide and e2e tests to the website. Fixed broken e2e tests --- website/index.html | 1 + website/js/routes.js | 4 ++++ website/test/e2e/api-page.js | 4 +++- website/test/e2e/api_spec.js | 11 ++++++----- website/test/e2e/navigation_spec.js | 7 +++++++ 5 files changed, 21 insertions(+), 6 deletions(-) diff --git a/website/index.html b/website/index.html index 5e36f3644..659868ee9 100644 --- a/website/index.html +++ b/website/index.html @@ -69,6 +69,7 @@