diff --git a/scripts/test.js b/scripts/test.js index 0985c321c..3fcb0ed5c 100755 --- a/scripts/test.js +++ b/scripts/test.js @@ -129,4 +129,10 @@ executor.addCommandlineTest('node built/cli.js spec/errorTest/slowHttpAndTimeout 'Locator: by.binding\\(\\"slowAngularTimeoutStatus\\"\\)$'} ]); +executor.addCommandlineTest('node built/cli.js spec/angular2TimeoutConf.js') + .expectExitCode(1) + .expectErrors([ + {message: 'Timed out waiting for Protractor to synchronize with the page'}, + ]); + executor.execute(); diff --git a/spec/angular2TimeoutConf.js b/spec/angular2TimeoutConf.js new file mode 100644 index 000000000..6e9bcf194 --- /dev/null +++ b/spec/angular2TimeoutConf.js @@ -0,0 +1,35 @@ +var env = require('./environment'); + +// This is the configuration for a smoke test for an Angular2 application. +// +// *** NOTE *** +// As Angular2 is in rapid development, the test application that ships with +// the Protractor repository does not yet contain an Angular2 section. This +// configuration assumes that you are serving the examples from the +// angular/angular repository at localhost:8000. +// See https://github.com/angular/angular/blob/master/DEVELOPER.md for +// setup instructions. +// +exports.config = { + seleniumAddress: env.seleniumAddress, + + framework: 'jasmine', + + specs: [ + 'ng2/timeout_spec.js' + ], + + capabilities: env.capabilities, + + baseUrl: env.baseUrl, + + // 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 + + // Alternatively, you could specify one root element application, to test + // against only that one: + // rootElement: 'async-app' +}; diff --git a/spec/ng2/async_spec.js b/spec/ng2/async_spec.js index 51772db41..16af1fbe1 100644 --- a/spec/ng2/async_spec.js +++ b/spec/ng2/async_spec.js @@ -63,7 +63,7 @@ describe('async angular2 application', function() { }); it('should wait for a series of periodic increments', function() { - var timeout = $('#periodicIncrement'); + var timeout = $('#periodicIncrement_unzoned'); // Waits for the val to count 2. var EC = protractor.ExpectedConditions; diff --git a/spec/ng2/timeout_spec.js b/spec/ng2/timeout_spec.js new file mode 100644 index 000000000..a023b67b2 --- /dev/null +++ b/spec/ng2/timeout_spec.js @@ -0,0 +1,10 @@ +describe('async angular2 application timeout', function() { + var URL = '/ng2/#/async'; + + it('should timeout if intervals are used in the NgZone', function() { + browser.get(URL); + var timeout = $('#periodicIncrement'); + timeout.$('.action').click(); + timeout.$('.cancel').click(); + }); +}); diff --git a/testapp/ng2/app/app.router.js b/testapp/ng2/app/app.router.js index 37771d518..4463c5200 100644 --- a/testapp/ng2/app/app.router.js +++ b/testapp/ng2/app/app.router.js @@ -1,4 +1,6 @@ -System.register(['angular2/core', 'angular2/router', './home/home.component', './async/async.component'], function(exports_1) { +System.register(['angular2/core', 'angular2/router', './home/home.component', './async/async.component'], function(exports_1, context_1) { + "use strict"; + var __moduleName = context_1 && context_1.id; 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); @@ -41,7 +43,7 @@ System.register(['angular2/core', 'angular2/router', './home/home.component', '. __metadata('design:paramtypes', []) ], AppRouter); return AppRouter; - })(); + }()); exports_1("AppRouter", AppRouter); } } diff --git a/testapp/ng2/app/app.router.js.map b/testapp/ng2/app/app.router.js.map index f1a7785c6..12d1cf12b 100644 --- a/testapp/ng2/app/app.router.js.map +++ b/testapp/ng2/app/app.router.js.map @@ -1 +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 +{"version":3,"file":"app.router.js","sourceRoot":"","sources":["app.router.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAeA;gBAAA;gBACA,CAAC;gBAVD;oBAAC,gBAAS,CAAC;wBACT,QAAQ,EAAE,QAAQ;wBAClB,WAAW,EAAE,qBAAqB;wBAClC,UAAU,EAAE,CAAC,0BAAiB,CAAC;qBAChC,CAAC;oBACD,oBAAW,CAAC;wBACX,EAAC,IAAI,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,8BAAa,EAAC;wBAClD,EAAC,IAAI,EAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,gCAAc,EAAC;qBAC1D,CAAC;;6BAAA;gBAEF,gBAAC;YAAD,CAAC,AADD,IACC;YADD,iCACC,CAAA"} \ No newline at end of file diff --git a/testapp/ng2/app/async/async-component.html b/testapp/ng2/app/async/async-component.html index 69e4e2d1d..d8016c6b2 100644 --- a/testapp/ng2/app/async/async-component.html +++ b/testapp/ng2/app/async/async-component.html @@ -22,3 +22,10 @@ +
+ {{val5}} + + +
diff --git a/testapp/ng2/app/async/async.component.js b/testapp/ng2/app/async/async.component.js index ccf898282..d2ac72180 100644 --- a/testapp/ng2/app/async/async.component.js +++ b/testapp/ng2/app/async/async.component.js @@ -1,4 +1,6 @@ -System.register(['angular2/core', 'angular2/common', 'angular2/src/facade/async'], function(exports_1) { +System.register(['angular2/core', 'angular2/common'], function(exports_1, context_1) { + "use strict"; + var __moduleName = context_1 && context_1.id; 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); @@ -8,7 +10,7 @@ System.register(['angular2/core', 'angular2/common', 'angular2/src/facade/async' 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 core_1, common_1; var AsyncComponent; return { setters:[ @@ -17,41 +19,42 @@ System.register(['angular2/core', 'angular2/common', 'angular2/src/facade/async' }, function (common_1_1) { common_1 = common_1_1; - }, - function (async_1_1) { - async_1 = async_1_1; }], execute: function() { AsyncComponent = (function () { - function AsyncComponent() { + function AsyncComponent(_ngZone) { + this._ngZone = _ngZone; this.val1 = 0; this.val2 = 0; this.val3 = 0; this.val4 = 0; + this.val5 = 0; this.timeoutId = null; - this.multiTimeoutId = null; + this.chainedTimeoutId = null; this.intervalId = null; + this.intervalId_unzoned = null; } + ; AsyncComponent.prototype.increment = function () { this.val1++; }; ; AsyncComponent.prototype.delayedIncrement = function () { var _this = this; this.cancelDelayedIncrement(); - this.timeoutId = async_1.TimerWrapper.setTimeout(function () { + this.timeoutId = setTimeout(function () { _this.val2++; _this.timeoutId = null; }, 2000); }; ; - AsyncComponent.prototype.multiDelayedIncrements = function (i) { - this.cancelMultiDelayedIncrements(); + AsyncComponent.prototype.chainedDelayedIncrements = function (i) { + this.cancelChainedDelayedIncrements(); var self = this; function helper(_i) { if (_i <= 0) { - self.multiTimeoutId = null; + self.chainedTimeoutId = null; return; } - self.multiTimeoutId = async_1.TimerWrapper.setTimeout(function () { + self.chainedTimeoutId = setTimeout(function () { self.val3++; helper(_i - 1); }, 500); @@ -62,39 +65,58 @@ System.register(['angular2/core', 'angular2/common', 'angular2/src/facade/async' AsyncComponent.prototype.periodicIncrement = function () { var _this = this; this.cancelPeriodicIncrement(); - this.intervalId = async_1.TimerWrapper.setInterval(function () { _this.val4++; }, 2000); + this.intervalId = setInterval(function () { _this.val4++; }, 2000); + }; + ; + AsyncComponent.prototype.periodicIncrement_unzoned = function () { + var _this = this; + this.cancelPeriodicIncrement_unzoned(); + this._ngZone.runOutsideAngular(function () { + _this.intervalId_unzoned = setInterval(function () { + _this._ngZone.run(function () { + _this.val5++; + }); + }, 2000); + }); }; ; AsyncComponent.prototype.cancelDelayedIncrement = function () { if (this.timeoutId != null) { - async_1.TimerWrapper.clearTimeout(this.timeoutId); + 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.cancelChainedDelayedIncrements = function () { + if (this.chainedTimeoutId != null) { + clearTimeout(this.chainedTimeoutId); + this.chainedTimeoutId = null; } }; ; AsyncComponent.prototype.cancelPeriodicIncrement = function () { if (this.intervalId != null) { - async_1.TimerWrapper.clearInterval(this.intervalId); + clearInterval(this.intervalId); this.intervalId = null; } }; ; + AsyncComponent.prototype.cancelPeriodicIncrement_unzoned = function () { + if (this.intervalId_unzoned != null) { + clearInterval(this.intervalId_unzoned); + this.intervalId_unzoned = null; + } + }; + ; AsyncComponent = __decorate([ core_1.Component({ templateUrl: 'app/async/async-component.html', directives: [common_1.NgIf] }), - __metadata('design:paramtypes', []) + __metadata('design:paramtypes', [core_1.NgZone]) ], AsyncComponent); return AsyncComponent; - })(); + }()); exports_1("AsyncComponent", AsyncComponent); } } diff --git a/testapp/ng2/app/async/async.component.js.map b/testapp/ng2/app/async/async.component.js.map index dfdfa1f93..c90732556 100644 --- a/testapp/ng2/app/async/async.component.js.map +++ b/testapp/ng2/app/async/async.component.js.map @@ -1 +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 +{"version":3,"file":"async.component.js","sourceRoot":"","sources":["async.component.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;YAQA;gBAWE,wBAAoB,OAAe;oBAAf,YAAO,GAAP,OAAO,CAAQ;oBAVnC,SAAI,GAAW,CAAC,CAAC;oBACjB,SAAI,GAAW,CAAC,CAAC;oBACjB,SAAI,GAAW,CAAC,CAAC;oBACjB,SAAI,GAAW,CAAC,CAAC;oBACjB,SAAI,GAAW,CAAC,CAAC;oBACjB,cAAS,GAAG,IAAI,CAAC;oBACjB,qBAAgB,GAAG,IAAI,CAAC;oBACxB,eAAU,GAAG,IAAI,CAAC;oBAClB,uBAAkB,GAAG,IAAI,CAAC;gBAEY,CAAC;;gBAEvC,kCAAS,GAAT,cAAoB,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;;gBAElC,yCAAgB,GAAhB;oBAAA,iBAMC;oBALC,IAAI,CAAC,sBAAsB,EAAE,CAAC;oBAC9B,IAAI,CAAC,SAAS,GAAG,UAAU,CAAC;wBAC1B,KAAI,CAAC,IAAI,EAAE,CAAC;wBACZ,KAAI,CAAC,SAAS,GAAG,IAAI,CAAC;oBACxB,CAAC,EAAE,IAAI,CAAC,CAAC;gBACX,CAAC;;gBAED,iDAAwB,GAAxB,UAAyB,CAAS;oBAChC,IAAI,CAAC,8BAA8B,EAAE,CAAC;oBAEtC,IAAI,IAAI,GAAG,IAAI,CAAC;oBAChB,gBAAgB,EAAE;wBAChB,EAAE,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;4BACZ,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC;4BAC7B,MAAM,CAAC;wBACT,CAAC;wBAED,IAAI,CAAC,gBAAgB,GAAG,UAAU,CAAC;4BACjC,IAAI,CAAC,IAAI,EAAE,CAAC;4BACZ,MAAM,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;wBACjB,CAAC,EAAE,GAAG,CAAC,CAAC;oBACV,CAAC;oBACD,MAAM,CAAC,CAAC,CAAC,CAAC;gBACZ,CAAC;;gBAED,0CAAiB,GAAjB;oBAAA,iBAGC;oBAFC,IAAI,CAAC,uBAAuB,EAAE,CAAC;oBAC/B,IAAI,CAAC,UAAU,GAAG,WAAW,CAAC,cAAQ,KAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;gBAC7D,CAAC;;gBAED,kDAAyB,GAAzB;oBAAA,iBASC;oBARC,IAAI,CAAC,+BAA+B,EAAE,CAAC;oBACvC,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC;wBAC7B,KAAI,CAAC,kBAAkB,GAAG,WAAW,CAAC;4BACpC,KAAI,CAAC,OAAO,CAAC,GAAG,CAAC;gCACf,KAAI,CAAC,IAAI,EAAE,CAAC;4BACd,CAAC,CAAC,CAAC;wBACL,CAAC,EAAE,IAAI,CAAC,CAAA;oBACV,CAAC,CAAC,CAAC;gBACL,CAAC;;gBAED,+CAAsB,GAAtB;oBACE,EAAE,CAAC,CAAC,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,CAAC,CAAC;wBAC3B,YAAY,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;wBAC7B,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;oBACxB,CAAC;gBACH,CAAC;;gBAED,uDAA8B,GAA9B;oBACE,EAAE,CAAC,CAAC,IAAI,CAAC,gBAAgB,IAAI,IAAI,CAAC,CAAC,CAAC;wBAClC,YAAY,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;wBACpC,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC;oBAC/B,CAAC;gBACH,CAAC;;gBAED,gDAAuB,GAAvB;oBACE,EAAE,CAAC,CAAC,IAAI,CAAC,UAAU,IAAI,IAAI,CAAC,CAAC,CAAC;wBAC5B,aAAa,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;wBAC/B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;oBACzB,CAAC;gBACH,CAAC;;gBAED,wDAA+B,GAA/B;oBACE,EAAE,CAAC,CAAC,IAAI,CAAC,kBAAkB,IAAI,IAAI,CAAC,CAAC,CAAC;wBACpC,aAAa,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC;wBACvC,IAAI,CAAC,kBAAkB,GAAG,IAAI,CAAC;oBACjC,CAAC;gBACH,CAAC;;gBAvFH;oBAAC,gBAAS,CAAC;wBACT,WAAW,EAAE,gCAAgC;wBAC7C,UAAU,EAAE,CAAC,aAAI,CAAC;qBACnB,CAAC;;kCAAA;gBAqFF,qBAAC;YAAD,CAAC,AApFD,IAoFC;YApFD,2CAoFC,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 index ad76d2fe1..bce93851b 100644 --- a/testapp/ng2/app/async/async.component.ts +++ b/testapp/ng2/app/async/async.component.ts @@ -1,7 +1,6 @@ import {bootstrap} from 'angular2/bootstrap'; -import {Component} from 'angular2/core'; +import {Component, NgZone} from 'angular2/core'; import {NgIf} from 'angular2/common'; -import {TimerWrapper} from 'angular2/src/facade/async'; @Component({ templateUrl: 'app/async/async-component.html', @@ -12,15 +11,19 @@ export class AsyncComponent { val2: number = 0; val3: number = 0; val4: number = 0; + val5: number = 0; timeoutId = null; chainedTimeoutId = null; intervalId = null; + intervalId_unzoned = null; + + constructor(private _ngZone: NgZone) {}; increment(): void { this.val1++; }; delayedIncrement(): void { this.cancelDelayedIncrement(); - this.timeoutId = TimerWrapper.setTimeout(() => { + this.timeoutId = setTimeout(() => { this.val2++; this.timeoutId = null; }, 2000); @@ -36,7 +39,7 @@ export class AsyncComponent { return; } - self.chainedTimeoutId = TimerWrapper.setTimeout(() => { + self.chainedTimeoutId = setTimeout(() => { self.val3++; helper(_i - 1); }, 500); @@ -46,27 +49,45 @@ export class AsyncComponent { periodicIncrement(): void { this.cancelPeriodicIncrement(); - this.intervalId = TimerWrapper.setInterval(() => { this.val4++; }, 2000) + this.intervalId = setInterval(() => { this.val4++; }, 2000) + }; + + periodicIncrement_unzoned(): void { + this.cancelPeriodicIncrement_unzoned(); + this._ngZone.runOutsideAngular(() => { + this.intervalId_unzoned = setInterval(() => { + this._ngZone.run(() => { + this.val5++; + }); + }, 2000) + }); }; cancelDelayedIncrement(): void { if (this.timeoutId != null) { - TimerWrapper.clearTimeout(this.timeoutId); + clearTimeout(this.timeoutId); this.timeoutId = null; } }; cancelChainedDelayedIncrements(): void { if (this.chainedTimeoutId != null) { - TimerWrapper.clearTimeout(this.chainedTimeoutId); + clearTimeout(this.chainedTimeoutId); this.chainedTimeoutId = null; } }; cancelPeriodicIncrement(): void { if (this.intervalId != null) { - TimerWrapper.clearInterval(this.intervalId); + clearInterval(this.intervalId); this.intervalId = null; } }; + + cancelPeriodicIncrement_unzoned(): void { + if (this.intervalId_unzoned != null) { + clearInterval(this.intervalId_unzoned); + this.intervalId_unzoned = null; + } + }; } diff --git a/testapp/ng2/app/boot.js b/testapp/ng2/app/boot.js index 69be33654..d948e2da0 100644 --- a/testapp/ng2/app/boot.js +++ b/testapp/ng2/app/boot.js @@ -1,4 +1,6 @@ -System.register(['angular2/core', 'angular2/platform/browser', 'angular2/router', './app.router'], function(exports_1) { +System.register(['angular2/core', 'angular2/platform/browser', 'angular2/router', './app.router'], function(exports_1, context_1) { + "use strict"; + var __moduleName = context_1 && context_1.id; var core_1, browser_1, router_1, app_router_1; return { setters:[ diff --git a/testapp/ng2/app/boot.js.map b/testapp/ng2/app/boot.js.map index efde64732..2112f1918 100644 --- a/testapp/ng2/app/boot.js.map +++ b/testapp/ng2/app/boot.js.map @@ -1 +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 +{"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/home/home.component.js b/testapp/ng2/app/home/home.component.js index f6bea41d2..e00d1b632 100644 --- a/testapp/ng2/app/home/home.component.js +++ b/testapp/ng2/app/home/home.component.js @@ -1,4 +1,6 @@ -System.register(['angular2/core'], function(exports_1) { +System.register(['angular2/core'], function(exports_1, context_1) { + "use strict"; + var __moduleName = context_1 && context_1.id; 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); @@ -26,7 +28,7 @@ System.register(['angular2/core'], function(exports_1) { __metadata('design:paramtypes', []) ], HomeComponent); return HomeComponent; - })(); + }()); exports_1("HomeComponent", HomeComponent); } } diff --git a/testapp/ng2/app/home/home.component.js.map b/testapp/ng2/app/home/home.component.js.map index 327f414f2..8f6bb554e 100644 --- a/testapp/ng2/app/home/home.component.js.map +++ b/testapp/ng2/app/home/home.component.js.map @@ -1 +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 +{"version":3,"file":"home.component.js","sourceRoot":"","sources":["home.component.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;YAKA;gBAAA;gBAEA,CAAC;gBALD;oBAAC,gBAAS,CAAC;wBACT,WAAW,EAAE,8BAA8B;qBAC5C,CAAC;;iCAAA;gBAGF,oBAAC;YAAD,CAAC,AAFD,IAEC;YAFD,yCAEC,CAAA"} \ No newline at end of file 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 index b07de2a7a..f174c3f5f 100644 --- 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 @@ -1,2266 +1,1414 @@ /** @license -Copyright 2014-2015 Google, Inc. http://angularjs.org +The MIT License -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +Copyright (c) 2016 Google, Inc. - http://www.apache.org/licenses/LICENSE-2.0 +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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); - }; - } - }); -}; +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. -/** - * 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'; + this._properties = zoneSpec && zoneSpec.properties || {}; + this._zoneDelegate = new ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec); + } + Object.defineProperty(Zone, "current", { + get: function () { return _currentZone; }, + enumerable: true, + configurable: true + }); + ; + Object.defineProperty(Zone, "currentTask", { + get: function () { return _currentTask; }, + enumerable: true, + configurable: true + }); + ; + Object.defineProperty(Zone.prototype, "parent", { + get: function () { return this._parent; }, + enumerable: true, + configurable: true + }); + ; + Object.defineProperty(Zone.prototype, "name", { + get: function () { return this._name; }, + enumerable: true, + configurable: true + }); + ; + Zone.prototype.get = function (key) { + var current = this; + while (current) { + if (current._properties.hasOwnProperty(key)) { + return current._properties[key]; + } + current = current._parent; + } + }; + Zone.prototype.fork = function (zoneSpec) { + if (!zoneSpec) + throw new Error('ZoneSpec required!'); + return this._zoneDelegate.fork(this, zoneSpec); + }; + Zone.prototype.wrap = function (callback, source) { + if (typeof callback != 'function') { + throw new Error('Expecting function got: ' + callback); + } + var callback = this._zoneDelegate.intercept(this, callback, source); + var zone = this; + return function () { + return zone.runGuarded(callback, this, arguments, source); + }; + }; + Zone.prototype.run = function (callback, applyThis, applyArgs, source) { + if (applyThis === void 0) { applyThis = null; } + if (applyArgs === void 0) { applyArgs = null; } + if (source === void 0) { source = null; } + var oldZone = _currentZone; + _currentZone = this; + try { + return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source); + } + finally { + _currentZone = oldZone; + } + }; + Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) { + if (applyThis === void 0) { applyThis = null; } + if (applyArgs === void 0) { applyArgs = null; } + if (source === void 0) { source = null; } + var oldZone = _currentZone; + _currentZone = this; + try { + try { + return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source); + } + catch (error) { + if (this._zoneDelegate.handleError(this, error)) { + throw error; + } + } + } + finally { + _currentZone = oldZone; + } + }; + Zone.prototype.runTask = function (task, applyThis, applyArgs) { + if (task.zone != this) + throw new Error('A task can only be run in the zone which created it! (Creation: ' + + task.zone.name + '; Execution: ' + this.name + ')'); + var previousTask = _currentTask; + _currentTask = task; + var oldZone = _currentZone; + _currentZone = this; + try { + try { + return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs); + } + catch (error) { + if (this._zoneDelegate.handleError(this, error)) { + throw error; + } + } + } + finally { + if (task.type == 'macroTask' && task.data && !task.data.isPeriodic) { + task.cancelFn = null; + } + _currentZone = oldZone; + _currentTask = previousTask; + } + }; + Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) { + return this._zoneDelegate.scheduleTask(this, new ZoneTask('microTask', this, source, callback, data, customSchedule, null)); + }; + Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) { + return this._zoneDelegate.scheduleTask(this, new ZoneTask('macroTask', this, source, callback, data, customSchedule, customCancel)); + }; + Zone.prototype.scheduleEventTask = function (source, callback, data, customSchedule, customCancel) { + return this._zoneDelegate.scheduleTask(this, new ZoneTask('eventTask', this, source, callback, data, customSchedule, customCancel)); + }; + Zone.prototype.cancelTask = function (task) { + var value = this._zoneDelegate.cancelTask(this, task); + task.cancelFn = null; + return value; + }; + Zone.__symbol__ = __symbol__; + return Zone; + }()); + ; + var ZoneDelegate = (function () { + function ZoneDelegate(zone, parentDelegate, zoneSpec) { + this._taskCounts = { microTask: 0, macroTask: 0, eventTask: 0 }; + this.zone = zone; + this._parentDelegate = parentDelegate; + this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS); + this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt); + this._interceptZS = zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS); + this._interceptDlgt = zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt); + this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS); + this._invokeDlgt = zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt); + this._handleErrorZS = zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS); + this._handleErrorDlgt = zoneSpec && (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt); + this._scheduleTaskZS = zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS); + this._scheduleTaskDlgt = zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt); + this._invokeTaskZS = zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS); + this._invokeTaskDlgt = zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt); + this._cancelTaskZS = zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS); + this._cancelTaskDlgt = zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt); + this._hasTaskZS = zoneSpec && (zoneSpec.onHasTask ? zoneSpec : parentDelegate._hasTaskZS); + this._hasTaskDlgt = zoneSpec && (zoneSpec.onHasTask ? parentDelegate : parentDelegate._hasTaskDlgt); + } + ZoneDelegate.prototype.fork = function (targetZone, zoneSpec) { + return this._forkZS + ? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec) + : new Zone(targetZone, zoneSpec); + }; + ZoneDelegate.prototype.intercept = function (targetZone, callback, source) { + return this._interceptZS + ? this._interceptZS.onIntercept(this._interceptDlgt, this.zone, targetZone, callback, source) + : callback; + }; + ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) { + return this._invokeZS + ? this._invokeZS.onInvoke(this._invokeDlgt, this.zone, targetZone, callback, applyThis, applyArgs, source) + : callback.apply(applyThis, applyArgs); + }; + ZoneDelegate.prototype.handleError = function (targetZone, error) { + return this._handleErrorZS + ? this._handleErrorZS.onHandleError(this._handleErrorDlgt, this.zone, targetZone, error) + : true; + }; + ZoneDelegate.prototype.scheduleTask = function (targetZone, task) { + try { + if (this._scheduleTaskZS) { + return this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this.zone, targetZone, task); + } + else if (task.scheduleFn) { + task.scheduleFn(task); + } + else if (task.type == 'microTask') { + scheduleMicroTask(task); + } + else { + throw new Error('Task is missing scheduleFn.'); + } + return task; + } + finally { + if (targetZone == this.zone) { + this._updateTaskCount(task.type, 1); + } + } + }; + ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) { + try { + return this._invokeTaskZS + ? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this.zone, targetZone, task, applyThis, applyArgs) + : task.callback.apply(applyThis, applyArgs); + } + finally { + if (targetZone == this.zone && (task.type != 'eventTask') && !(task.data && task.data.isPeriodic)) { + this._updateTaskCount(task.type, -1); + } + } + }; + ZoneDelegate.prototype.cancelTask = function (targetZone, task) { + var value; + if (this._cancelTaskZS) { + value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this.zone, targetZone, task); + } + else if (!task.cancelFn) { + throw new Error('Task does not support cancellation, or is already canceled.'); + } + else { + value = task.cancelFn(task); + } + if (targetZone == this.zone) { + // this should not be in the finally block, because exceptions assume not canceled. + this._updateTaskCount(task.type, -1); + } + return value; + }; + ZoneDelegate.prototype.hasTask = function (targetZone, isEmpty) { + return this._hasTaskZS && this._hasTaskZS.onHasTask(this._hasTaskDlgt, this.zone, targetZone, isEmpty); + }; + ZoneDelegate.prototype._updateTaskCount = function (type, count) { + var counts = this._taskCounts; + var prev = counts[type]; + var next = counts[type] = prev + count; + if (next < 0) { + throw new Error('More tasks executed then were scheduled.'); + } + if (prev == 0 || next == 0) { + var isEmpty = { + microTask: counts.microTask > 0, + macroTask: counts.macroTask > 0, + eventTask: counts.eventTask > 0, + change: type + }; + try { + this.hasTask(this.zone, isEmpty); + } + finally { + if (this._parentDelegate) { + this._parentDelegate._updateTaskCount(type, count); + } + } + } + }; + return ZoneDelegate; + }()); + var ZoneTask = (function () { + function ZoneTask(type, zone, source, callback, options, scheduleFn, cancelFn) { + this.type = type; + this.zone = zone; + this.source = source; + this.data = options; + this.scheduleFn = scheduleFn; + this.cancelFn = cancelFn; + this.callback = callback; + var self = this; + this.invoke = function () { + try { + return zone.runTask(self, this, arguments); + } + finally { + drainMicroTaskQueue(); + } + }; + } + return ZoneTask; + }()); + function __symbol__(name) { return '__zone_symbol__' + name; } + ; + var symbolSetTimeout = __symbol__('setTimeout'); + var symbolPromise = __symbol__('Promise'); + var symbolThen = __symbol__('then'); + var _currentZone = new Zone(null, null); + var _currentTask = null; + var _microTaskQueue = []; + var _isDrainingMicrotaskQueue = false; + var _uncaughtPromiseErrors = []; + var _drainScheduled = false; + function scheduleQueueDrain() { + if (!_drainScheduled && !_currentTask && _microTaskQueue.length == 0) { + // We are not running in Task, so we need to kickstart the microtask queue. + if (global[symbolPromise]) { + global[symbolPromise].resolve(0)[symbolThen](drainMicroTaskQueue); + } + else { + global[symbolSetTimeout](drainMicroTaskQueue, 0); + } + } + } + function scheduleMicroTask(task) { + scheduleQueueDrain(); + _microTaskQueue.push(task); + } + function consoleError(e) { + var rejection = e && e.rejection; + if (rejection) { + console.error('Unhandled Promise rejection:', rejection instanceof Error ? rejection.message : rejection, '; Zone:', e.zone.name, '; Task:', e.task && e.task.source, '; Value:', rejection); + } + console.error(e); + } + function drainMicroTaskQueue() { + if (!_isDrainingMicrotaskQueue) { + _isDrainingMicrotaskQueue = true; + while (_microTaskQueue.length) { + var queue = _microTaskQueue; + _microTaskQueue = []; + for (var i = 0; i < queue.length; i++) { + var task = queue[i]; + try { + task.zone.runTask(task, null, null); + } + catch (e) { + consoleError(e); + } + } + } + while (_uncaughtPromiseErrors.length) { + var uncaughtPromiseErrors = _uncaughtPromiseErrors; + _uncaughtPromiseErrors = []; + for (var i = 0; i < uncaughtPromiseErrors.length; i++) { + var uncaughtPromiseError = uncaughtPromiseErrors[i]; + try { + uncaughtPromiseError.zone.runGuarded(function () { throw uncaughtPromiseError; }); + } + catch (e) { + consoleError(e); + } + } + } + _isDrainingMicrotaskQueue = false; + _drainScheduled = false; + } + } + function isThenable(value) { + return value && value.then; + } + function forwardResolution(value) { return value; } + function forwardRejection(rejection) { return ZoneAwarePromise.reject(rejection); } + var symbolState = __symbol__('state'); + var symbolValue = __symbol__('value'); + var source = 'Promise.then'; + var UNRESOLVED = null; + var RESOLVED = true; + var REJECTED = false; + var REJECTED_NO_CATCH = 0; + function makeResolver(promise, state) { + return function (v) { + resolvePromise(promise, state, v); + // Do not return value or you will break the Promise spec. + }; + } + function resolvePromise(promise, state, value) { + if (promise[symbolState] === UNRESOLVED) { + if (value instanceof ZoneAwarePromise && value[symbolState] !== UNRESOLVED) { + clearRejectedNoCatch(value); + resolvePromise(promise, value[symbolState], value[symbolValue]); + } + else if (isThenable(value)) { + value.then(makeResolver(promise, state), makeResolver(promise, false)); + } + else { + promise[symbolState] = state; + var queue = promise[symbolValue]; + promise[symbolValue] = value; + for (var i = 0; i < queue.length;) { + scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]); + } + if (queue.length == 0 && state == REJECTED) { + promise[symbolState] = REJECTED_NO_CATCH; + try { + throw new Error("Uncaught (in promise): " + value); + } + catch (e) { + var error = e; + error.rejection = value; + error.promise = promise; + error.zone = Zone.current; + error.task = Zone.currentTask; + _uncaughtPromiseErrors.push(error); + scheduleQueueDrain(); + } + } + } + } + // Resolving an already resolved promise is a noop. + return promise; + } + function clearRejectedNoCatch(promise) { + if (promise[symbolState] === REJECTED_NO_CATCH) { + promise[symbolState] = REJECTED; + for (var i = 0; i < _uncaughtPromiseErrors.length; i++) { + if (promise === _uncaughtPromiseErrors[i].promise) { + _uncaughtPromiseErrors.splice(i, 1); + break; + } + } + } + } + function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) { + clearRejectedNoCatch(promise); + var delegate = promise[symbolState] ? onFulfilled || forwardResolution : onRejected || forwardRejection; + zone.scheduleMicroTask(source, function () { + try { + resolvePromise(chainPromise, true, zone.run(delegate, null, [promise[symbolValue]])); + } + catch (error) { + resolvePromise(chainPromise, false, error); + } + }); + } + var ZoneAwarePromise = (function () { + function ZoneAwarePromise(executor) { + var promise = this; + promise[symbolState] = UNRESOLVED; + promise[symbolValue] = []; // queue; + try { + executor && executor(makeResolver(promise, RESOLVED), makeResolver(promise, REJECTED)); + } + catch (e) { + resolvePromise(promise, false, e); + } + } + ZoneAwarePromise.resolve = function (value) { + return resolvePromise(new this(null), RESOLVED, value); + }; + ZoneAwarePromise.reject = function (error) { + return resolvePromise(new this(null), REJECTED, error); + }; + ZoneAwarePromise.race = function (values) { + var resolve; + var reject; + var promise = new this(function (res, rej) { resolve = res; reject = rej; }); + function onResolve(value) { promise && (promise = null || resolve(value)); } + function onReject(error) { promise && (promise = null || reject(error)); } + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var value = values_1[_i]; + if (!isThenable(value)) { + value = this.resolve(value); + } + value.then(onResolve, onReject); + } + return promise; + }; + ZoneAwarePromise.all = function (values) { + var resolve; + var reject; + var promise = new this(function (res, rej) { resolve = res; reject = rej; }); + var resolvedValues = []; + var count = 0; + function onReject(error) { promise && reject(error); promise = null; } + for (var _i = 0, values_2 = values; _i < values_2.length; _i++) { + var value = values_2[_i]; + if (!isThenable(value)) { + value = this.resolve(value); + } + value.then((function (index) { return function (value) { + resolvedValues[index] = value; + count--; + if (promise && !count) { + resolve(resolvedValues); + } + promise == null; + }; })(count), onReject); + count++; + } + if (!count) + resolve(resolvedValues); + return promise; + }; + ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) { + var chainPromise = new ZoneAwarePromise(null); + var zone = Zone.current; + if (this[symbolState] == UNRESOLVED) { + this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected); + } + else { + scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected); + } + return chainPromise; + }; + ZoneAwarePromise.prototype.catch = function (onRejected) { + return this.then(null, onRejected); + }; + return ZoneAwarePromise; + }()); + var NativePromise = global[__symbol__('Promise')] = global.Promise; + global.Promise = ZoneAwarePromise; + if (NativePromise) { + var NativePromiseProtototype = NativePromise.prototype; + var NativePromiseThen = NativePromiseProtototype[__symbol__('then')] + = NativePromiseProtototype.then; + NativePromiseProtototype.then = function (onResolve, onReject) { + var nativePromise = this; + return new ZoneAwarePromise(function (resolve, reject) { + NativePromiseThen.call(nativePromise, resolve, reject); + }).then(onResolve, onReject); + }; + } + return global.Zone = Zone; + })(typeof window == 'undefined' ? global : window); + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }, +/* 2 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + var utils_1 = __webpack_require__(3); + var WTF_ISSUE_555 = 'Anchor,Area,Audio,BR,Base,BaseFont,Body,Button,Canvas,Content,DList,Directory,Div,Embed,FieldSet,Font,Form,Frame,FrameSet,HR,Head,Heading,Html,IFrame,Image,Input,Keygen,LI,Label,Legend,Link,Map,Marquee,Media,Menu,Meta,Meter,Mod,OList,Object,OptGroup,Option,Output,Paragraph,Pre,Progress,Quote,Script,Select,Source,Span,Style,TableCaption,TableCell,TableCol,Table,TableRow,TableSection,TextArea,Title,Track,UList,Unknown,Video'; + var NO_EVENT_TARGET = 'ApplicationCache,EventSource,FileReader,InputMethodContext,MediaController,MessagePort,Node,Performance,SVGElementInstance,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebKitNamedFlow,Worker,WorkerGlobalScope,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload,IDBRequest,IDBOpenDBRequest,IDBDatabase,IDBTransaction,IDBCursor,DBIndex'.split(','); + var EVENT_TARGET = 'EventTarget'; + function eventTargetPatch(_global) { + var apis = []; + var isWtf = _global['wtf']; + if (isWtf) { + // Workaround for: https://github.com/google/tracing-framework/issues/555 + apis = WTF_ISSUE_555.split(',').map(function (v) { return 'HTML' + v + 'Element'; }).concat(NO_EVENT_TARGET); + } + else if (_global[EVENT_TARGET]) { + apis.push(EVENT_TARGET); + } + else { + // 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 + apis = NO_EVENT_TARGET; + } + for (var i = 0; i < apis.length; i++) { + var type = _global[apis[i]]; + utils_1.patchEventTargetMethods(type && type.prototype); + } + } + exports.eventTargetPatch = eventTargetPatch; + + +/***/ }, +/* 3 */ +/***/ function(module, exports) { + + /* WEBPACK VAR INJECTION */(function(global) {/** + * Suppress closure compiler errors about unknown 'process' variable + * @fileoverview + * @suppress {undefinedVars} + */ + "use strict"; + exports.zoneSymbol = Zone['__symbol__']; + var _global = typeof window == 'undefined' ? global : window; + function bindArguments(args, source) { + for (var i = args.length - 1; i >= 0; i--) { + if (typeof args[i] === 'function') { + args[i] = Zone.current.wrap(args[i], source + '_' + i); + } + } + return args; + } + exports.bindArguments = bindArguments; + ; + function patchPrototype(prototype, fnNames) { + var source = prototype.constructor['name']; + for (var i = 0; i < fnNames.length; i++) { + var name = fnNames[i]; + var delegate = prototype[name]; + if (delegate) { + prototype[name] = (function (delegate) { + return function () { + return delegate.apply(this, bindArguments(arguments, source + '.' + name)); + }; + })(delegate); + } + } + } + exports.patchPrototype = patchPrototype; + ; + exports.isWebWorker = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope); + exports.isNode = (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'); + exports.isBrowser = !exports.isNode && !exports.isWebWorker && !!(window && window['HTMLElement']); + 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') { + var wrapFn = function (event) { + var result; + result = fn.apply(this, arguments); + if (result != undefined && !result) + event.preventDefault(); + }; + this[_prop] = wrapFn; + this.addEventListener(eventName, wrapFn, false); + } + else { + this[_prop] = null; + } + }; + desc.get = function () { + return this[_prop]; + }; + Object.defineProperty(obj, prop, desc); + } + exports.patchProperty = patchProperty; + ; + function patchOnProperties(obj, properties) { + var onProperties = []; + for (var prop in obj) { + if (prop.substr(0, 2) == 'on') { + onProperties.push(prop); + } + } + for (var j = 0; j < onProperties.length; j++) { + patchProperty(obj, onProperties[j]); + } + if (properties) { + for (var i = 0; i < properties.length; i++) { + patchProperty(obj, 'on' + properties[i]); + } + } + } + exports.patchOnProperties = patchOnProperties; + ; + var EVENT_TASKS = exports.zoneSymbol('eventTasks'); + var ADD_EVENT_LISTENER = 'addEventListener'; + var REMOVE_EVENT_LISTENER = 'removeEventListener'; + var SYMBOL_ADD_EVENT_LISTENER = exports.zoneSymbol(ADD_EVENT_LISTENER); + var SYMBOL_REMOVE_EVENT_LISTENER = exports.zoneSymbol(REMOVE_EVENT_LISTENER); + function findExistingRegisteredTask(target, handler, name, capture, remove) { + var eventTasks = target[EVENT_TASKS]; + if (eventTasks) { + for (var i = 0; i < eventTasks.length; i++) { + var eventTask = eventTasks[i]; + var data = eventTask.data; + if (data.handler === handler + && data.useCapturing === capture + && data.eventName === name) { + if (remove) { + eventTasks.splice(i, 1); + } + return eventTask; + } + } + } + return null; + } + function attachRegisteredEvent(target, eventTask) { + var eventTasks = target[EVENT_TASKS]; + if (!eventTasks) { + eventTasks = target[EVENT_TASKS] = []; + } + eventTasks.push(eventTask); + } + function scheduleEventListener(eventTask) { + var meta = eventTask.data; + attachRegisteredEvent(meta.target, eventTask); + return meta.target[SYMBOL_ADD_EVENT_LISTENER](meta.eventName, eventTask.invoke, meta.useCapturing); + } + function cancelEventListener(eventTask) { + var meta = eventTask.data; + findExistingRegisteredTask(meta.target, eventTask.invoke, meta.eventName, meta.useCapturing, true); + meta.target[SYMBOL_REMOVE_EVENT_LISTENER](meta.eventName, eventTask.invoke, meta.useCapturing); + } + function zoneAwareAddEventListener(self, args) { + var eventName = args[0]; + var handler = args[1]; + var useCapturing = args[2] || false; + // - 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 = self || _global; + var delegate = null; + if (typeof handler == 'function') { + delegate = handler; + } + else if (handler && handler.handleEvent) { + delegate = function (event) { return handler.handleEvent(event); }; + } + // Ignore special listeners of IE11 & Edge dev tools, see https://github.com/angular/zone.js/issues/150 + if (!delegate || handler && handler.toString() === "[object FunctionWrapper]") { + return target[SYMBOL_ADD_EVENT_LISTENER](eventName, handler, useCapturing); + } + var eventTask = findExistingRegisteredTask(target, handler, eventName, useCapturing, false); + if (eventTask) { + // we already registered, so this will have noop. + return target[SYMBOL_ADD_EVENT_LISTENER](eventName, eventTask.invoke, useCapturing); + } + var zone = Zone.current; + var source = target.constructor['name'] + '.addEventListener:' + eventName; + var data = { + target: target, + eventName: eventName, + name: eventName, + useCapturing: useCapturing, + handler: handler + }; + zone.scheduleEventTask(source, delegate, data, scheduleEventListener, cancelEventListener); + } + function zoneAwareRemoveEventListener(self, args) { + var eventName = args[0]; + var handler = args[1]; + var useCapturing = args[2] || false; + // - 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 = self || _global; + var eventTask = findExistingRegisteredTask(target, handler, eventName, useCapturing, true); + if (eventTask) { + eventTask.zone.cancelTask(eventTask); + } + else { + target[SYMBOL_REMOVE_EVENT_LISTENER](eventName, handler, useCapturing); + } + } + function patchEventTargetMethods(obj) { + if (obj && obj.addEventListener) { + patchMethod(obj, ADD_EVENT_LISTENER, function () { return zoneAwareAddEventListener; }); + patchMethod(obj, REMOVE_EVENT_LISTENER, function () { return zoneAwareRemoveEventListener; }); + return true; + } + else { + return false; + } + } + exports.patchEventTargetMethods = patchEventTargetMethods; + ; + var originalInstanceKey = exports.zoneSymbol('originalInstance'); + // wrap some native API on `window` + function patchClass(className) { + var OriginalClass = _global[className]; + if (!OriginalClass) + return; + _global[className] = function () { + var a = bindArguments(arguments, className); + 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('Arg list too long.'); + } + }; + var instance = new OriginalClass(function () { }); + 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] = Zone.current.wrap(fn, className + '.' + prop); + } + 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]; + } + } + } + exports.patchClass = patchClass; + ; + function createNamedFn(name, delegate) { + try { + return (Function('f', "return function " + name + "(){return f(this, arguments)}"))(delegate); + } + catch (e) { + // if we fail, we must be CSP, just return delegate. + return function () { + return delegate(this, arguments); + }; + } + } + exports.createNamedFn = createNamedFn; + function patchMethod(target, name, patchFn) { + var proto = target; + while (proto && !proto.hasOwnProperty(name)) { + proto = Object.getPrototypeOf(proto); + } + if (!proto && target[name]) { + // somehow we did not find it, but we can see it. This happens on IE for Window properties. + proto = target; + } + var delegateName = exports.zoneSymbol(name); + var delegate; + if (proto && !(delegate = proto[delegateName])) { + delegate = proto[delegateName] = proto[name]; + proto[name] = createNamedFn(name, patchFn(delegate, delegateName, name)); + } + return delegate; + } + exports.patchMethod = patchMethod; + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }, +/* 4 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + var utils_1 = __webpack_require__(3); + // might need similar for object.freeze + // i regret nothing + var _defineProperty = Object.defineProperty; + var _getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + var _create = Object.create; + var unconfigurablesKey = utils_1.zoneSymbol('unconfigurables'); + function propertyPatch() { + 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; + }; + } + exports.propertyPatch = propertyPatch; + ; + function _redefineProperty(obj, prop, desc) { + desc = rewriteDescriptor(obj, prop, desc); + return _defineProperty(obj, prop, desc); + } + exports._redefineProperty = _redefineProperty; + ; + 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; + } + + +/***/ }, +/* 5 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + var define_property_1 = __webpack_require__(4); + var utils_1 = __webpack_require__(3); + function registerElementPatch(_global) { + if (!utils_1.isBrowser || !('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) { + var source = 'Document.registerElement::' + callback; + if (opts.prototype.hasOwnProperty(callback)) { + var descriptor = Object.getOwnPropertyDescriptor(opts.prototype, callback); + if (descriptor && descriptor.value) { + descriptor.value = Zone.current.wrap(descriptor.value, source); + define_property_1._redefineProperty(opts.prototype, callback, descriptor); + } + else { + opts.prototype[callback] = Zone.current.wrap(opts.prototype[callback], source); + } + } + else if (opts.prototype[callback]) { + opts.prototype[callback] = Zone.current.wrap(opts.prototype[callback], source); + } + }); + } + return _registerElement.apply(document, [name, opts]); + }; + } + exports.registerElementPatch = registerElementPatch; + + +/***/ }, +/* 6 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + var webSocketPatch = __webpack_require__(7); + var utils_1 = __webpack_require__(3); + 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 propertyDescriptorPatch(_global) { + if (utils_1.isNode) { + return; + } + var supportsWebSocket = typeof WebSocket !== 'undefined'; + if (canPatchViaPropertyDescriptor()) { + // for browsers that we can patch the descriptor: Chrome & Firefox + if (utils_1.isBrowser) { + utils_1.patchOnProperties(HTMLElement.prototype, eventNames); + } + utils_1.patchOnProperties(XMLHttpRequest.prototype, null); + if (typeof IDBIndex !== 'undefined') { + utils_1.patchOnProperties(IDBIndex.prototype, null); + utils_1.patchOnProperties(IDBRequest.prototype, null); + utils_1.patchOnProperties(IDBOpenDBRequest.prototype, null); + utils_1.patchOnProperties(IDBDatabase.prototype, null); + utils_1.patchOnProperties(IDBTransaction.prototype, null); + utils_1.patchOnProperties(IDBCursor.prototype, null); + } + if (supportsWebSocket) { + utils_1.patchOnProperties(WebSocket.prototype, null); + } + } + else { + // Safari, Android browsers (Jelly Bean) + patchViaCapturingAllTheEvents(); + utils_1.patchClass('XMLHttpRequest'); + if (supportsWebSocket) { + webSocketPatch.apply(_global); + } + } + } + exports.propertyDescriptorPatch = propertyDescriptorPatch; + function canPatchViaPropertyDescriptor() { + if (utils_1.isBrowser && !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(XMLHttpRequest.prototype, 'onreadystatechange', { + get: function () { + return true; + } + }); + var req = new XMLHttpRequest(); + var result = !!req.onreadystatechange; + Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {}); + return result; + } + ; + var unboundKey = utils_1.zoneSymbol('unbound'); + // Whenever any eventListener fires, we check the eventListener target and all parents + // for `onwhatever` properties and replace them with zone-bound functions + // - Chrome (for now) + function patchViaCapturingAllTheEvents() { + for (var i = 0; i < eventNames.length; i++) { + var property = eventNames[i]; + var onproperty = 'on' + property; + document.addEventListener(property, function (event) { + var elt = event.target, bound; + var source = elt.constructor['name'] + '.' + onproperty; + while (elt) { + if (elt[onproperty] && !elt[onproperty][unboundKey]) { + bound = Zone.current.wrap(elt[onproperty], source); + bound[unboundKey] = elt[onproperty]; + elt[onproperty] = bound; + } + elt = elt.parentElement; + } + }, true); + } + ; + } + ; + + +/***/ }, +/* 7 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global) {"use strict"; + var utils_1 = __webpack_require__(3); + // we have to patch the instance since the proto is non-configurable + function apply(_global) { + var WS = _global.WebSocket; + // On Safari window.EventTarget doesn't exist so need to patch WS add/removeEventListener + // On older Chrome, no need since EventTarget was already patched + if (!_global.EventTarget) { + utils_1.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_1.patchOnProperties(proxySocket, ['close', 'error', 'message', 'open']); + return proxySocket; + }; + global.WebSocket.prototype = Object.create(WS.prototype, { constructor: { value: WebSocket } }); + } + exports.apply = apply; + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ } +/******/ ]); +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports) { + + 'use strict'; + (function () { + var NEWLINE = '\n'; + var SEP = ' ------------- '; + var IGNORE_FRAMES = []; + var creationTrace = '__creationTrace__'; + var LongStackTrace = (function () { + function LongStackTrace() { + this.error = getStacktrace(); + this.timestamp = new Date(); + } + return LongStackTrace; + }()); + function getStacktraceWithUncaughtError() { + return new Error('STACKTRACE TRACKING'); + } + function getStacktraceWithCaughtError() { + try { + throw getStacktraceWithUncaughtError(); + } + catch (e) { + return e; + } + } + // Some implementations of exception handling don't create a stack trace if the exception + // isn't thrown, however it's faster not to actually throw the exception. + var error = getStacktraceWithUncaughtError(); + var coughtError = getStacktraceWithCaughtError(); + var getStacktrace = error.stack + ? getStacktraceWithUncaughtError + : (coughtError.stack ? getStacktraceWithCaughtError : getStacktraceWithUncaughtError); + function getFrames(error) { + return error.stack ? error.stack.split(NEWLINE) : []; + } + function addErrorStack(lines, error) { + var trace; + trace = getFrames(error); + for (var i = 0; i < trace.length; i++) { + var frame = trace[i]; + // Filter out the Frames which are part of stack capturing. + if (!(i < IGNORE_FRAMES.length && IGNORE_FRAMES[i] === frame)) { + lines.push(trace[i]); + } + } + } + function renderLongStackTrace(frames, stack) { + var longTrace = [stack]; + if (frames) { + var timestamp = new Date().getTime(); + for (var i = 0; i < frames.length; i++) { + var traceFrames = frames[i]; + var lastTime = traceFrames.timestamp; + longTrace.push(SEP + " Elapsed: " + (timestamp - lastTime.getTime()) + " ms; At: " + lastTime + " " + SEP); + addErrorStack(longTrace, traceFrames.error); + timestamp = lastTime.getTime(); + } + } + return longTrace.join(NEWLINE); + } + Zone['longStackTraceZoneSpec'] = { + name: 'long-stack-trace', + longStackTraceLimit: 10, + onScheduleTask: function (parentZoneDelegate, currentZone, targetZone, task) { + var currentTask = Zone.currentTask; + var trace = currentTask && currentTask.data && currentTask.data[creationTrace] || []; + trace = [new LongStackTrace()].concat(trace); + if (trace.length > this.longStackTraceLimit) { + trace.length = this.longStackTraceLimit; + } + if (!task.data) + task.data = {}; + task.data[creationTrace] = trace; + return parentZoneDelegate.scheduleTask(targetZone, task); + }, + onHandleError: function (parentZoneDelegate, currentZone, targetZone, error) { + var parentTask = Zone.currentTask; + if (error instanceof Error && parentTask) { + var descriptor = Object.getOwnPropertyDescriptor(error, 'stack'); + if (descriptor) { + var delegateGet = descriptor.get; + var value = descriptor.value; + descriptor = { + get: function () { + return renderLongStackTrace(parentTask.data && parentTask.data[creationTrace], delegateGet ? delegateGet.apply(this) : value); + } + }; + Object.defineProperty(error, 'stack', descriptor); + } + else { + error.stack = renderLongStackTrace(parentTask.data && parentTask.data[creationTrace], error.stack); + } + } + return parentZoneDelegate.handleError(targetZone, error); + } + }; + function captureStackTraces(stackTraces, count) { + if (count > 0) { + stackTraces.push(getFrames((new LongStackTrace()).error)); + captureStackTraces(stackTraces, count - 1); + } + } + function computeIgnoreFrames() { + var frames = []; + captureStackTraces(frames, 2); + var frames1 = frames[0]; + var frames2 = frames[1]; + for (var i = 0; i < frames1.length; i++) { + var frame1 = frames1[i]; + var frame2 = frames2[i]; + if (frame1 === frame2) { + IGNORE_FRAMES.push(frame1); + } + else { + break; + } + } + } + computeIgnoreFrames(); + })(); + + +/***/ } +/******/ ]); /** @license Apache License 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 index 9f9bde89b..6ce049dd0 100644 --- 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 @@ -22,13 +22,19 @@ System.register("angular2/src/facade/lang", [], true, function(require, exports, } else { globalScope = window; } - ; + function scheduleMicroTask(fn) { + Zone.current.scheduleMicroTask('scheduleMicrotask', fn); + } + exports.scheduleMicroTask = scheduleMicroTask; exports.IS_DART = false; var _global = globalScope; exports.global = _global; exports.Type = Function; function getTypeNameForDebugging(type) { - return type['name']; + if (type['name']) { + return type['name']; + } + return typeof type; } exports.getTypeNameForDebugging = getTypeNameForDebugging; exports.Math = _global.Math; @@ -113,6 +119,9 @@ System.register("angular2/src/facade/lang", [], true, function(require, exports, if (token.name) { return token.name; } + if (token.overriddenName) { + return token.overriddenName; + } var res = token.toString(); var newLineIndex = res.indexOf("\n"); return (newLineIndex === -1) ? res : res.substring(0, newLineIndex); @@ -126,6 +135,10 @@ System.register("angular2/src/facade/lang", [], true, function(require, exports, return val; } exports.deserializeEnum = deserializeEnum; + function resolveEnumToken(enumValue, val) { + return enumValue[val]; + } + exports.resolveEnumToken = resolveEnumToken; var StringWrapper = (function() { function StringWrapper() {} StringWrapper.fromCharCode = function(code) { @@ -308,6 +321,21 @@ System.register("angular2/src/facade/lang", [], true, function(require, exports, input: input }; }; + RegExpWrapper.replaceAll = function(regExp, input, replace) { + var c = regExp.exec(input); + var res = ''; + regExp.lastIndex = 0; + var prev = 0; + while (c) { + res += input.substring(prev, c.index); + res += replace(c); + prev = c.index + c[0].length; + regExp.lastIndex = prev; + c = regExp.exec(input); + } + res += input.substring(prev); + return res; + }; return RegExpWrapper; })(); exports.RegExpWrapper = RegExpWrapper; @@ -438,6 +466,41 @@ System.register("angular2/src/facade/lang", [], true, function(require, exports, return _symbolIterator; } exports.getSymbolIterator = getSymbolIterator; + function evalExpression(sourceUrl, expr, declarations, vars) { + var fnBody = declarations + "\nreturn " + expr + "\n//# sourceURL=" + sourceUrl; + var fnArgNames = []; + var fnArgValues = []; + for (var argName in vars) { + fnArgNames.push(argName); + fnArgValues.push(vars[argName]); + } + return new (Function.bind.apply(Function, [void 0].concat(fnArgNames.concat(fnBody))))().apply(void 0, fnArgValues); + } + exports.evalExpression = evalExpression; + function isPrimitive(obj) { + return !isJsObject(obj); + } + exports.isPrimitive = isPrimitive; + function hasConstructor(value, type) { + return value.constructor === type; + } + exports.hasConstructor = hasConstructor; + function bitWiseOr(values) { + return values.reduce(function(a, b) { + return a | b; + }); + } + exports.bitWiseOr = bitWiseOr; + function bitWiseAnd(values) { + return values.reduce(function(a, b) { + return a & b; + }); + } + exports.bitWiseAnd = bitWiseAnd; + function escape(s) { + return _global.encodeURI(s); + } + exports.escape = escape; global.define = __define; return module.exports; }); @@ -538,6 +601,7 @@ System.register("angular2/src/core/util/decorators", ["angular2/src/facade/lang" __define = global.define; global.define = undefined; var lang_1 = require("angular2/src/facade/lang"); + var _nextClassId = 0; function extractAnnotation(annotation) { if (lang_1.isFunction(annotation) && annotation.hasOwnProperty('annotation')) { annotation = annotation.annotation; @@ -600,13 +664,18 @@ System.register("angular2/src/core/util/decorators", ["angular2/src/facade/lang" if (this && this.annotations instanceof Array) { Reflect.defineMetadata('annotations', this.annotations, constructor); } + if (!constructor['name']) { + constructor['overriddenName'] = "class" + _nextClassId++; + } 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 checkReflect() { + if (!(Reflect && Reflect.getMetadata)) { + throw 'reflect-metadata shim is required when using class decorators'; + } + })(); function makeDecorator(annotationCls, chainFn) { if (chainFn === void 0) { chainFn = null; @@ -849,6 +918,12 @@ System.register("angular2/src/facade/collection", ["angular2/src/facade/lang"], StringMapWrapper.keys = function(map) { return Object.keys(map); }; + StringMapWrapper.values = function(map) { + return Object.keys(map).reduce(function(r, a) { + r.push(map[a]); + return r; + }, []); + }; StringMapWrapper.isEmpty = function(map) { for (var prop in map) { return false; @@ -908,6 +983,11 @@ System.register("angular2/src/facade/collection", ["angular2/src/facade/lang"], ListWrapper.clone = function(array) { return array.slice(0); }; + ListWrapper.createImmutable = function(array) { + var result = ListWrapper.clone(array); + Object.seal(result); + return result; + }; ListWrapper.forEachWithIndex = function(array, fn) { for (var i = 0; i < array.length; i++) { fn(array[i], i); @@ -1029,6 +1109,16 @@ System.register("angular2/src/facade/collection", ["angular2/src/facade/lang"], } return solution; }; + ListWrapper.isImmutable = function(list) { + return Object.isSealed(list); + }; + ListWrapper.flatten = function(array) { + var res = []; + array.forEach(function(a) { + return res = res.concat(a); + }); + return res; + }; return ListWrapper; })(); exports.ListWrapper = ListWrapper; @@ -1038,6 +1128,21 @@ System.register("angular2/src/facade/collection", ["angular2/src/facade/lang"], return lang_1.isArray(obj) || (!(obj instanceof exports.Map) && lang_1.getSymbolIterator() in obj); } exports.isListLikeIterable = isListLikeIterable; + function areIterablesEqual(a, b, comparator) { + var iterator1 = a[lang_1.getSymbolIterator()](); + var iterator2 = b[lang_1.getSymbolIterator()](); + while (true) { + var item1 = iterator1.next(); + var item2 = iterator2.next(); + if (item1.done && item2.done) + return true; + if (item1.done || item2.done) + return false; + if (!comparator(item1.value, item2.value)) + return false; + } + } + exports.areIterablesEqual = areIterablesEqual; function iterateListLike(obj, fn) { if (lang_1.isArray(obj)) { for (var i = 0; i < obj.length; i++) { @@ -1088,12 +1193,79 @@ System.register("angular2/src/facade/collection", ["angular2/src/facade/lang"], 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) { +System.register("angular2/src/facade/base_wrapped_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 BaseWrappedException = (function(_super) { + __extends(BaseWrappedException, _super); + function BaseWrappedException(message) { + _super.call(this, message); + } + Object.defineProperty(BaseWrappedException.prototype, "wrapperMessage", { + get: function() { + return ''; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseWrappedException.prototype, "wrapperStack", { + get: function() { + return null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseWrappedException.prototype, "originalException", { + get: function() { + return null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseWrappedException.prototype, "originalStack", { + get: function() { + return null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseWrappedException.prototype, "context", { + get: function() { + return null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseWrappedException.prototype, "message", { + get: function() { + return ''; + }, + enumerable: true, + configurable: true + }); + return BaseWrappedException; + })(Error); + exports.BaseWrappedException = BaseWrappedException; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/facade/exception_handler", ["angular2/src/facade/lang", "angular2/src/facade/base_wrapped_exception", "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 base_wrapped_exception_1 = require("angular2/src/facade/base_wrapped_exception"); var collection_1 = require("angular2/src/facade/collection"); var _ArrayLogger = (function() { function _ArrayLogger() { @@ -1166,14 +1338,14 @@ System.register("angular2/src/facade/exception_handler", ["angular2/src/facade/l throw exception; }; ExceptionHandler.prototype._extractMessage = function(exception) { - return exception instanceof exceptions_1.WrappedException ? exception.wrapperMessage : exception.toString(); + return exception instanceof base_wrapped_exception_1.BaseWrappedException ? 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)) + if (!(exception instanceof base_wrapped_exception_1.BaseWrappedException)) return null; return lang_1.isPresent(exception.context) ? exception.context : this._findContext(exception.originalException); } catch (e) { @@ -1181,22 +1353,22 @@ System.register("angular2/src/facade/exception_handler", ["angular2/src/facade/l } }; ExceptionHandler.prototype._findOriginalException = function(exception) { - if (!(exception instanceof exceptions_1.WrappedException)) + if (!(exception instanceof base_wrapped_exception_1.BaseWrappedException)) return null; var e = exception.originalException; - while (e instanceof exceptions_1.WrappedException && lang_1.isPresent(e.originalException)) { + while (e instanceof base_wrapped_exception_1.BaseWrappedException && lang_1.isPresent(e.originalException)) { e = e.originalException; } return e; }; ExceptionHandler.prototype._findOriginalStack = function(exception) { - if (!(exception instanceof exceptions_1.WrappedException)) + if (!(exception instanceof base_wrapped_exception_1.BaseWrappedException)) return null; var e = exception; var stack = exception.originalStack; - while (e instanceof exceptions_1.WrappedException && lang_1.isPresent(e.originalException)) { + while (e instanceof base_wrapped_exception_1.BaseWrappedException && lang_1.isPresent(e.originalException)) { e = e.originalException; - if (e instanceof exceptions_1.WrappedException && lang_1.isPresent(e.originalException)) { + if (e instanceof base_wrapped_exception_1.BaseWrappedException && lang_1.isPresent(e.originalException)) { stack = e.originalStack; } } @@ -1209,145 +1381,15 @@ System.register("angular2/src/facade/exception_handler", ["angular2/src/facade/l 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) { +System.register("angular2/src/core/reflection/reflector_reader", [], 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; + var ReflectorReader = (function() { + function ReflectorReader() {} + return ReflectorReader; })(); - exports.Reflector = Reflector; - function _mergeMaps(target, config) { - collection_1.StringMapWrapper.forEach(config, function(v, k) { - return target.set(k, v); - }); - } + exports.ReflectorReader = ReflectorReader; global.define = __define; return module.exports; }); @@ -1455,7 +1497,7 @@ System.register("angular2/src/core/reflection/reflection_capabilities", ["angula ; 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) { + ReflectionCapabilities.prototype._zipTypesAndAnnotations = function(paramTypes, paramAnnotations) { var result; if (typeof paramTypes === 'undefined') { result = new Array(paramAnnotations.length); @@ -1484,7 +1526,7 @@ System.register("angular2/src/core/reflection/reflection_capabilities", ["angula 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); + return this._zipTypesAndAnnotations(paramTypes, paramAnnotations); } } var parameters = new Array(typeOrFunc.length); @@ -1544,35 +1586,79 @@ System.register("angular2/src/core/reflection/reflection_capabilities", ["angula return module.exports; }); -System.register("angular2/src/core/di/type_literal", [], true, function(require, exports, module) { +System.register("angular2/src/core/di/key", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/core/di/forward_ref"], 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", { + var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var forward_ref_1 = require("angular2/src/core/di/forward_ref"); + 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() { - throw new Error("Type literals are only supported in Dart"); + return _globalKeyRegistry.numberOfKeys; }, enumerable: true, configurable: true }); - return TypeLiteral; + return Key; })(); - 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 __() { + exports.Key = Key; + var KeyRegistry = (function() { + function KeyRegistry() { + this._allKeys = new Map(); + } + KeyRegistry.prototype.get = function(token) { + if (token instanceof Key) + return token; + 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/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 __()); @@ -1708,7 +1794,7 @@ System.register("angular2/src/core/di/exceptions", ["angular2/src/facade/collect 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 "Cannot resolve all parameters for '" + lang_1.stringify(typeOrFunc) + "'(" + signature.join(', ') + "). " + "Make sure that all the parameters are decorated with Inject or have valid type annotations and that '" + lang_1.stringify(typeOrFunc) + "' is decorated with Injectable."; }; return NoAnnotationError; })(exceptions_1.BaseException); @@ -1915,45 +2001,152 @@ System.register("angular2/src/platform/dom/dom_tokens", ["angular2/src/core/di", return module.exports; }); -System.register("angular2/src/core/profile/wtf_impl", ["angular2/src/facade/lang"], true, function(require, exports, module) { +System.register("angular2/src/facade/promise", [], 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; - } + var PromiseCompleter = (function() { + function PromiseCompleter() { + var _this = this; + this.promise = new Promise(function(res, rej) { + _this.resolve = res; + _this.reject = rej; + }); } - return false; - } - exports.detectWTF = detectWTF; - function createScope(signature, flags) { - if (flags === void 0) { - flags = null; + return PromiseCompleter; + })(); + exports.PromiseCompleter = PromiseCompleter; + 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() { + return new PromiseCompleter(); + }; + return PromiseWrapper; + })(); + exports.PromiseWrapper = PromiseWrapper; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/zone/ng_zone_impl", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var NgZoneError = (function() { + function NgZoneError(error, stackTrace) { + this.error = error; + this.stackTrace = stackTrace; } - 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; + return NgZoneError; + })(); + exports.NgZoneError = NgZoneError; + var NgZoneImpl = (function() { + function NgZoneImpl(_a) { + var _this = this; + var trace = _a.trace, + onEnter = _a.onEnter, + onLeave = _a.onLeave, + setMicrotask = _a.setMicrotask, + setMacrotask = _a.setMacrotask, + onError = _a.onError; + this.onEnter = onEnter; + this.onLeave = onLeave; + this.setMicrotask = setMicrotask; + this.setMacrotask = setMacrotask; + this.onError = onError; + if (Zone) { + this.outer = this.inner = Zone.current; + if (Zone['wtfZoneSpec']) { + this.inner = this.inner.fork(Zone['wtfZoneSpec']); + } + if (trace && Zone['longStackTraceZoneSpec']) { + this.inner = this.inner.fork(Zone['longStackTraceZoneSpec']); + } + this.inner = this.inner.fork({ + name: 'angular', + properties: {'isAngularZone': true}, + onInvokeTask: function(delegate, current, target, task, applyThis, applyArgs) { + try { + _this.onEnter(); + return delegate.invokeTask(target, task, applyThis, applyArgs); + } finally { + _this.onLeave(); + } + }, + onInvoke: function(delegate, current, target, callback, applyThis, applyArgs, source) { + try { + _this.onEnter(); + return delegate.invoke(target, callback, applyThis, applyArgs, source); + } finally { + _this.onLeave(); + } + }, + onHasTask: function(delegate, current, target, hasTaskState) { + delegate.hasTask(target, hasTaskState); + if (current == target) { + if (hasTaskState.change == 'microTask') { + _this.setMicrotask(hasTaskState.microTask); + } else if (hasTaskState.change == 'macroTask') { + _this.setMacrotask(hasTaskState.macroTask); + } + } + }, + onHandleError: function(delegate, current, target, error) { + delegate.handleError(target, error); + _this.onError(new NgZoneError(error, error.stack)); + return false; + } + }); + } else { + throw new Error('Angular2 needs to be run with Zone.js polyfill.'); + } + } + NgZoneImpl.isInAngularZone = function() { + return Zone.current.get('isAngularZone') === true; + }; + NgZoneImpl.prototype.runInner = function(fn) { + return this.inner.runGuarded(fn); + }; + ; + NgZoneImpl.prototype.runOuter = function(fn) { + return this.outer.run(fn); + }; + ; + return NgZoneImpl; + })(); + exports.NgZoneImpl = NgZoneImpl; global.define = __define; return module.exports; }); @@ -2188,10 +2381,10 @@ System.register("angular2/src/core/change_detection/differs/iterable_differs", [ if (lang_1.isPresent(factory)) { return factory; } else { - throw new exceptions_1.BaseException("Cannot find a differ supporting object '" + iterable + "'"); + throw new exceptions_1.BaseException("Cannot find a differ supporting object '" + iterable + "' of type '" + lang_1.getTypeNameForDebugging(iterable) + "'"); } }; - IterableDiffers = __decorate([di_1.Injectable(), lang_1.CONST(), __metadata('design:paramtypes', [Array])], IterableDiffers); + IterableDiffers = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Array])], IterableDiffers); return IterableDiffers; })(); exports.IterableDiffers = IterableDiffers; @@ -2228,17 +2421,21 @@ System.register("angular2/src/core/change_detection/differs/default_iterable_dif DefaultIterableDifferFactory.prototype.supports = function(obj) { return collection_1.isListLikeIterable(obj); }; - DefaultIterableDifferFactory.prototype.create = function(cdRef) { - return new DefaultIterableDiffer(); + DefaultIterableDifferFactory.prototype.create = function(cdRef, trackByFn) { + return new DefaultIterableDiffer(trackByFn); }; DefaultIterableDifferFactory = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [])], DefaultIterableDifferFactory); return DefaultIterableDifferFactory; })(); exports.DefaultIterableDifferFactory = DefaultIterableDifferFactory; + var trackByIdentity = function(index, item) { + return item; + }; var DefaultIterableDiffer = (function() { - function DefaultIterableDiffer() { - this._collection = null; + function DefaultIterableDiffer(_trackByFn) { + this._trackByFn = _trackByFn; this._length = null; + this._collection = null; this._linkedRecords = null; this._unlinkedRecords = null; this._previousItHead = null; @@ -2250,6 +2447,9 @@ System.register("angular2/src/core/change_detection/differs/default_iterable_dif this._movesTail = null; this._removalsHead = null; this._removalsTail = null; + this._identityChangesHead = null; + this._identityChangesTail = null; + this._trackByFn = lang_2.isPresent(this._trackByFn) ? this._trackByFn : trackByIdentity; } Object.defineProperty(DefaultIterableDiffer.prototype, "collection", { get: function() { @@ -2295,6 +2495,12 @@ System.register("angular2/src/core/change_detection/differs/default_iterable_dif fn(record); } }; + DefaultIterableDiffer.prototype.forEachIdentityChange = function(fn) { + var record; + for (record = this._identityChangesHead; record !== null; record = record._nextIdentityChange) { + fn(record); + } + }; DefaultIterableDiffer.prototype.diff = function(collection) { if (lang_2.isBlank(collection)) collection = []; @@ -2315,40 +2521,54 @@ System.register("angular2/src/core/change_detection/differs/default_iterable_dif var mayBeDirty = false; var index; var item; + var itemTrackBy; 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); + if (collection !== this._collection || !collection_1.ListWrapper.isImmutable(collection)) { + var list = collection; + this._length = collection.length; + for (index = 0; index < this._length; index++) { + item = list[index]; + itemTrackBy = this._trackByFn(index, item); + if (record === null || !lang_2.looseIdentical(record.trackById, itemTrackBy)) { + record = this._mismatch(record, item, itemTrackBy, index); + mayBeDirty = true; + } else { + if (mayBeDirty) { + record = this._verifyReinsertion(record, item, itemTrackBy, index); + } + if (!lang_2.looseIdentical(record.item, item)) + this._addIdentityChange(record, item); + } + record = record._next; } - record = record._next; + this._truncate(record); } } else { index = 0; collection_1.iterateListLike(collection, function(item) { - if (record === null || !lang_2.looseIdentical(record.item, item)) { - record = _this._mismatch(record, item, index); + itemTrackBy = _this._trackByFn(index, item); + if (record === null || !lang_2.looseIdentical(record.trackById, itemTrackBy)) { + record = _this._mismatch(record, item, itemTrackBy, index); mayBeDirty = true; - } else if (mayBeDirty) { - record = _this._verifyReinsertion(record, item, index); + } else { + if (mayBeDirty) { + record = _this._verifyReinsertion(record, item, itemTrackBy, index); + } + if (!lang_2.looseIdentical(record.item, item)) + _this._addIdentityChange(record, item); } record = record._next; index++; }); this._length = index; + this._truncate(record); } - 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; + return this._additionsHead !== null || this._movesHead !== null || this._removalsHead !== null || this._identityChangesHead !== null; }, enumerable: true, configurable: true @@ -2370,9 +2590,10 @@ System.register("angular2/src/core/change_detection/differs/default_iterable_dif } this._movesHead = this._movesTail = null; this._removalsHead = this._removalsTail = null; + this._identityChangesHead = this._identityChangesTail = null; } }; - DefaultIterableDiffer.prototype._mismatch = function(record, item, index) { + DefaultIterableDiffer.prototype._mismatch = function(record, item, itemTrackBy, index) { var previousRecord; if (record === null) { previousRecord = this._itTail; @@ -2380,21 +2601,25 @@ System.register("angular2/src/core/change_detection/differs/default_iterable_dif previousRecord = record._prev; this._remove(record); } - record = this._linkedRecords === null ? null : this._linkedRecords.get(item, index); + record = this._linkedRecords === null ? null : this._linkedRecords.get(itemTrackBy, index); if (record !== null) { + if (!lang_2.looseIdentical(record.item, item)) + this._addIdentityChange(record, item); this._moveAfter(record, previousRecord, index); } else { - record = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(item); + record = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy); if (record !== null) { + if (!lang_2.looseIdentical(record.item, item)) + this._addIdentityChange(record, item); this._reinsertAfter(record, previousRecord, index); } else { - record = this._addAfter(new CollectionChangeRecord(item), previousRecord, index); + record = this._addAfter(new CollectionChangeRecord(item, itemTrackBy), previousRecord, index); } } return record; }; - DefaultIterableDiffer.prototype._verifyReinsertion = function(record, item, index) { - var reinsertRecord = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(item); + DefaultIterableDiffer.prototype._verifyReinsertion = function(record, item, itemTrackBy, index) { + var reinsertRecord = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy); if (reinsertRecord !== null) { record = this._reinsertAfter(reinsertRecord, record._prev, index); } else if (record.currentIndex != index) { @@ -2424,6 +2649,9 @@ System.register("angular2/src/core/change_detection/differs/default_iterable_dif if (this._removalsTail !== null) { this._removalsTail._nextRemoved = null; } + if (this._identityChangesTail !== null) { + this._identityChangesTail._nextIdentityChange = null; + } }; DefaultIterableDiffer.prototype._reinsertAfter = function(record, prevRecord, index) { if (this._unlinkedRecords !== null) { @@ -2529,36 +2757,49 @@ System.register("angular2/src/core/change_detection/differs/default_iterable_dif } return record; }; + DefaultIterableDiffer.prototype._addIdentityChange = function(record, item) { + record.item = item; + if (this._identityChangesTail === null) { + this._identityChangesTail = this._identityChangesHead = record; + } else { + this._identityChangesTail = this._identityChangesTail._nextIdentityChange = record; + } + return record; + }; DefaultIterableDiffer.prototype.toString = function() { - var record; var list = []; - for (record = this._itHead; record !== null; record = record._next) { - list.push(record); - } + this.forEachItem(function(record) { + return list.push(record); + }); var previous = []; - for (record = this._previousItHead; record !== null; record = record._nextPrevious) { - previous.push(record); - } + this.forEachPreviousItem(function(record) { + return previous.push(record); + }); var additions = []; - for (record = this._additionsHead; record !== null; record = record._nextAdded) { - additions.push(record); - } + this.forEachAddedItem(function(record) { + return additions.push(record); + }); var moves = []; - for (record = this._movesHead; record !== null; record = record._nextMoved) { - moves.push(record); - } + this.forEachMovedItem(function(record) { + return 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"; + this.forEachRemovedItem(function(record) { + return removals.push(record); + }); + var identityChanges = []; + this.forEachIdentityChange(function(record) { + return identityChanges.push(record); + }); + return "collection: " + list.join(', ') + "\n" + "previous: " + previous.join(', ') + "\n" + "additions: " + additions.join(', ') + "\n" + "moves: " + moves.join(', ') + "\n" + "removals: " + removals.join(', ') + "\n" + "identityChanges: " + identityChanges.join(', ') + "\n"; }; return DefaultIterableDiffer; })(); exports.DefaultIterableDiffer = DefaultIterableDiffer; var CollectionChangeRecord = (function() { - function CollectionChangeRecord(item) { + function CollectionChangeRecord(item, trackById) { this.item = item; + this.trackById = trackById; this.currentIndex = null; this.previousIndex = null; this._nextPrevious = null; @@ -2570,6 +2811,7 @@ System.register("angular2/src/core/change_detection/differs/default_iterable_dif this._nextRemoved = null; this._nextAdded = null; this._nextMoved = null; + this._nextIdentityChange = 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) + ']'; @@ -2594,10 +2836,10 @@ System.register("angular2/src/core/change_detection/differs/default_iterable_dif this._tail = record; } }; - _DuplicateItemRecordList.prototype.get = function(item, afterIndex) { + _DuplicateItemRecordList.prototype.get = function(trackById, afterIndex) { var record; for (record = this._head; record !== null; record = record._nextDup) { - if ((afterIndex === null || afterIndex < record.currentIndex) && lang_2.looseIdentical(record.item, item)) { + if ((afterIndex === null || afterIndex < record.currentIndex) && lang_2.looseIdentical(record.trackById, trackById)) { return record; } } @@ -2625,7 +2867,7 @@ System.register("angular2/src/core/change_detection/differs/default_iterable_dif this.map = new Map(); } _DuplicateMap.prototype.put = function(record) { - var key = lang_2.getMapKey(record.item); + var key = lang_2.getMapKey(record.trackById); var duplicates = this.map.get(key); if (!lang_2.isPresent(duplicates)) { duplicates = new _DuplicateItemRecordList(); @@ -2633,16 +2875,16 @@ System.register("angular2/src/core/change_detection/differs/default_iterable_dif } duplicates.add(record); }; - _DuplicateMap.prototype.get = function(value, afterIndex) { + _DuplicateMap.prototype.get = function(trackById, afterIndex) { if (afterIndex === void 0) { afterIndex = null; } - var key = lang_2.getMapKey(value); + var key = lang_2.getMapKey(trackById); var recordList = this.map.get(key); - return lang_2.isBlank(recordList) ? null : recordList.get(value, afterIndex); + return lang_2.isBlank(recordList) ? null : recordList.get(trackById, afterIndex); }; _DuplicateMap.prototype.remove = function(record) { - var key = lang_2.getMapKey(record.item); + var key = lang_2.getMapKey(record.trackById); var recordList = this.map.get(key); if (recordList.remove(record)) { this.map.delete(key); @@ -2726,7 +2968,7 @@ System.register("angular2/src/core/change_detection/differs/keyvalue_differs", [ 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); + KeyValueDiffers = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Array])], KeyValueDiffers); return KeyValueDiffers; })(); exports.KeyValueDiffers = KeyValueDiffers; @@ -2858,7 +3100,7 @@ System.register("angular2/src/core/change_detection/differs/default_keyvalue_dif if (records.has(key)) { newSeqRecord = records.get(key); } else { - newSeqRecord = new KVChangeRecord(key); + newSeqRecord = new KeyValueChangeRecord(key); records.set(key, newSeqRecord); newSeqRecord.currentValue = value; _this._addToAdditions(newSeqRecord); @@ -3001,8 +3243,8 @@ System.register("angular2/src/core/change_detection/differs/default_keyvalue_dif return DefaultKeyValueDiffer; })(); exports.DefaultKeyValueDiffer = DefaultKeyValueDiffer; - var KVChangeRecord = (function() { - function KVChangeRecord(key) { + var KeyValueChangeRecord = (function() { + function KeyValueChangeRecord(key) { this.key = key; this.previousValue = null; this.currentValue = null; @@ -3013,12 +3255,12 @@ System.register("angular2/src/core/change_detection/differs/default_keyvalue_dif this._prevRemoved = null; this._nextChanged = null; } - KVChangeRecord.prototype.toString = function() { + KeyValueChangeRecord.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; + return KeyValueChangeRecord; })(); - exports.KVChangeRecord = KVChangeRecord; + exports.KeyValueChangeRecord = KeyValueChangeRecord; global.define = __define; return module.exports; }); @@ -3784,18 +4026,14 @@ System.register("angular2/src/core/change_detection/parser/lexer", ["angular2/sr 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) { @@ -3806,11 +4044,9 @@ System.register("angular2/src/core/change_detection/parser/lexer", ["angular2/sr 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)) @@ -3823,7 +4059,6 @@ System.register("angular2/src/core/change_detection/parser/lexer", ["angular2/sr } }; _Scanner.prototype.scanNumber = function(start) { - assert(isDigit(this.peek)); var simple = (this.index === start); this.advance(); while (true) { @@ -3846,7 +4081,6 @@ System.register("angular2/src/core/change_detection/parser/lexer", ["angular2/sr 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(); @@ -3989,7 +4223,7 @@ System.register("angular2/src/core/change_detection/parser/parser", ["angular2/s 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 INTERPOLATION_REGEXP = /\{\{([\s\S]*?)\}\}/g; var ParseException = (function(_super) { __extends(ParseException, _super); function ParseException(message, input, errLocation, ctxLocation) { @@ -3997,6 +4231,14 @@ System.register("angular2/src/core/change_detection/parser/parser", ["angular2/s } return ParseException; })(exceptions_1.BaseException); + var SplitInterpolation = (function() { + function SplitInterpolation(strings, expressions) { + this.strings = strings; + this.expressions = expressions; + } + return SplitInterpolation; + })(); + exports.SplitInterpolation = SplitInterpolation; var Parser = (function() { function Parser(_lexer, providedReflector) { if (providedReflector === void 0) { @@ -4048,6 +4290,18 @@ System.register("angular2/src/core/change_detection/parser/parser", ["angular2/s return new _ParseAST(input, location, tokens, this._reflector, false).parseTemplateBindings(); }; Parser.prototype.parseInterpolation = function(input, location) { + var split = this.splitInterpolation(input, location); + if (split == null) + return null; + var expressions = []; + for (var i = 0; i < split.expressions.length; ++i) { + var tokens = this._lexer.tokenize(split.expressions[i]); + var ast = new _ParseAST(input, location, tokens, this._reflector, false).parseChain(); + expressions.push(ast); + } + return new ast_1.ASTWithSource(new ast_1.Interpolation(split.strings, expressions), input, location); + }; + Parser.prototype.splitInterpolation = function(input, location) { var parts = lang_1.StringWrapper.split(input, INTERPOLATION_REGEXP); if (parts.length <= 1) { return null; @@ -4059,14 +4313,12 @@ System.register("angular2/src/core/change_detection/parser/parser", ["angular2/s 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); + expressions.push(part); } 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); + return new SplitInterpolation(strings, expressions); }; Parser.prototype.wrapLiteralPrimitive = function(input, location) { return new ast_1.ASTWithSource(new ast_1.LiteralPrimitive(input), input, location); @@ -4623,7 +4875,7 @@ System.register("angular2/src/core/change_detection/parser/locals", ["angular2/s throw new exceptions_1.BaseException("Setting of new keys post-construction is not supported. Key: " + name + "."); } }; - Locals.prototype.clearValues = function() { + Locals.prototype.clearLocalValues = function() { collection_1.MapWrapper.clearValues(this.current); }; return Locals; @@ -4666,12 +4918,31 @@ System.register("angular2/src/core/change_detection/exceptions", ["angular2/src/ exports.ChangeDetectionError = ChangeDetectionError; var DehydratedException = (function(_super) { __extends(DehydratedException, _super); - function DehydratedException() { - _super.call(this, 'Attempt to detect changes on a dehydrated detector.'); + function DehydratedException(details) { + _super.call(this, "Attempt to use a dehydrated detector: " + details); } return DehydratedException; })(exceptions_1.BaseException); exports.DehydratedException = DehydratedException; + 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); + exports.EventEvaluationError = EventEvaluationError; + var EventEvaluationErrorContext = (function() { + function EventEvaluationErrorContext(element, componentElement, context, locals, injector) { + this.element = element; + this.componentElement = componentElement; + this.context = context; + this.locals = locals; + this.injector = injector; + } + return EventEvaluationErrorContext; + })(); + exports.EventEvaluationErrorContext = EventEvaluationErrorContext; global.define = __define; return module.exports; }); @@ -4736,10 +5007,9 @@ System.register("angular2/src/core/change_detection/constants", ["angular2/src/f 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_DETECTION_STRATEGY_VALUES = [ChangeDetectionStrategy.CheckOnce, ChangeDetectionStrategy.Checked, ChangeDetectionStrategy.CheckAlways, ChangeDetectionStrategy.Detached, ChangeDetectionStrategy.OnPush, ChangeDetectionStrategy.Default]; exports.CHANGE_DETECTOR_STATE_VALUES = [ChangeDetectorState.NeverChecked, ChangeDetectorState.CheckedBefore, ChangeDetectorState.Errored]; function isDefaultChangeDetectionStrategy(changeDetectionStrategy) { return lang_1.isBlank(changeDetectionStrategy) || changeDetectionStrategy === ChangeDetectionStrategy.Default; @@ -4922,7 +5192,9 @@ System.register("angular2/src/core/change_detection/directive_record", ["angular callOnChanges = _b.callOnChanges, callDoCheck = _b.callDoCheck, callOnInit = _b.callOnInit, - changeDetection = _b.changeDetection; + callOnDestroy = _b.callOnDestroy, + changeDetection = _b.changeDetection, + outputs = _b.outputs; this.directiveIndex = directiveIndex; this.callAfterContentInit = lang_1.normalizeBool(callAfterContentInit); this.callAfterContentChecked = lang_1.normalizeBool(callAfterContentChecked); @@ -4931,7 +5203,9 @@ System.register("angular2/src/core/change_detection/directive_record", ["angular this.callAfterViewChecked = lang_1.normalizeBool(callAfterViewChecked); this.callDoCheck = lang_1.normalizeBool(callDoCheck); this.callOnInit = lang_1.normalizeBool(callOnInit); + this.callOnDestroy = lang_1.normalizeBool(callOnDestroy); this.changeDetection = changeDetection; + this.outputs = outputs; } DirectiveRecord.prototype.isDefaultChangeDetection = function() { return constants_1.isDefaultChangeDetectionStrategy(this.changeDetection); @@ -4991,14 +5265,45 @@ System.register("angular2/src/core/change_detection/change_detector_ref", ["angu return module.exports; }); -System.register("angular2/src/core/change_detection/observable_facade", [], true, function(require, exports, module) { +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; - function isObservable(value) { + 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.isObservable = isObservable; + 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; }); @@ -5483,327 +5788,18 @@ System.register("angular2/src/core/prod_mode", ["angular2/src/facade/lang"], tru return module.exports; }); -System.register("angular2/src/facade/promise", [], true, function(require, exports, module) { +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 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"); + exports.Type = lang_1.Type; 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; + 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; }); @@ -5862,27 +5858,32 @@ System.register("angular2/src/core/testability/testability", ["angular2/src/core var async_1 = require("angular2/src/facade/async"); var Testability = (function() { function Testability(_ngZone) { + this._ngZone = _ngZone; this._pendingCount = 0; + this._isZoneStable = true; + this._didWork = false; this._callbacks = []; - this._isAngularEventPending = false; - this._watchAngularEvents(_ngZone); + this._watchAngularEvents(); } - Testability.prototype._watchAngularEvents = function(_ngZone) { + Testability.prototype._watchAngularEvents = function() { var _this = this; - async_1.ObservableWrapper.subscribe(_ngZone.onTurnStart, function(_) { - _this._isAngularEventPending = true; + async_1.ObservableWrapper.subscribe(this._ngZone.onUnstable, function(_) { + _this._didWork = true; + _this._isZoneStable = false; }); - _ngZone.runOutsideAngular(function() { - async_1.ObservableWrapper.subscribe(_ngZone.onEventDone, function(_) { - if (!_ngZone.hasPendingTimers) { - _this._isAngularEventPending = false; + this._ngZone.runOutsideAngular(function() { + async_1.ObservableWrapper.subscribe(_this._ngZone.onStable, function(_) { + ng_zone_1.NgZone.assertNotInAngularZone(); + lang_1.scheduleMicroTask(function() { + _this._isZoneStable = true; _this._runCallbacksIfReady(); - } + }); }); }); }; Testability.prototype.increasePendingRequestCount = function() { this._pendingCount += 1; + this._didWork = true; return this._pendingCount; }; Testability.prototype.decreasePendingRequestCount = function() { @@ -5894,18 +5895,20 @@ System.register("angular2/src/core/testability/testability", ["angular2/src/core return this._pendingCount; }; Testability.prototype.isStable = function() { - return this._pendingCount == 0 && !this._isAngularEventPending; + return this._isZoneStable && this._pendingCount == 0 && !this._ngZone.hasPendingMacrotasks; }; Testability.prototype._runCallbacksIfReady = function() { var _this = this; - if (!this.isStable()) { - return ; + if (this.isStable()) { + lang_1.scheduleMicroTask(function() { + while (_this._callbacks.length !== 0) { + (_this._callbacks.pop())(_this._didWork); + } + _this._didWork = false; + }); + } else { + this._didWork = true; } - async_1.PromiseWrapper.resolve(null).then(function(_) { - while (_this._callbacks.length !== 0) { - (_this._callbacks.pop())(); - } - }); }; Testability.prototype.whenStable = function(callback) { this._callbacks.push(callback); @@ -5914,9 +5917,6 @@ System.register("angular2/src/core/testability/testability", ["angular2/src/core Testability.prototype.getPendingRequestCount = function() { return this._pendingCount; }; - Testability.prototype.isAngularEventPending = function() { - return this._isAngularEventPending; - }; Testability.prototype.findBindings = function(using, provider, exactMatch) { return []; }; @@ -5941,6 +5941,9 @@ System.register("angular2/src/core/testability/testability", ["angular2/src/core TestabilityRegistry.prototype.getAllTestabilities = function() { return collection_1.MapWrapper.values(this._applications); }; + TestabilityRegistry.prototype.getAllRootElements = function() { + return collection_1.MapWrapper.keys(this._applications); + }; TestabilityRegistry.prototype.findTestabilityInTree = function(elem, findInAncestors) { if (findInAncestors === void 0) { findInAncestors = true; @@ -5969,7 +5972,63 @@ System.register("angular2/src/core/testability/testability", ["angular2/src/core return module.exports; }); -System.register("angular2/src/core/render/api", ["angular2/src/facade/exceptions"], true, function(require, exports, module) { +System.register("angular2/src/core/linker/view_type", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + (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; + 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 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 + }); + return ElementRef; + })(); + exports.ElementRef = ElementRef; + var ElementRef_ = (function() { + function ElementRef_(_appElement) { + this._appElement = _appElement; + } + Object.defineProperty(ElementRef_.prototype, "internalElement", { + get: function() { + return this._appElement; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ElementRef_.prototype, "nativeElement", { + get: function() { + return this._appElement.nativeElement; + }, + enumerable: true, + configurable: true + }); + return ElementRef_; + })(); + exports.ElementRef_ = ElementRef_; + 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"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -5982,41 +6041,24 @@ System.register("angular2/src/core/render/api", ["angular2/src/facade/exceptions } 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 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", { + var lang_1 = require("angular2/src/facade/lang"); + var ViewContainerRef = (function() { + function ViewContainerRef() {} + Object.defineProperty(ViewContainerRef.prototype, "element", { get: function() { return exceptions_1.unimplemented(); }, enumerable: true, configurable: true }); - ; - Object.defineProperty(RenderBeginCmd.prototype, "isBound", { + 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(); }, @@ -6024,145 +6066,246 @@ System.register("angular2/src/core/render/api", ["angular2/src/facade/exceptions configurable: true }); ; - return RenderBeginCmd; - })(RenderTemplateCmd); - exports.RenderBeginCmd = RenderBeginCmd; - var RenderTextCmd = (function(_super) { - __extends(RenderTextCmd, _super); - function RenderTextCmd() { - _super.apply(this, arguments); + return ViewContainerRef; + })(); + exports.ViewContainerRef = ViewContainerRef; + var ViewContainerRef_ = (function(_super) { + __extends(ViewContainerRef_, _super); + function ViewContainerRef_(_element) { + _super.call(this); + this._element = _element; } - Object.defineProperty(RenderTextCmd.prototype, "value", { + ViewContainerRef_.prototype.get = function(index) { + return this._element.nestedViews[index].ref; + }; + Object.defineProperty(ViewContainerRef_.prototype, "length", { get: function() { - return exceptions_1.unimplemented(); + var views = this._element.nestedViews; + return lang_1.isPresent(views) ? views.length : 0; }, 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", { + Object.defineProperty(ViewContainerRef_.prototype, "element", { get: function() { - return exceptions_1.unimplemented(); + return this._element.ref; }, 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); + ViewContainerRef_.prototype.createEmbeddedView = function(templateRef, index) { + if (index === void 0) { + index = -1; + } + if (index == -1) + index = this.length; + var vm = this._element.parentView.viewManager; + return vm.createEmbeddedViewInContainer(this._element.ref, index, templateRef); + }; + ViewContainerRef_.prototype.createHostView = function(hostViewFactoryRef, index, dynamicallyCreatedProviders, projectableNodes) { + if (index === void 0) { + index = -1; + } + if (dynamicallyCreatedProviders === void 0) { + dynamicallyCreatedProviders = null; + } + if (projectableNodes === void 0) { + projectableNodes = null; + } + if (index == -1) + index = this.length; + var vm = this._element.parentView.viewManager; + return vm.createHostViewInContainer(this._element.ref, index, hostViewFactoryRef, dynamicallyCreatedProviders, projectableNodes); + }; + ViewContainerRef_.prototype.insert = function(viewRef, index) { + if (index === void 0) { + index = -1; + } + if (index == -1) + index = this.length; + var vm = this._element.parentView.viewManager; + return vm.attachViewInContainer(this._element.ref, index, viewRef); + }; + ViewContainerRef_.prototype.indexOf = function(viewRef) { + return collection_1.ListWrapper.indexOf(this._element.nestedViews, viewRef.internalView); + }; + ViewContainerRef_.prototype.remove = function(index) { + if (index === void 0) { + index = -1; + } + if (index == -1) + index = this.length - 1; + var vm = this._element.parentView.viewManager; + return vm.destroyViewInContainer(this._element.ref, index); + }; + ViewContainerRef_.prototype.detach = function(index) { + if (index === void 0) { + index = -1; + } + if (index == -1) + index = this.length - 1; + var vm = this._element.parentView.viewManager; + return vm.detachViewInContainer(this._element.ref, index); + }; + return ViewContainerRef_; + })(ViewContainerRef); + exports.ViewContainerRef_ = ViewContainerRef_; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/render/api", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var RenderComponentType = (function() { + function RenderComponentType(id, encapsulation, styles) { + this.id = id; + this.encapsulation = encapsulation; + this.styles = styles; + } + return RenderComponentType; + })(); + exports.RenderComponentType = RenderComponentType; + var RenderDebugInfo = (function() { + function RenderDebugInfo(injector, component, providerTokens, locals) { + this.injector = injector; + this.component = component; + this.providerTokens = providerTokens; + this.locals = locals; + } + return RenderDebugInfo; + })(); + exports.RenderDebugInfo = RenderDebugInfo; + var Renderer = (function() { + function Renderer() {} + return Renderer; + })(); + exports.Renderer = Renderer; + var RootRenderer = (function() { + function RootRenderer() {} + return RootRenderer; + })(); + exports.RootRenderer = RootRenderer; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/core/linker/template_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; } - Object.defineProperty(RenderBeginElementCmd.prototype, "name", { + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var TemplateRef = (function() { + function TemplateRef() {} + Object.defineProperty(TemplateRef.prototype, "elementRef", { get: function() { - return exceptions_1.unimplemented(); + return null; }, enumerable: true, configurable: true }); - ; - Object.defineProperty(RenderBeginElementCmd.prototype, "attrNameAndValues", { + return TemplateRef; + })(); + exports.TemplateRef = TemplateRef; + var TemplateRef_ = (function(_super) { + __extends(TemplateRef_, _super); + function TemplateRef_(_elementRef) { + _super.call(this); + this._elementRef = _elementRef; + } + Object.defineProperty(TemplateRef_.prototype, "elementRef", { get: function() { - return exceptions_1.unimplemented(); + return this._elementRef; }, enumerable: true, configurable: true }); - ; - Object.defineProperty(RenderBeginElementCmd.prototype, "eventTargetAndNames", { + return TemplateRef_; + })(TemplateRef); + exports.TemplateRef_ = TemplateRef_; + 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 exceptions_1.unimplemented(); + return this._emitter; }, 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", { + Object.defineProperty(QueryList.prototype, "length", { get: function() { - return exceptions_1.unimplemented(); + return this._results.length; }, 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", { + Object.defineProperty(QueryList.prototype, "first", { get: function() { - return exceptions_1.unimplemented(); + return collection_1.ListWrapper.first(this._results); }, enumerable: true, configurable: true }); - ; - Object.defineProperty(RenderEmbeddedTemplateCmd.prototype, "children", { + Object.defineProperty(QueryList.prototype, "last", { get: function() { - return exceptions_1.unimplemented(); + return collection_1.ListWrapper.last(this._results); }, 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; + 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.forEach = function(fn) { + this._results.forEach(fn); + }; + 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.Renderer = Renderer; + exports.QueryList = QueryList; global.define = __define; return module.exports; }); @@ -6201,23 +6344,7 @@ System.register("angular2/src/core/pipes/pipe_provider", ["angular2/src/core/di/ 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) { +System.register("angular2/src/core/linker/view_ref", ["angular2/src/facade/exceptions"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -6230,24 +6357,20 @@ System.register("angular2/src/core/linker/view_ref", ["angular2/src/facade/lang" } 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 + }); + ; + Object.defineProperty(ViewRef.prototype, "destroyed", { + get: function() { + return exceptions_1.unimplemented(); }, enumerable: true, configurable: true @@ -6255,33 +6378,60 @@ System.register("angular2/src/core/linker/view_ref", ["angular2/src/facade/lang" return ViewRef; })(); exports.ViewRef = ViewRef; - var ViewRef_ = (function(_super) { - __extends(ViewRef_, _super); + var HostViewRef = (function(_super) { + __extends(HostViewRef, _super); + function HostViewRef() { + _super.apply(this, arguments); + } + Object.defineProperty(HostViewRef.prototype, "rootNodes", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + return HostViewRef; + })(ViewRef); + exports.HostViewRef = HostViewRef; + var EmbeddedViewRef = (function(_super) { + __extends(EmbeddedViewRef, _super); + function EmbeddedViewRef() { + _super.apply(this, arguments); + } + Object.defineProperty(EmbeddedViewRef.prototype, "rootNodes", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + ; + return EmbeddedViewRef; + })(ViewRef); + exports.EmbeddedViewRef = EmbeddedViewRef; + var ViewRef_ = (function() { function ViewRef_(_view) { - _super.call(this); - this._changeDetectorRef = null; + this._view = _view; this._view = _view; } - Object.defineProperty(ViewRef_.prototype, "render", { + Object.defineProperty(ViewRef_.prototype, "internalView", { get: function() { - return this._view.render; + return this._view; }, enumerable: true, configurable: true }); - Object.defineProperty(ViewRef_.prototype, "renderFragment", { + Object.defineProperty(ViewRef_.prototype, "changeDetectorRef", { get: function() { - return this._view.renderFragment; + return this._view.changeDetector.ref; }, enumerable: true, configurable: true }); - Object.defineProperty(ViewRef_.prototype, "changeDetectorRef", { + Object.defineProperty(ViewRef_.prototype, "rootNodes", { get: function() { - if (this._changeDetectorRef === null) { - this._changeDetectorRef = this._view.changeDetector.ref; - } - return this._changeDetectorRef; + return this._view.flatRootNodes; }, enumerable: true, configurable: true @@ -6289,142 +6439,82 @@ System.register("angular2/src/core/linker/view_ref", ["angular2/src/facade/lang" ViewRef_.prototype.setLocal = function(variableName, value) { this._view.setLocal(variableName, value); }; + ViewRef_.prototype.hasLocal = function(variableName) { + return this._view.hasLocal(variableName); + }; + Object.defineProperty(ViewRef_.prototype, "destroyed", { + get: function() { + return this._view.destroyed; + }, + enumerable: true, + configurable: true + }); 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; + var HostViewFactoryRef = (function() { + function HostViewFactoryRef() {} + return HostViewFactoryRef; + })(); + exports.HostViewFactoryRef = HostViewFactoryRef; + var HostViewFactoryRef_ = (function() { + function HostViewFactoryRef_(_hostViewFactory) { + this._hostViewFactory = _hostViewFactory; } - return ProtoViewRef_; - })(ProtoViewRef); - exports.ProtoViewRef_ = ProtoViewRef_; + Object.defineProperty(HostViewFactoryRef_.prototype, "internalHostViewFactory", { + get: function() { + return this._hostViewFactory; + }, + enumerable: true, + configurable: true + }); + return HostViewFactoryRef_; + })(); + exports.HostViewFactoryRef_ = HostViewFactoryRef_; global.define = __define; return module.exports; }); -System.register("angular2/src/core/render/util", ["angular2/src/facade/lang"], true, function(require, exports, module) { +System.register("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 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.'); - } + var SelectedPipe = (function() { + function SelectedPipe(pipe, pure) { + this.pipe = pipe; + this.pure = pure; } - return ElementBinder; + return SelectedPipe; })(); - exports.ElementBinder = ElementBinder; + exports.SelectedPipe = SelectedPipe; global.define = __define; return module.exports; }); -System.register("angular2/src/core/linker/element_ref", ["angular2/src/facade/exceptions"], true, function(require, exports, module) { +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 __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 + 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(); }); - Object.defineProperty(ElementRef_.prototype, "nativeElement", { - get: function() { - return this._renderer.getNativeElementSync(this); - }, - enumerable: true, - configurable: true + } + exports.camelCaseToDashCase = camelCaseToDashCase; + function dashCaseToCamelCase(input) { + return lang_1.StringWrapper.replaceAllMapped(input, DASH_CASE_REGEXP, function(m) { + return m[1].toUpperCase(); }); - return ElementRef_; - })(ElementRef); - exports.ElementRef_ = ElementRef_; + } + exports.dashCaseToCamelCase = dashCaseToCamelCase; 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) { +System.register("angular2/src/core/linker/view_manager", ["angular2/src/core/di", "angular2/src/facade/lang", "angular2/src/facade/collection", "angular2/src/facade/exceptions", "angular2/src/core/linker/view", "angular2/src/core/render/api", "angular2/src/core/profile/profile", "angular2/src/core/application_tokens", "angular2/src/core/linker/view_type"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -6437,44 +6527,6 @@ System.register("angular2/src/core/linker/template_ref", ["angular2/src/core/lin } 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, @@ -6499,41 +6551,157 @@ System.register("angular2/src/core/linker/view_pool", ["angular2/src/core/di", " 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; + var exceptions_1 = require("angular2/src/facade/exceptions"); + var view_1 = require("angular2/src/core/linker/view"); + var api_1 = require("angular2/src/core/render/api"); + var profile_1 = require("angular2/src/core/profile/profile"); + var application_tokens_1 = require("angular2/src/core/application_tokens"); + var view_type_1 = require("angular2/src/core/linker/view_type"); + var AppViewManager = (function() { + function AppViewManager() {} + return AppViewManager; + })(); + exports.AppViewManager = AppViewManager; + var AppViewManager_ = (function(_super) { + __extends(AppViewManager_, _super); + function AppViewManager_(_renderer, _appId) { + _super.call(this); + this._renderer = _renderer; + this._appId = _appId; + this._nextCompTypeId = 0; + 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()'); } - AppViewPool.prototype.getView = function(protoView) { - var pooledViews = this._pooledViewsPerProtoView.get(protoView); - if (lang_1.isPresent(pooledViews) && pooledViews.length > 0) { - return pooledViews.pop(); + AppViewManager_.prototype.getViewContainer = function(location) { + return location.internalElement.getViewContainerRef(); + }; + AppViewManager_.prototype.getHostElement = function(hostViewRef) { + var hostView = hostViewRef.internalView; + if (hostView.proto.type !== view_type_1.ViewType.HOST) { + throw new exceptions_1.BaseException('This operation is only allowed on host views'); } - return null; + return hostView.appElements[0].ref; }; - 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); + AppViewManager_.prototype.getNamedElementInComponentView = function(hostLocation, variableName) { + var appEl = hostLocation.internalElement; + var componentView = appEl.componentView; + if (lang_1.isBlank(componentView)) { + throw new exceptions_1.BaseException("There is no component directive at element " + hostLocation); } - var haveRemainingCapacity = pooledViews.length < this._poolCapacityPerProtoView; - if (haveRemainingCapacity) { - pooledViews.push(view); + for (var i = 0; i < componentView.appElements.length; i++) { + var compAppEl = componentView.appElements[i]; + if (collection_1.StringMapWrapper.contains(compAppEl.proto.directiveVariableBindings, variableName)) { + return compAppEl.ref; + } } - return haveRemainingCapacity; + throw new exceptions_1.BaseException("Could not find variable " + variableName); }; - 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; + AppViewManager_.prototype.getComponent = function(hostLocation) { + return hostLocation.internalElement.getComponent(); + }; + AppViewManager_.prototype.createRootHostView = function(hostViewFactoryRef, overrideSelector, injector, projectableNodes) { + if (projectableNodes === void 0) { + projectableNodes = null; + } + var s = this._createRootHostViewScope(); + var hostViewFactory = hostViewFactoryRef.internalHostViewFactory; + var selector = lang_1.isPresent(overrideSelector) ? overrideSelector : hostViewFactory.selector; + var view = hostViewFactory.viewFactory(this._renderer, this, null, projectableNodes, selector, null, injector); + return profile_1.wtfLeave(s, view.ref); + }; + AppViewManager_.prototype.destroyRootHostView = function(hostViewRef) { + var s = this._destroyRootHostViewScope(); + var hostView = hostViewRef.internalView; + hostView.renderer.detachView(view_1.flattenNestedViewRenderNodes(hostView.rootNodesOrAppElements)); + hostView.destroy(); + profile_1.wtfLeave(s); + }; + AppViewManager_.prototype.createEmbeddedViewInContainer = function(viewContainerLocation, index, templateRef) { + var s = this._createEmbeddedViewInContainerScope(); + var contextEl = templateRef.elementRef.internalElement; + var view = contextEl.embeddedViewFactory(contextEl.parentView.renderer, this, contextEl, contextEl.parentView.projectableNodes, null, null, null); + this._attachViewToContainer(view, viewContainerLocation.internalElement, index); + return profile_1.wtfLeave(s, view.ref); + }; + AppViewManager_.prototype.createHostViewInContainer = function(viewContainerLocation, index, hostViewFactoryRef, dynamicallyCreatedProviders, projectableNodes) { + var s = this._createHostViewInContainerScope(); + var viewContainerLocation_ = viewContainerLocation; + var contextEl = viewContainerLocation_.internalElement; + var hostViewFactory = hostViewFactoryRef.internalHostViewFactory; + var view = hostViewFactory.viewFactory(contextEl.parentView.renderer, contextEl.parentView.viewManager, contextEl, projectableNodes, null, dynamicallyCreatedProviders, null); + this._attachViewToContainer(view, viewContainerLocation_.internalElement, index); + return profile_1.wtfLeave(s, view.ref); + }; + AppViewManager_.prototype.destroyViewInContainer = function(viewContainerLocation, index) { + var s = this._destroyViewInContainerScope(); + var view = this._detachViewInContainer(viewContainerLocation.internalElement, index); + view.destroy(); + profile_1.wtfLeave(s); + }; + AppViewManager_.prototype.attachViewInContainer = function(viewContainerLocation, index, viewRef) { + var viewRef_ = viewRef; + var s = this._attachViewInContainerScope(); + this._attachViewToContainer(viewRef_.internalView, viewContainerLocation.internalElement, index); + return profile_1.wtfLeave(s, viewRef_); + }; + AppViewManager_.prototype.detachViewInContainer = function(viewContainerLocation, index) { + var s = this._detachViewInContainerScope(); + var view = this._detachViewInContainer(viewContainerLocation.internalElement, index); + return profile_1.wtfLeave(s, view.ref); + }; + AppViewManager_.prototype.onViewCreated = function(view) {}; + AppViewManager_.prototype.onViewDestroyed = function(view) {}; + AppViewManager_.prototype.createRenderComponentType = function(encapsulation, styles) { + return new api_1.RenderComponentType(this._appId + "-" + this._nextCompTypeId++, encapsulation, styles); + }; + AppViewManager_.prototype._attachViewToContainer = function(view, vcAppElement, viewIndex) { + if (view.proto.type === view_type_1.ViewType.COMPONENT) { + throw new exceptions_1.BaseException("Component views can't be moved!"); + } + var nestedViews = vcAppElement.nestedViews; + if (nestedViews == null) { + nestedViews = []; + vcAppElement.nestedViews = nestedViews; + } + collection_1.ListWrapper.insert(nestedViews, viewIndex, view); + var refNode; + if (viewIndex > 0) { + var prevView = nestedViews[viewIndex - 1]; + refNode = prevView.rootNodesOrAppElements.length > 0 ? prevView.rootNodesOrAppElements[prevView.rootNodesOrAppElements.length - 1] : null; + } else { + refNode = vcAppElement.nativeElement; + } + if (lang_1.isPresent(refNode)) { + var refRenderNode = view_1.findLastRenderNode(refNode); + view.renderer.attachViewAfter(refRenderNode, view_1.flattenNestedViewRenderNodes(view.rootNodesOrAppElements)); + } + vcAppElement.parentView.changeDetector.addContentChild(view.changeDetector); + vcAppElement.traverseAndSetQueriesAsDirty(); + }; + AppViewManager_.prototype._detachViewInContainer = function(vcAppElement, viewIndex) { + var view = collection_1.ListWrapper.removeAt(vcAppElement.nestedViews, viewIndex); + if (view.proto.type === view_type_1.ViewType.COMPONENT) { + throw new exceptions_1.BaseException("Component views can't be moved!"); + } + vcAppElement.traverseAndSetQueriesAsDirty(); + view.renderer.detachView(view_1.flattenNestedViewRenderNodes(view.rootNodesOrAppElements)); + view.changeDetector.remove(); + return view; + }; + AppViewManager_ = __decorate([di_1.Injectable(), __param(1, di_1.Inject(application_tokens_1.APP_ID)), __metadata('design:paramtypes', [api_1.RootRenderer, String])], AppViewManager_); + return AppViewManager_; + })(AppViewManager); + exports.AppViewManager_ = AppViewManager_; global.define = __define; return module.exports; }); -System.register("angular2/src/core/linker/view_listener", ["angular2/src/core/di"], true, function(require, exports, module) { +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; @@ -6554,298 +6722,93 @@ System.register("angular2/src/core/linker/view_listener", ["angular2/src/core/di 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; + 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/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) { +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 __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 api_1 = require("angular2/src/core/render/api"); + exports.RootRenderer = api_1.RootRenderer; + exports.Renderer = api_1.Renderer; + exports.RenderComponentType = api_1.RenderComponentType; + 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", "angular2/src/core/reflection/reflector_reader"], 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 collection_1 = require("angular2/src/facade/collection"); - var exceptions_1 = require("angular2/src/facade/exceptions"); + 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 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); + 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"); + var reflector_reader_1 = require("angular2/src/core/reflection/reflector_reader"); + function _isDirectiveMetadata(type) { + return type instanceof metadata_1.DirectiveMetadata; + } + var DirectiveResolver = (function() { + function DirectiveResolver(_reflector) { + if (lang_1.isPresent(_reflector)) { + this._reflector = _reflector; + } else { + this._reflector = reflection_1.reflector; } - }; - 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)); + var typeMetadata = this._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); + var propertyMetadata = this._reflector.propMetadata(type); + return this._mergeWithPropertyMetadata(metadata, propertyMetadata, type); } } throw new exceptions_1.BaseException("No Directive annotation found on " + lang_1.stringify(type)); }; - DirectiveResolver.prototype._mergeWithPropertyMetadata = function(dm, propertyMetadata) { + DirectiveResolver.prototype._mergeWithPropertyMetadata = function(dm, propertyMetadata, directiveType) { var inputs = []; var outputs = []; var host = {}; @@ -6891,11 +6854,21 @@ System.register("angular2/src/core/linker/directive_resolver", ["angular2/src/co } }); }); - return this._merge(dm, inputs, outputs, host, queries); + return this._merge(dm, inputs, outputs, host, queries, directiveType); }; - DirectiveResolver.prototype._merge = function(dm, inputs, outputs, host, queries) { + DirectiveResolver.prototype._merge = function(dm, inputs, outputs, host, queries, directiveType) { 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 mergedOutputs; + if (lang_1.isPresent(dm.outputs)) { + dm.outputs.forEach(function(propName) { + if (collection_1.ListWrapper.contains(outputs, propName)) { + throw new exceptions_1.BaseException("Output event '" + propName + "' defined multiple times in '" + lang_1.stringify(directiveType) + "'"); + } + }); + mergedOutputs = collection_1.ListWrapper.concat(dm.outputs, outputs); + } else { + mergedOutputs = 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) { @@ -6923,15 +6896,16 @@ System.register("angular2/src/core/linker/directive_resolver", ["angular2/src/co }); } }; - DirectiveResolver = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], DirectiveResolver); + DirectiveResolver = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [reflector_reader_1.ReflectorReader])], DirectiveResolver); return DirectiveResolver; })(); exports.DirectiveResolver = DirectiveResolver; + exports.CODEGEN_DIRECTIVE_RESOLVER = new DirectiveResolver(reflection_1.reflector); 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) { +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/reflector_reader", "angular2/src/core/reflection/reflection"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -6957,10 +6931,16 @@ System.register("angular2/src/core/linker/view_resolver", ["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 reflector_reader_1 = require("angular2/src/core/reflection/reflector_reader"); var reflection_1 = require("angular2/src/core/reflection/reflection"); var ViewResolver = (function() { - function ViewResolver() { + function ViewResolver(_reflector) { this._cache = new collection_1.Map(); + if (lang_1.isPresent(_reflector)) { + this._reflector = _reflector; + } else { + this._reflector = reflection_1.reflector; + } } ViewResolver.prototype.resolve = function(component) { var view = this._cache.get(component); @@ -6973,7 +6953,7 @@ System.register("angular2/src/core/linker/view_resolver", ["angular2/src/core/di ViewResolver.prototype._resolve = function(component) { var compMeta; var viewMeta; - reflection_1.reflector.annotations(component).forEach(function(m) { + this._reflector.annotations(component).forEach(function(m) { if (m instanceof view_1.ViewMetadata) { viewMeta = m; } @@ -6983,7 +6963,7 @@ System.register("angular2/src/core/linker/view_resolver", ["angular2/src/core/di }); 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."); + throw new exceptions_1.BaseException("Component '" + lang_1.stringify(component) + "' must have either 'template' or 'templateUrl' 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)) { @@ -7013,7 +6993,7 @@ System.register("angular2/src/core/linker/view_resolver", ["angular2/src/core/di } } else { if (lang_1.isBlank(viewMeta)) { - throw new exceptions_1.BaseException("No View decorator found on component '" + lang_1.stringify(component) + "'"); + throw new exceptions_1.BaseException("Could not compile '" + lang_1.stringify(component) + "' because it is not a component."); } else { return viewMeta; } @@ -7023,7 +7003,7 @@ System.register("angular2/src/core/linker/view_resolver", ["angular2/src/core/di 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); + ViewResolver = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [reflector_reader_1.ReflectorReader])], ViewResolver); return ViewResolver; })(); exports.ViewResolver = ViewResolver; @@ -7031,50 +7011,175 @@ System.register("angular2/src/core/linker/view_resolver", ["angular2/src/core/di 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) { +System.register("angular2/src/core/debug/debug_node", ["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 __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 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; + var collection_1 = require("angular2/src/facade/collection"); + var EventListener = (function() { + function EventListener(name, callback) { + this.name = name; + this.callback = callback; + } + ; + return EventListener; + })(); + exports.EventListener = EventListener; + var DebugNode = (function() { + function DebugNode(nativeNode, parent) { + this.nativeNode = nativeNode; + if (lang_1.isPresent(parent) && parent instanceof DebugElement) { + parent.addChild(this); + } else { + this.parent = null; + } + this.listeners = []; + this.providerTokens = []; + } + DebugNode.prototype.setDebugInfo = function(info) { + this.injector = info.injector; + this.providerTokens = info.providerTokens; + this.locals = info.locals; + this.componentInstance = info.component; + }; + DebugNode.prototype.inject = function(token) { + return this.injector.get(token); + }; + DebugNode.prototype.getLocal = function(name) { + return this.locals.get(name); + }; + return DebugNode; + })(); + exports.DebugNode = DebugNode; + var DebugElement = (function(_super) { + __extends(DebugElement, _super); + function DebugElement(nativeNode, parent) { + _super.call(this, nativeNode, parent); + this.properties = new Map(); + this.attributes = new Map(); + this.childNodes = []; + this.nativeElement = nativeNode; + } + DebugElement.prototype.addChild = function(child) { + if (lang_1.isPresent(child)) { + this.childNodes.push(child); + child.parent = this; + } + }; + DebugElement.prototype.removeChild = function(child) { + var childIndex = this.childNodes.indexOf(child); + if (childIndex !== -1) { + child.parent = null; + this.childNodes.splice(childIndex, 1); + } + }; + DebugElement.prototype.insertChildrenAfter = function(child, newChildren) { + var siblingIndex = this.childNodes.indexOf(child); + if (siblingIndex !== -1) { + var previousChildren = this.childNodes.slice(0, siblingIndex + 1); + var nextChildren = this.childNodes.slice(siblingIndex + 1); + this.childNodes = collection_1.ListWrapper.concat(collection_1.ListWrapper.concat(previousChildren, newChildren), nextChildren); + for (var i = 0; i < newChildren.length; ++i) { + var newChild = newChildren[i]; + if (lang_1.isPresent(newChild.parent)) { + newChild.parent.removeChild(newChild); + } + newChild.parent = this; } } - 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; + DebugElement.prototype.query = function(predicate) { + var results = this.queryAll(predicate); + return results.length > 0 ? results[0] : null; + }; + DebugElement.prototype.queryAll = function(predicate) { + var matches = []; + _queryElementChildren(this, predicate, matches); + return matches; + }; + DebugElement.prototype.queryAllNodes = function(predicate) { + var matches = []; + _queryNodeChildren(this, predicate, matches); + return matches; + }; + Object.defineProperty(DebugElement.prototype, "children", { + get: function() { + var children = []; + this.childNodes.forEach(function(node) { + if (node instanceof DebugElement) { + children.push(node); + } + }); + return children; + }, + enumerable: true, + configurable: true + }); + DebugElement.prototype.triggerEventHandler = function(eventName, eventObj) { + this.listeners.forEach(function(listener) { + if (listener.name == eventName) { + listener.callback(eventObj); + } + }); + }; + return DebugElement; + })(DebugNode); + exports.DebugElement = DebugElement; + function asNativeElements(debugEls) { + return debugEls.map(function(el) { + return el.nativeElement; + }); + } + exports.asNativeElements = asNativeElements; + function _queryElementChildren(element, predicate, matches) { + element.childNodes.forEach(function(node) { + if (node instanceof DebugElement) { + if (predicate(node)) { + matches.push(node); + } + _queryElementChildren(node, predicate, matches); + } + }); + } + function _queryNodeChildren(parentNode, predicate, matches) { + if (parentNode instanceof DebugElement) { + parentNode.childNodes.forEach(function(node) { + if (predicate(node)) { + matches.push(node); + } + if (node instanceof DebugElement) { + _queryNodeChildren(node, predicate, matches); + } + }); + } + } + var _nativeNodeToDebugNode = new Map(); + function getDebugNode(nativeNode) { + return _nativeNodeToDebugNode.get(nativeNode); + } + exports.getDebugNode = getDebugNode; + function getAllDebugNodes() { + return collection_1.MapWrapper.values(_nativeNodeToDebugNode); + } + exports.getAllDebugNodes = getAllDebugNodes; + function indexDebugNode(node) { + _nativeNodeToDebugNode.set(node.nativeNode, node); + } + exports.indexDebugNode = indexDebugNode; + function removeDebugNodeFromIndex(node) { + _nativeNodeToDebugNode.delete(node.nativeNode); + } + exports.removeDebugNodeFromIndex = removeDebugNodeFromIndex; global.define = __define; return module.exports; }); @@ -7091,211 +7196,28 @@ System.register("angular2/src/core/platform_directives_and_pipes", ["angular2/sr 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) { +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/reflection/reflector_reader", "angular2/src/core/testability/testability"], 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); - } + 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 reflector_reader_1 = require("angular2/src/core/reflection/reflector_reader"); + var testability_1 = require("angular2/src/core/testability/testability"); + function _reflector() { + return reflection_1.reflector; } - exports.visitAllCommands = visitAllCommands; + exports.PLATFORM_COMMON_PROVIDERS = lang_1.CONST_EXPR([new di_1.Provider(reflection_1.Reflector, { + useFactory: _reflector, + deps: [] + }), new di_1.Provider(reflector_reader_1.ReflectorReader, {useExisting: reflection_1.Reflector}), testability_1.TestabilityRegistry, console_1.Console]); 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) { +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/reflector_reader", "angular2/src/core/reflection/reflection"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -7317,84 +7239,261 @@ System.register("angular2/src/core/console", ["angular2/src/core/di", "angular2/ }; 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); + var exceptions_1 = require("angular2/src/facade/exceptions"); + var metadata_1 = require("angular2/src/core/metadata"); + var reflector_reader_1 = require("angular2/src/core/reflection/reflector_reader"); + var reflection_1 = require("angular2/src/core/reflection/reflection"); + function _isPipeMetadata(type) { + return type instanceof metadata_1.PipeMetadata; + } + var PipeResolver = (function() { + function PipeResolver(_reflector) { + if (lang_1.isPresent(_reflector)) { + this._reflector = _reflector; + } else { + this._reflector = reflection_1.reflector; + } + } + PipeResolver.prototype.resolve = function(type) { + var metas = this._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)); }; - Console = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], Console); - return Console; + PipeResolver = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [reflector_reader_1.ReflectorReader])], PipeResolver); + return PipeResolver; })(); - exports.Console = Console; + exports.PipeResolver = PipeResolver; + exports.CODEGEN_PIPE_RESOLVER = new PipeResolver(reflection_1.reflector); global.define = __define; return module.exports; }); -System.register("angular2/src/core/zone", ["angular2/src/core/zone/ng_zone"], true, function(require, exports, module) { +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 ng_zone_1 = require("angular2/src/core/zone/ng_zone"); - exports.NgZone = ng_zone_1.NgZone; - exports.NgZoneError = ng_zone_1.NgZoneError; + 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.providerTokens.indexOf(type) !== -1; + }; + }; + return By; + })(); + exports.By = By; global.define = __define; return module.exports; }); -System.register("angular2/src/core/render", ["angular2/src/core/render/api"], true, function(require, exports, module) { +System.register("angular2/src/core/debug/debug_renderer", ["angular2/src/facade/lang", "angular2/src/core/debug/debug_node"], 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; + var lang_1 = require("angular2/src/facade/lang"); + var debug_node_1 = require("angular2/src/core/debug/debug_node"); + var DebugDomRootRenderer = (function() { + function DebugDomRootRenderer(_delegate) { + this._delegate = _delegate; + } + DebugDomRootRenderer.prototype.renderComponent = function(componentProto) { + return new DebugDomRenderer(this, this._delegate.renderComponent(componentProto)); + }; + return DebugDomRootRenderer; + })(); + exports.DebugDomRootRenderer = DebugDomRootRenderer; + var DebugDomRenderer = (function() { + function DebugDomRenderer(_rootRenderer, _delegate) { + this._rootRenderer = _rootRenderer; + this._delegate = _delegate; + } + DebugDomRenderer.prototype.renderComponent = function(componentType) { + return this._rootRenderer.renderComponent(componentType); + }; + DebugDomRenderer.prototype.selectRootElement = function(selector) { + var nativeEl = this._delegate.selectRootElement(selector); + var debugEl = new debug_node_1.DebugElement(nativeEl, null); + debug_node_1.indexDebugNode(debugEl); + return nativeEl; + }; + DebugDomRenderer.prototype.createElement = function(parentElement, name) { + var nativeEl = this._delegate.createElement(parentElement, name); + var debugEl = new debug_node_1.DebugElement(nativeEl, debug_node_1.getDebugNode(parentElement)); + debugEl.name = name; + debug_node_1.indexDebugNode(debugEl); + return nativeEl; + }; + DebugDomRenderer.prototype.createViewRoot = function(hostElement) { + return this._delegate.createViewRoot(hostElement); + }; + DebugDomRenderer.prototype.createTemplateAnchor = function(parentElement) { + var comment = this._delegate.createTemplateAnchor(parentElement); + var debugEl = new debug_node_1.DebugNode(comment, debug_node_1.getDebugNode(parentElement)); + debug_node_1.indexDebugNode(debugEl); + return comment; + }; + DebugDomRenderer.prototype.createText = function(parentElement, value) { + var text = this._delegate.createText(parentElement, value); + var debugEl = new debug_node_1.DebugNode(text, debug_node_1.getDebugNode(parentElement)); + debug_node_1.indexDebugNode(debugEl); + return text; + }; + DebugDomRenderer.prototype.projectNodes = function(parentElement, nodes) { + var debugParent = debug_node_1.getDebugNode(parentElement); + if (lang_1.isPresent(debugParent) && debugParent instanceof debug_node_1.DebugElement) { + nodes.forEach(function(node) { + debugParent.addChild(debug_node_1.getDebugNode(node)); + }); + } + return this._delegate.projectNodes(parentElement, nodes); + }; + DebugDomRenderer.prototype.attachViewAfter = function(node, viewRootNodes) { + var debugNode = debug_node_1.getDebugNode(node); + if (lang_1.isPresent(debugNode)) { + var debugParent = debugNode.parent; + if (viewRootNodes.length > 0 && lang_1.isPresent(debugParent)) { + var debugViewRootNodes = []; + viewRootNodes.forEach(function(rootNode) { + return debugViewRootNodes.push(debug_node_1.getDebugNode(rootNode)); + }); + debugParent.insertChildrenAfter(debugNode, debugViewRootNodes); + } + } + return this._delegate.attachViewAfter(node, viewRootNodes); + }; + DebugDomRenderer.prototype.detachView = function(viewRootNodes) { + viewRootNodes.forEach(function(node) { + var debugNode = debug_node_1.getDebugNode(node); + if (lang_1.isPresent(debugNode) && lang_1.isPresent(debugNode.parent)) { + debugNode.parent.removeChild(debugNode); + } + }); + return this._delegate.detachView(viewRootNodes); + }; + DebugDomRenderer.prototype.destroyView = function(hostElement, viewAllNodes) { + viewAllNodes.forEach(function(node) { + debug_node_1.removeDebugNodeFromIndex(debug_node_1.getDebugNode(node)); + }); + return this._delegate.destroyView(hostElement, viewAllNodes); + }; + DebugDomRenderer.prototype.listen = function(renderElement, name, callback) { + var debugEl = debug_node_1.getDebugNode(renderElement); + if (lang_1.isPresent(debugEl)) { + debugEl.listeners.push(new debug_node_1.EventListener(name, callback)); + } + return this._delegate.listen(renderElement, name, callback); + }; + DebugDomRenderer.prototype.listenGlobal = function(target, name, callback) { + return this._delegate.listenGlobal(target, name, callback); + }; + DebugDomRenderer.prototype.setElementProperty = function(renderElement, propertyName, propertyValue) { + var debugEl = debug_node_1.getDebugNode(renderElement); + if (lang_1.isPresent(debugEl) && debugEl instanceof debug_node_1.DebugElement) { + debugEl.properties.set(propertyName, propertyValue); + } + return this._delegate.setElementProperty(renderElement, propertyName, propertyValue); + }; + DebugDomRenderer.prototype.setElementAttribute = function(renderElement, attributeName, attributeValue) { + var debugEl = debug_node_1.getDebugNode(renderElement); + if (lang_1.isPresent(debugEl) && debugEl instanceof debug_node_1.DebugElement) { + debugEl.attributes.set(attributeName, attributeValue); + } + return this._delegate.setElementAttribute(renderElement, attributeName, attributeValue); + }; + DebugDomRenderer.prototype.setBindingDebugInfo = function(renderElement, propertyName, propertyValue) { + return this._delegate.setBindingDebugInfo(renderElement, propertyName, propertyValue); + }; + DebugDomRenderer.prototype.setElementDebugInfo = function(renderElement, info) { + var debugEl = debug_node_1.getDebugNode(renderElement); + debugEl.setDebugInfo(info); + return this._delegate.setElementDebugInfo(renderElement, info); + }; + DebugDomRenderer.prototype.setElementClass = function(renderElement, className, isAdd) { + return this._delegate.setElementClass(renderElement, className, isAdd); + }; + DebugDomRenderer.prototype.setElementStyle = function(renderElement, styleName, styleValue) { + return this._delegate.setElementStyle(renderElement, styleName, styleValue); + }; + DebugDomRenderer.prototype.invokeElementMethod = function(renderElement, methodName, args) { + return this._delegate.invokeElementMethod(renderElement, methodName, args); + }; + DebugDomRenderer.prototype.setText = function(renderNode, text) { + return this._delegate.setText(renderNode, text); + }; + return DebugDomRenderer; + })(); + exports.DebugDomRenderer = DebugDomRenderer; 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) { +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 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; + 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() {} + Object.defineProperty(DomAdapter.prototype, "attrToPropMap", { + get: function() { + return this._attrToPropMap; + }, + set: function(value) { + this._attrToPropMap = value; + }, + enumerable: true, + configurable: true + }); + ; + ; + 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/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) { +System.register("angular2/src/facade/exceptions", ["angular2/src/facade/base_wrapped_exception", "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; @@ -7407,653 +7506,394 @@ System.register("angular2/src/core/debug/debug_element", ["angular2/src/facade/l } 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", { + var base_wrapped_exception_1 = require("angular2/src/facade/base_wrapped_exception"); + 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 exceptions_1.unimplemented(); + return this._wrapperMessage; }, 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", { + Object.defineProperty(WrappedException.prototype, "wrapperStack", { get: function() { - if (!lang_1.isPresent(this._elementInjector)) { - return null; - } - return this._elementInjector.getComponent(); + return this._wrapperStack; }, enumerable: true, configurable: true }); - Object.defineProperty(DebugElement_.prototype, "nativeElement", { + Object.defineProperty(WrappedException.prototype, "originalException", { get: function() { - return this.elementRef.nativeElement; + return this._originalException; }, enumerable: true, configurable: true }); - Object.defineProperty(DebugElement_.prototype, "elementRef", { + Object.defineProperty(WrappedException.prototype, "originalStack", { get: function() { - return this._parentView.elementRefs[this._boundElementIndex]; + return this._originalStack; }, enumerable: true, configurable: true }); - DebugElement_.prototype.getDirectiveInstance = function(directiveIndex) { - return this._elementInjector.getDirectiveAtIndex(directiveIndex); - }; - Object.defineProperty(DebugElement_.prototype, "children", { + Object.defineProperty(WrappedException.prototype, "context", { get: function() { - return this._getChildElements(this._parentView, this._boundElementIndex); + return this._context; }, enumerable: true, configurable: true }); - Object.defineProperty(DebugElement_.prototype, "componentViewChildren", { + Object.defineProperty(WrappedException.prototype, "message", { 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); + return exception_handler_1.ExceptionHandler.exceptionToString(this); }, 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; + WrappedException.prototype.toString = function() { + return this.message; }; - 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; - }); + return WrappedException; + })(base_wrapped_exception_1.BaseWrappedException); + exports.WrappedException = WrappedException; + function makeTypeError(message) { + return new TypeError(message); } - 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.makeTypeError = makeTypeError; + function unimplemented() { + throw new BaseException('unimplemented'); } - 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_})]); + exports.unimplemented = unimplemented; 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) { +System.register("angular2/src/core/reflection/reflector", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/core/reflection/reflector_reader"], 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 __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 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); + var reflector_reader_1 = require("angular2/src/core/reflection/reflector_reader"); + 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; } - 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); + return ReflectionInfo; + })(); + exports.ReflectionInfo = ReflectionInfo; + var Reflector = (function(_super) { + __extends(Reflector, _super); + function Reflector(reflectionCapabilities) { + _super.call(this); + 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(); }; - EventManager.prototype.getZone = function() { - return this._zone; + Reflector.prototype.trackUsage = function() { + this._usedKeys = new collection_1.Set(); }; - 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; - } + Reflector.prototype.listUnusedKeys = function() { + var _this = this; + if (this._usedKeys == null) { + throw new exceptions_1.BaseException('Usage tracking is disabled'); } - throw new exceptions_1.BaseException("No event manager plugin found for event " + eventName); + var allTypes = collection_1.MapWrapper.keys(this._injectableInfo); + return allTypes.filter(function(key) { + return !collection_1.SetWrapper.has(_this._usedKeys, key); + }); }; - 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; + Reflector.prototype.registerFunction = function(func, funcInfo) { + this._injectableInfo.set(func, funcInfo); }; - EventManagerPlugin.prototype.addEventListener = function(element, eventName, handler) { - throw "not implemented"; + Reflector.prototype.registerType = function(type, typeInfo) { + this._injectableInfo.set(type, typeInfo); }; - EventManagerPlugin.prototype.addGlobalEventListener = function(element, eventName, handler) { - throw "not implemented"; + Reflector.prototype.registerGetters = function(getters) { + _mergeMaps(this._getters, getters); }; - 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); + 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); } - 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; + 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); + } }; - 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); - }); + 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); + } }; - 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); - }); + 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); + } }; - 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; - }; + 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); + } }; - By.css = function(selector) { - return function(debugElement) { - return lang_1.isPresent(debugElement.nativeElement) ? dom_adapter_1.DOM.elementMatches(debugElement.nativeElement, selector) : false; - }; + Reflector.prototype.getter = function(name) { + if (this._getters.has(name)) { + return this._getters.get(name); + } else { + return this.reflectionCapabilities.getter(name); + } }; - By.directive = function(type) { - return function(debugElement) { - return debugElement.hasDirective(type); - }; + Reflector.prototype.setter = function(name) { + if (this._setters.has(name)) { + return this._setters.get(name); + } else { + return this.reflectionCapabilities.setter(name); + } }; - return By; - })(); - exports.By = By; + 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; + })(reflector_reader_1.ReflectorReader); + 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/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) { +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 __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 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 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); + 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(); }); - } 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]); + 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(); } - } - 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]); + }; + 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; }; - DebugElementViewListener.prototype.onViewDestroyed = function(view) { - var viewId = _allIdsByView.get(view); - _allIdsByView.delete(view); - _allViewsById.delete(viewId); + 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; }; - 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; + Animation.prototype.stripLetters = function(str) { + return lang_1.StringWrapper.replaceAll(str, lang_1.RegExpWrapper.create('[^0-9]+$', ''), ''); + }; + return Animation; })(); - 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); + exports.Animation = Animation; 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) { +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; @@ -8066,497 +7906,136 @@ System.register("angular2/src/facade/exceptions", ["angular2/src/facade/exceptio } 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; + 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); }; - 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; + }; + 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(); } - 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; + 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); }; - 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)); + SharedStylesHost.prototype.onStylesAdded = function(additions) {}; + SharedStylesHost.prototype.getAllStyles = function() { + return this._styles; }; - Object.defineProperty(Key, "numberOfKeys", { - get: function() { - return _globalKeyRegistry.numberOfKeys; - }, - enumerable: true, - configurable: true - }); - return Key; + SharedStylesHost = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], SharedStylesHost); + return SharedStylesHost; })(); - exports.Key = Key; - var KeyRegistry = (function() { - function KeyRegistry() { - this._allKeys = new Map(); + 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); } - 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); + 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)); } - 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(); + 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/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) { +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 math_1 = require("angular2/src/facade/math"); - var util_1 = require("angular2/src/platform/dom/util"); + var exceptions_1 = require("angular2/src/facade/exceptions"); 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(); - }); + 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; } - 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); + WrappedValue.wrap = function(value) { + var w = _wrappedValues[_wrappedIndex++ % 5]; + w.wrapped = value; + return w; }; - 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'}); + 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; }; - 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(); + return SimpleChange; + })(); + exports.SimpleChange = SimpleChange; + function _simpleChange(previousValue, currentValue) { + return new SimpleChange(previousValue, currentValue); + } + var ChangeDetectionUtil = (function() { + function ChangeDetectionUtil() {} + ChangeDetectionUtil.arrayFn0 = function() { + return []; }; - 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.arrayFn1 = function(a1) { + return [a1]; }; ChangeDetectionUtil.arrayFn2 = function(a1, a2) { return [a1, a2]; @@ -8719,6 +8198,15 @@ System.register("angular2/src/core/change_detection/change_detection_util", ["an ChangeDetectionUtil.looseNotIdentical = function(a, b) { return !lang_1.looseIdentical(a, b); }; + ChangeDetectionUtil.devModeEqual = function(a, b) { + if (collection_1.isListLikeIterable(a) && collection_1.isListLikeIterable(b)) { + return collection_1.areIterablesEqual(a, b, ChangeDetectionUtil.devModeEqual); + } else if (!collection_1.isListLikeIterable(a) && !lang_1.isPrimitive(a) && !collection_1.isListLikeIterable(b) && !lang_1.isPrimitive(b)) { + return true; + } else { + return lang_1.looseIdentical(a, b); + } + }; ChangeDetectionUtil.uninitialized = lang_1.CONST_EXPR(new Object()); return ChangeDetectionUtil; })(); @@ -8727,288 +8215,44 @@ System.register("angular2/src/core/change_detection/change_detection_util", ["an 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) { +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 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; + 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/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) { +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/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) { + function CodegenLogicUtil(_names, _utilName, _changeDetectorStateName) { this._names = _names; this._utilName = _utilName; this._changeDetectorStateName = _changeDetectorStateName; - this._changeDetection = _changeDetection; } CodegenLogicUtil.prototype.genPropertyBindingEvalValue = function(protoRec) { var _this = this; @@ -9036,24 +8280,24 @@ System.register("angular2/src/core/change_detection/codegen_logic_util", ["angul rhs = codegen_facade_1.codify(protoRec.funcOrValue); break; case proto_record_1.RecordType.PropertyRead: - rhs = this._observe(context + "." + protoRec.name, protoRec); + rhs = context + "." + protoRec.name; 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); + var read = context + "." + protoRec.name; + rhs = this._utilName + ".isValueBlank(" + context + ") ? null : " + read; 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); + rhs = localsAccessor + ".get(" + codegen_facade_1.rawString(protoRec.name) + ")"; break; case proto_record_1.RecordType.InvokeMethod: - rhs = this._observe(context + "." + protoRec.name + "(" + argString + ")", protoRec); + rhs = context + "." + protoRec.name + "(" + argString + ")"; break; case proto_record_1.RecordType.SafeMethodInvoke: var invoke = context + "." + protoRec.name + "(" + argString + ")"; - rhs = this._utilName + ".isValueBlank(" + context + ") ? null : " + this._observe(invoke, protoRec); + rhs = this._utilName + ".isValueBlank(" + context + ") ? null : " + invoke; break; case proto_record_1.RecordType.InvokeClosure: rhs = context + "(" + argString + ")"; @@ -9068,26 +8312,19 @@ System.register("angular2/src/core/change_detection/codegen_logic_util", ["angul rhs = this._genInterpolation(protoRec); break; case proto_record_1.RecordType.KeyedRead: - rhs = this._observe(context + "[" + getLocalName(protoRec.args[0]) + "]", protoRec); + rhs = context + "[" + getLocalName(protoRec.args[0]) + "]"; 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'; + rhs = "" + getLocalName(protoRec.args[protoRec.args.length - 1]); 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) { @@ -9115,20 +8352,56 @@ System.register("angular2/src/core/change_detection/codegen_logic_util", ["angul return codegen_facade_1.combineGeneratedStrings(iVals); }; CodegenLogicUtil.prototype.genHydrateDirectives = function(directiveRecords) { + var _this = this; var res = []; + var outputCount = 0; for (var i = 0; i < directiveRecords.length; ++i) { var r = directiveRecords[i]; - res.push(this._names.getDirectiveName(r.directiveIndex) + " = " + this._genReadDirective(i) + ";"); + var dirVarName = this._names.getDirectiveName(r.directiveIndex); + res.push(dirVarName + " = " + this._genReadDirective(i) + ";"); + if (lang_1.isPresent(r.outputs)) { + r.outputs.forEach(function(output) { + var eventHandlerExpr = _this._genEventHandler(r.directiveIndex.elementIndex, output[1]); + var statementStart = "this.outputSubscriptions[" + outputCount++ + "] = " + dirVarName + "." + output[0]; + if (lang_1.IS_DART) { + res.push(statementStart + ".listen(" + eventHandlerExpr + ");"); + } else { + res.push(statementStart + ".subscribe({next: " + eventHandlerExpr + "});"); + } + }); + } + } + if (outputCount > 0) { + var statementStart = 'this.outputSubscriptions'; + if (lang_1.IS_DART) { + res.unshift(statementStart + " = new List(" + outputCount + ");"); + } else { + res.unshift(statementStart + " = new Array(" + outputCount + ");"); + } } return res.join("\n"); }; - CodegenLogicUtil.prototype._genReadDirective = function(index) { - if (this._changeDetection === constants_1.ChangeDetectionStrategy.OnPushObserve) { - return "this.observeDirective(this.getDirectiveFor(directives, " + index + "), " + index + ")"; + CodegenLogicUtil.prototype.genDirectivesOnDestroy = function(directiveRecords) { + var res = []; + for (var i = 0; i < directiveRecords.length; ++i) { + var r = directiveRecords[i]; + if (r.callOnDestroy) { + var dirVarName = this._names.getDirectiveName(r.directiveIndex); + res.push(dirVarName + ".ngOnDestroy();"); + } + } + return res.join("\n"); + }; + CodegenLogicUtil.prototype._genEventHandler = function(boundElementIndex, eventName) { + if (lang_1.IS_DART) { + return "(event) => this.handleEvent('" + eventName + "', " + boundElementIndex + ", event)"; } else { - return "this.getDirectiveFor(directives, " + index + ")"; + return "(function(event) { return this.handleEvent('" + eventName + "', " + boundElementIndex + ", event); }).bind(this)"; } }; + CodegenLogicUtil.prototype._genReadDirective = function(index) { + return "this.getDirectiveFor(directives, " + index + ")"; + }; CodegenLogicUtil.prototype.genHydrateDetectors = function(directiveRecords) { var res = []; for (var i = 0; i < directiveRecords.length; ++i) { @@ -9174,1232 +8447,1004 @@ System.register("angular2/src/core/change_detection/codegen_logic_util", ["angul 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) { +System.register("angular2/src/core/linker/element", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/core/di", "angular2/src/core/di/provider", "angular2/src/core/di/injector", "angular2/src/core/di/provider", "angular2/src/core/metadata/di", "angular2/src/core/linker/view_type", "angular2/src/core/linker/element_ref", "angular2/src/core/linker/view_container_ref", "angular2/src/core/linker/element_ref", "angular2/src/core/render/api", "angular2/src/core/linker/template_ref", "angular2/src/core/metadata/directives", "angular2/src/core/change_detection/change_detection", "angular2/src/core/linker/query_list", "angular2/src/core/reflection/reflection", "angular2/src/core/pipes/pipe_provider", "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 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 di_1 = require("angular2/src/core/di"); + var provider_1 = require("angular2/src/core/di/provider"); + var injector_1 = require("angular2/src/core/di/injector"); + var provider_2 = require("angular2/src/core/di/provider"); + var di_2 = require("angular2/src/core/metadata/di"); + var view_type_1 = require("angular2/src/core/linker/view_type"); + var element_ref_1 = require("angular2/src/core/linker/element_ref"); + var view_container_ref_1 = require("angular2/src/core/linker/view_container_ref"); + var element_ref_2 = require("angular2/src/core/linker/element_ref"); + var api_1 = require("angular2/src/core/render/api"); + var template_ref_1 = require("angular2/src/core/linker/template_ref"); + var directives_1 = require("angular2/src/core/metadata/directives"); 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 = []; + var query_list_1 = require("angular2/src/core/linker/query_list"); + var reflection_1 = require("angular2/src/core/reflection/reflection"); + var pipe_provider_1 = require("angular2/src/core/pipes/pipe_provider"); + var view_container_ref_2 = require("angular2/src/core/linker/view_container_ref"); + var _staticKeys; + var StaticKeys = (function() { + function StaticKeys() { + 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_2.ElementRef).id; + this.rendererId = di_1.Key.get(api_1.Renderer).id; } - return AppViewContainer; + StaticKeys.instance = function() { + if (lang_1.isBlank(_staticKeys)) + _staticKeys = new StaticKeys(); + return _staticKeys; + }; + return StaticKeys; })(); - 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)); + exports.StaticKeys = StaticKeys; + 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(); } - 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; + 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.'); }; - AppView.prototype.invokeElementMethod = function(elementIndex, methodName, args) { - this.renderer.invokeElementMethod(this.elementRefs[elementIndex], methodName, args); + 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)); }; - 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); + DirectiveDependency._attributeName = function(properties) { + var p = properties.find(function(p) { + return p instanceof di_2.AttributeMetadata; + }); + return lang_1.isPresent(p) ? p.attributeName : null; }; - 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); - } + DirectiveDependency._query = function(properties) { + return properties.find(function(p) { + return p instanceof di_2.QueryMetadata; + }); }; - Object.defineProperty(AppView.prototype, "ownBindersCount", { + return DirectiveDependency; + })(di_1.Dependency); + exports.DirectiveDependency = DirectiveDependency; + var DirectiveProvider = (function(_super) { + __extends(DirectiveProvider, _super); + function DirectiveProvider(key, factory, deps, isComponent, providers, viewProviders, queries) { + _super.call(this, key, [new provider_2.ResolvedFactory(factory, deps)], false); + this.isComponent = isComponent; + this.providers = providers; + this.viewProviders = viewProviders; + this.queries = queries; + } + Object.defineProperty(DirectiveProvider.prototype, "displayName", { get: function() { - return this.proto.elementBinders.length; + return this.key.displayName; }, enumerable: true, configurable: true }); - return AppView; + DirectiveProvider.createFromType = function(type, meta) { + var provider = new di_1.Provider(type, {useClass: type}); + if (lang_1.isBlank(meta)) { + meta = new directives_1.DirectiveMetadata(); + } + var rb = provider_2.resolveProvider(provider); + var rf = rb.resolvedFactories[0]; + var deps = rf.dependencies.map(DirectiveDependency.createFrom); + var isComponent = meta instanceof directives_1.ComponentMetadata; + var resolvedProviders = lang_1.isPresent(meta.providers) ? di_1.Injector.resolve(meta.providers) : null; + var resolvedViewProviders = meta instanceof directives_1.ComponentMetadata && lang_1.isPresent(meta.viewProviders) ? di_1.Injector.resolve(meta.viewProviders) : null; + var queries = []; + if (lang_1.isPresent(meta.queries)) { + collection_1.StringMapWrapper.forEach(meta.queries, function(meta, fieldName) { + var setter = reflection_1.reflector.setter(fieldName); + queries.push(new QueryMetadataWithSetter(setter, meta)); + }); + } + deps.forEach(function(d) { + if (lang_1.isPresent(d.queryDecorator)) { + queries.push(new QueryMetadataWithSetter(null, d.queryDecorator)); + } + }); + return new DirectiveProvider(rb.key, rf.factory, deps, isComponent, resolvedProviders, resolvedViewProviders, queries); + }; + return DirectiveProvider; + })(provider_2.ResolvedProvider_); + exports.DirectiveProvider = DirectiveProvider; + var QueryMetadataWithSetter = (function() { + function QueryMetadataWithSetter(setter, metadata) { + this.setter = setter; + this.metadata = metadata; + } + return QueryMetadataWithSetter; })(); - 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; + exports.QueryMetadataWithSetter = QueryMetadataWithSetter; + function setProvidersVisibility(providers, visibility, result) { + for (var i = 0; i < providers.length; i++) { + result.set(providers[i].key.id, visibility); } - return res; } + var AppProtoElement = (function() { + function AppProtoElement(firstProviderIsComponent, index, attributes, pwvs, protoQueryRefs, directiveVariableBindings) { + this.firstProviderIsComponent = firstProviderIsComponent; + this.index = index; + this.attributes = attributes; + this.protoQueryRefs = protoQueryRefs; + this.directiveVariableBindings = directiveVariableBindings; + var length = pwvs.length; + if (length > 0) { + this.protoInjector = new injector_1.ProtoInjector(pwvs); + } else { + this.protoInjector = null; + this.protoQueryRefs = []; + } + } + AppProtoElement.create = function(metadataCache, index, attributes, directiveTypes, directiveVariableBindings) { + var componentDirProvider = null; + var mergedProvidersMap = new Map(); + var providerVisibilityMap = new Map(); + var providers = collection_1.ListWrapper.createGrowableSize(directiveTypes.length); + var protoQueryRefs = []; + for (var i = 0; i < directiveTypes.length; i++) { + var dirProvider = metadataCache.getResolvedDirectiveMetadata(directiveTypes[i]); + providers[i] = new injector_1.ProviderWithVisibility(dirProvider, dirProvider.isComponent ? injector_1.Visibility.PublicAndPrivate : injector_1.Visibility.Public); + if (dirProvider.isComponent) { + componentDirProvider = dirProvider; + } else { + if (lang_1.isPresent(dirProvider.providers)) { + provider_1.mergeResolvedProviders(dirProvider.providers, mergedProvidersMap); + setProvidersVisibility(dirProvider.providers, injector_1.Visibility.Public, providerVisibilityMap); + } + } + if (lang_1.isPresent(dirProvider.viewProviders)) { + provider_1.mergeResolvedProviders(dirProvider.viewProviders, mergedProvidersMap); + setProvidersVisibility(dirProvider.viewProviders, injector_1.Visibility.Private, providerVisibilityMap); + } + for (var queryIdx = 0; queryIdx < dirProvider.queries.length; queryIdx++) { + var q = dirProvider.queries[queryIdx]; + protoQueryRefs.push(new ProtoQueryRef(i, q.setter, q.metadata)); + } + } + if (lang_1.isPresent(componentDirProvider) && lang_1.isPresent(componentDirProvider.providers)) { + provider_1.mergeResolvedProviders(componentDirProvider.providers, mergedProvidersMap); + setProvidersVisibility(componentDirProvider.providers, injector_1.Visibility.Public, providerVisibilityMap); + } + mergedProvidersMap.forEach(function(provider, _) { + providers.push(new injector_1.ProviderWithVisibility(provider, providerVisibilityMap.get(provider.key.id))); + }); + return new AppProtoElement(lang_1.isPresent(componentDirProvider), index, attributes, providers, protoQueryRefs, directiveVariableBindings); + }; + AppProtoElement.prototype.getProviderAtIndex = function(index) { + return this.protoInjector.getProviderAtIndex(index); + }; + return AppProtoElement; + })(); + exports.AppProtoElement = AppProtoElement; var _Context = (function() { - function _Context(element, componentElement, context, locals, injector) { + function _Context(element, componentElement, 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; + var InjectorWithHostBoundary = (function() { + function InjectorWithHostBoundary(injector, hostInjectorBoundary) { + this.injector = injector; + this.hostInjectorBoundary = hostInjectorBoundary; } - return AppProtoViewMergeInfo; + return InjectorWithHostBoundary; })(); - 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) { + exports.InjectorWithHostBoundary = InjectorWithHostBoundary; + var AppElement = (function() { + function AppElement(proto, parentView, parent, nativeElement, embeddedViewFactory) { 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); + this.proto = proto; + this.parentView = parentView; + this.parent = parent; + this.nativeElement = nativeElement; + this.embeddedViewFactory = embeddedViewFactory; + this.nestedViews = null; + this.componentView = null; + this.ref = new element_ref_1.ElementRef_(this); + var parentInjector = lang_1.isPresent(parent) ? parent._injector : parentView.parentInjector; + if (lang_1.isPresent(this.proto.protoInjector)) { + var isBoundary; + if (lang_1.isPresent(parent) && lang_1.isPresent(parent.proto.protoInjector)) { + isBoundary = false; + } else { + isBoundary = parentView.hostInjectorBoundary; + } + this._queryStrategy = this._buildQueryStrategy(); + this._injector = new di_1.Injector(this.proto.protoInjector, parentInjector, isBoundary, this, function() { + return _this._debugContext(); }); + var injectorStrategy = this._injector.internalStrategy; + this._strategy = injectorStrategy instanceof injector_1.InjectorInlineStrategy ? new ElementDirectiveInlineStrategy(injectorStrategy, this) : new ElementDirectiveDynamicStrategy(injectorStrategy, this); + this._strategy.init(); + } else { + this._queryStrategy = null; + this._injector = parentInjector; + this._strategy = null; + } + } + AppElement.getViewParentInjector = function(parentViewType, containerAppElement, imperativelyCreatedProviders, rootInjector) { + var parentInjector; + var hostInjectorBoundary; + switch (parentViewType) { + case view_type_1.ViewType.COMPONENT: + parentInjector = containerAppElement._injector; + hostInjectorBoundary = true; + break; + case view_type_1.ViewType.EMBEDDED: + parentInjector = lang_1.isPresent(containerAppElement.proto.protoInjector) ? containerAppElement._injector.parent : containerAppElement._injector; + hostInjectorBoundary = containerAppElement._injector.hostBoundary; + break; + case view_type_1.ViewType.HOST: + if (lang_1.isPresent(containerAppElement)) { + parentInjector = lang_1.isPresent(containerAppElement.proto.protoInjector) ? containerAppElement._injector.parent : containerAppElement._injector; + if (lang_1.isPresent(imperativelyCreatedProviders)) { + var imperativeProvidersWithVisibility = imperativelyCreatedProviders.map(function(p) { + return new injector_1.ProviderWithVisibility(p, injector_1.Visibility.Public); + }); + parentInjector = new di_1.Injector(new injector_1.ProtoInjector(imperativeProvidersWithVisibility), parentInjector, true, null, null); + hostInjectorBoundary = false; + } else { + hostInjectorBoundary = containerAppElement._injector.hostBoundary; + } + } else { + parentInjector = rootInjector; + hostInjectorBoundary = true; + } + break; } + return new InjectorWithHostBoundary(parentInjector, hostInjectorBoundary); }; - AppProtoView.prototype.isInitialized = function() { - return lang_1.isPresent(this.elementBinders); + AppElement.prototype.attachComponentView = function(componentView) { + this.componentView = componentView; }; - 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]; + AppElement.prototype._debugContext = function() { + var c = this.parentView.getDebugContext(this, null, null); + return lang_1.isPresent(c) ? new _Context(c.element, c.componentElement, c.injector) : null; }; - AppViewManagerUtils.prototype.hydrateRootHostView = function(hostView, injector) { - this._hydrateView(hostView, injector, null, new Object(), null); + AppElement.prototype.hasVariableBinding = function(name) { + var vb = this.proto.directiveVariableBindings; + return lang_1.isPresent(vb) && collection_1.StringMapWrapper.contains(vb, name); }; - 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); - } + AppElement.prototype.getVariableBinding = function(name) { + var index = this.proto.directiveVariableBindings[name]; + return lang_1.isPresent(index) ? this.getDirectiveAtIndex(index) : this.getElementRef(); + }; + AppElement.prototype.get = function(token) { + return this._injector.get(token); + }; + AppElement.prototype.hasDirective = function(type) { + return lang_1.isPresent(this._injector.getOptional(type)); + }; + AppElement.prototype.getComponent = function() { + return lang_1.isPresent(this._strategy) ? this._strategy.getComponent() : null; + }; + AppElement.prototype.getInjector = function() { + return this._injector; + }; + AppElement.prototype.getElementRef = function() { + return this.ref; + }; + AppElement.prototype.getViewContainerRef = function() { + return new view_container_ref_2.ViewContainerRef_(this); + }; + AppElement.prototype.getTemplateRef = function() { + if (lang_1.isPresent(this.embeddedViewFactory)) { + return new template_ref_1.TemplateRef_(this.ref); } - elementInjector.traverseAndSetQueriesAsDirty(); + return null; }; - 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(); + AppElement.prototype.getDependency = function(injector, provider, dep) { + if (provider instanceof DirectiveProvider) { + var dirDep = dep; + 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 (this.proto.firstProviderIsComponent) { + return new _ComponentViewChangeDetectorRef(this); + } else { + return this.parentView.changeDetector.ref; } - 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); - } + } + 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) { + var tr = this.getTemplateRef(); + if (lang_1.isBlank(tr) && !dirDep.optional) { + throw new di_1.NoProviderError(null, dirDep.key); } - 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++; + return tr; } - } - }; - 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); + if (dirDep.key.id === StaticKeys.instance().rendererId) { + return this.parentView.renderer; + } + } else if (provider instanceof pipe_provider_1.PipeProvider) { + if (dep.key.id === StaticKeys.instance().changeDetectorRefId) { + if (this.proto.firstProviderIsComponent) { + return new _ComponentViewChangeDetectorRef(this); } else { - view.locals.set(name, elementInjector.getDirectiveAtIndex(directiveIndex)); + return this.parentView.changeDetector; } - }); - } - }; - 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); } } + return injector_1.UNDEFINED; }; - 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(); - } - } - } + AppElement.prototype._buildAttribute = function(dep) { + var attributes = this.proto.attributes; + if (lang_1.isPresent(attributes) && collection_1.StringMapWrapper.contains(attributes, dep.attributeName)) { + return attributes[dep.attributeName]; + } else { + return null; } }; - 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; + AppElement.prototype.addDirectivesMatchingQuery = function(query, list) { + var templateRef = this.getTemplateRef(); + if (query.selector === template_ref_1.TemplateRef && lang_1.isPresent(templateRef)) { + list.push(templateRef); + } + if (this._strategy != null) { + this._strategy.addDirectivesMatchingQuery(query, list); + } }; - 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)); + AppElement.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 { - var handler = createEventHandler(boundElementIndex, eventName, this._eventDispatcher); - this.factory.on(this.boundElements[boundElementIndex], eventName, handler); + return new DynamicQueryStrategy(this); } }; - 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); + AppElement.prototype.getDirectiveAtIndex = function(index) { + return this._injector.getAt(index); }; - } - 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); - } + AppElement.prototype.ngAfterViewChecked = function() { + if (lang_1.isPresent(this._queryStrategy)) + this._queryStrategy.updateViewQueries(); }; - 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; + AppElement.prototype.ngAfterContentChecked = function() { + if (lang_1.isPresent(this._queryStrategy)) + this._queryStrategy.updateContentQueries(); }; - 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); + AppElement.prototype.traverseAndSetQueriesAsDirty = function() { + var inj = this; + while (lang_1.isPresent(inj)) { + inj._setQueriesAsDirty(); + if (lang_1.isBlank(inj.parent) && inj.parentView.proto.type === view_type_1.ViewType.EMBEDDED) { + inj = inj.parentView.containerAppElement; } 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); - } + inj = inj.parent; } } - return null; }; - RenderViewBuilder.prototype.visitBeginElement = function(cmd, context) { - this.parentStack.push(this._beginElement(cmd, context, null)); - return null; + AppElement.prototype._setQueriesAsDirty = function() { + if (lang_1.isPresent(this._queryStrategy)) { + this._queryStrategy.setContentQueriesAsDirty(); + } + if (this.parentView.proto.type === view_type_1.ViewType.COMPONENT) { + this.parentView.containerAppElement._queryStrategy.setViewQueriesAsDirty(); + } }; - RenderViewBuilder.prototype.visitEndElement = function(context) { - this._endElement(); - return null; + return AppElement; + })(); + exports.AppElement = AppElement; + var _EmptyQueryStrategy = (function() { + function _EmptyQueryStrategy() {} + _EmptyQueryStrategy.prototype.setContentQueriesAsDirty = function() {}; + _EmptyQueryStrategy.prototype.setViewQueriesAsDirty = 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 + "."); }; - 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; + 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; }; - RenderViewBuilder.prototype.visitEndComponent = function(context) { - this._endElement(); - return null; + 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; }; - 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); + InlineQueryStrategy.prototype.updateContentQueries = function() { + if (lang_1.isPresent(this.query0) && !this.query0.isViewQuery) { + this.query0.update(); } - 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 (lang_1.isPresent(this.query1) && !this.query1.isViewQuery) { + this.query1.update(); } - 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); - } + if (lang_1.isPresent(this.query2) && !this.query2.isViewQuery) { + this.query2.update(); } - 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); + InlineQueryStrategy.prototype.updateViewQueries = function() { + if (lang_1.isPresent(this.query0) && this.query0.isViewQuery) { + this.query0.update(); } - }; - 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); + if (lang_1.isPresent(this.query1) && this.query1.isViewQuery) { + this.query1.update(); + } + if (lang_1.isPresent(this.query2) && this.query2.isViewQuery) { + this.query2.update(); } }; - Component.prototype.project = function(ngContentIndex) { - return ngContentIndex < this.contentNodesByNgContentIndex.length ? this.contentNodesByNgContentIndex[ngContentIndex] : []; + 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 + "."); }; - return Component; + InlineQueryStrategy.NUMBER_OF_SUPPORTED_QUERIES = 3; + return InlineQueryStrategy; })(); - 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; + var DynamicQueryStrategy = (function() { + function DynamicQueryStrategy(ei) { + this.queries = ei.proto.protoQueryRefs.map(function(p) { + return new QueryRef(p, ei); + }); } - 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; + 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.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 ElementDirectiveInlineStrategy = (function() { + function ElementDirectiveInlineStrategy(injectorStrategy, _ei) { + this.injectorStrategy = injectorStrategy; + this._ei = _ei; } - Dependency.fromKey = function(key) { - return new Dependency(key, false, null, null, []); + ElementDirectiveInlineStrategy.prototype.init = 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); }; - return Dependency; + ElementDirectiveInlineStrategy.prototype.getComponent = function() { + return this.injectorStrategy.obj0; + }; + ElementDirectiveInlineStrategy.prototype.isComponentKey = function(key) { + return this._ei.proto.firstProviderIsComponent && lang_1.isPresent(key) && key.id === this.injectorStrategy.protoStrategy.keyId0; + }; + ElementDirectiveInlineStrategy.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 ElementDirectiveInlineStrategy; })(); - 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; + var ElementDirectiveDynamicStrategy = (function() { + function ElementDirectiveDynamicStrategy(injectorStrategy, _ei) { + this.injectorStrategy = injectorStrategy; + this._ei = _ei; } - Object.defineProperty(Provider.prototype, "multi", { + ElementDirectiveDynamicStrategy.prototype.init = 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]); + } + } + }; + ElementDirectiveDynamicStrategy.prototype.getComponent = function() { + return this.injectorStrategy.objs[0]; + }; + ElementDirectiveDynamicStrategy.prototype.isComponentKey = function(key) { + var p = this.injectorStrategy.protoStrategy; + return this._ei.proto.firstProviderIsComponent && lang_1.isPresent(key) && key.id === p.keyIds[0]; + }; + ElementDirectiveDynamicStrategy.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 ElementDirectiveDynamicStrategy; + })(); + 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.normalizeBool(this._multi); + return lang_1.isPresent(this.setter); }, enumerable: true, configurable: true }); - Provider = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object, Object])], Provider); - return Provider; + return ProtoQueryRef; })(); - 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; + exports.ProtoQueryRef = ProtoQueryRef; + var QueryRef = (function() { + function QueryRef(protoQueryRef, originator) { + this.protoQueryRef = protoQueryRef; + this.originator = originator; + this.list = new query_list_1.QueryList(); + this.dirty = true; } - Object.defineProperty(ResolvedProvider_.prototype, "resolvedFactory", { + Object.defineProperty(QueryRef.prototype, "isViewQuery", { get: function() { - return this.resolvedFactories[0]; + return this.protoQueryRef.query.isViewQuery; }, 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!"); + 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); + } } - return new Provider(this.token, {useClass: type}); - }; - ProviderBuilder.prototype.toValue = function(value) { - return new Provider(this.token, {useValue: value}); + this.list.notifyOnChanges(); }; - 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!"); + QueryRef.prototype._update = function() { + var aggregator = []; + if (this.protoQueryRef.query.isViewQuery) { + var nestedView = this.originator.componentView; + if (lang_1.isPresent(nestedView)) + this._visitView(nestedView, aggregator); + } else { + this._visit(this.originator, aggregator); } - return new Provider(this.token, {useExisting: aliasToken}); + this.list.reset(aggregator); }; - 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!"); + ; + QueryRef.prototype._visit = function(inj, aggregator) { + var view = inj.parentView; + var startIdx = inj.proto.index; + for (var i = startIdx; i < view.appElements.length; i++) { + var curInj = view.appElements[i]; + if (i > startIdx && (lang_1.isBlank(curInj.parent) || curInj.parent.proto.index < startIdx)) { + break; + } + if (!this.protoQueryRef.query.descendants && !(curInj.parent == this.originator || curInj == this.originator)) + continue; + this._visitInjector(curInj, aggregator); + this._visitViewContainerViews(curInj.nestedViews, aggregator); } - 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); + QueryRef.prototype._visitInjector = function(inj, aggregator) { + if (this.protoQueryRef.query.isVarBindingQuery) { + this._aggregateVariableBinding(inj, aggregator); } else { - var arr = b; - return new ResolvedProvider_(arr[0].key, arr.map(function(_) { - return _.resolvedFactory; - }), true); + this._aggregateDirective(inj, aggregator); } - }); - } - 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); + }; + QueryRef.prototype._visitViewContainerViews = function(views, aggregator) { + if (lang_1.isPresent(views)) { + for (var j = 0; j < views.length; j++) { + this._visitView(views[j], aggregator); + } } - }); - 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); + }; + QueryRef.prototype._visitView = function(view, aggregator) { + for (var i = 0; i < view.appElements.length; i++) { + var inj = view.appElements[i]; + this._visitInjector(inj, aggregator); + this._visitViewContainerViews(inj.nestedViews, aggregator); } - } else { - var existingProvider = res.get(key.id); - if (existingProvider instanceof Array) { - throw new exceptions_2.MixingMultiProvidersWithRegularProvidersError(existingProvider, b); + }; + 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])); + } } - 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); - }); + }; + QueryRef.prototype._aggregateDirective = function(inj, aggregator) { + inj.addDirectivesMatchingQuery(this.protoQueryRef.query, aggregator); + }; + return QueryRef; + })(); + exports.QueryRef = QueryRef; + var _ComponentViewChangeDetectorRef = (function(_super) { + __extends(_ComponentViewChangeDetectorRef, _super); + function _ComponentViewChangeDetectorRef(_appElement) { + _super.call(this); + this._appElement = _appElement; } - } - 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); + _ComponentViewChangeDetectorRef.prototype.markForCheck = function() { + this._appElement.componentView.changeDetector.ref.markForCheck(); + }; + _ComponentViewChangeDetectorRef.prototype.detach = function() { + this._appElement.componentView.changeDetector.ref.detach(); + }; + _ComponentViewChangeDetectorRef.prototype.detectChanges = function() { + this._appElement.componentView.changeDetector.ref.detectChanges(); + }; + _ComponentViewChangeDetectorRef.prototype.checkNoChanges = function() { + this._appElement.componentView.changeDetector.ref.checkNoChanges(); + }; + _ComponentViewChangeDetectorRef.prototype.reattach = function() { + this._appElement.componentView.changeDetector.ref.reattach(); + }; + return _ComponentViewChangeDetectorRef; + })(change_detection_1.ChangeDetectorRef); + 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; } - 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); - } + 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 = {}; } - 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); + 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", ["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.EmbeddedViewRef = view_ref_1.EmbeddedViewRef; + exports.HostViewRef = view_ref_1.HostViewRef; + exports.ViewRef = view_ref_1.ViewRef; + exports.HostViewFactoryRef = view_ref_1.HostViewFactoryRef; + 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/linker/resolved_metadata_cache", ["angular2/src/core/di", "angular2/src/facade/lang", "angular2/src/core/linker/element", "angular2/src/core/linker/directive_resolver", "angular2/src/core/pipes/pipe_provider", "angular2/src/core/linker/pipe_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 di_1 = require("angular2/src/core/di"); + var lang_1 = require("angular2/src/facade/lang"); + var element_1 = require("angular2/src/core/linker/element"); + var directive_resolver_1 = require("angular2/src/core/linker/directive_resolver"); + var pipe_provider_1 = require("angular2/src/core/pipes/pipe_provider"); + var pipe_resolver_1 = require("angular2/src/core/linker/pipe_resolver"); + var ResolvedMetadataCache = (function() { + function ResolvedMetadataCache(_directiveResolver, _pipeResolver) { + this._directiveResolver = _directiveResolver; + this._pipeResolver = _pipeResolver; + this._directiveCache = new Map(); + this._pipeCache = new Map(); } - 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); + ResolvedMetadataCache.prototype.getResolvedDirectiveMetadata = function(type) { + var result = this._directiveCache.get(type); + if (lang_1.isBlank(result)) { + result = element_1.DirectiveProvider.createFromType(type, this._directiveResolver.resolve(type)); + this._directiveCache.set(type, result); + } + return result; + }; + ResolvedMetadataCache.prototype.getResolvedPipeMetadata = function(type) { + var result = this._pipeCache.get(type); + if (lang_1.isBlank(result)) { + result = pipe_provider_1.PipeProvider.createFromType(type, this._pipeResolver.resolve(type)); + this._pipeCache.set(type, result); + } + return result; + }; + ResolvedMetadataCache = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [directive_resolver_1.DirectiveResolver, pipe_resolver_1.PipeResolver])], ResolvedMetadataCache); + return ResolvedMetadataCache; + })(); + exports.ResolvedMetadataCache = ResolvedMetadataCache; + exports.CODEGEN_RESOLVED_METADATA_CACHE = new ResolvedMetadataCache(directive_resolver_1.CODEGEN_DIRECTIVE_RESOLVER, pipe_resolver_1.CODEGEN_PIPE_RESOLVER); + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/platform/dom/debug/ng_probe", ["angular2/src/facade/lang", "angular2/src/core/di", "angular2/src/platform/dom/dom_adapter", "angular2/src/core/debug/debug_node", "angular2/src/platform/dom/dom_renderer", "angular2/core", "angular2/src/core/debug/debug_renderer"], 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 dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); + var debug_node_1 = require("angular2/src/core/debug/debug_node"); + var dom_renderer_1 = require("angular2/src/platform/dom/dom_renderer"); + var core_1 = require("angular2/core"); + var debug_renderer_1 = require("angular2/src/core/debug/debug_renderer"); + var CORE_TOKENS = lang_1.CONST_EXPR({ + 'ApplicationRef': core_1.ApplicationRef, + 'NgZone': core_1.NgZone + }); + var INSPECT_GLOBAL_NAME = 'ng.probe'; + var CORE_TOKENS_GLOBAL_NAME = 'ng.coreTokens'; + function inspectNativeElement(element) { + return debug_node_1.getDebugNode(element); + } + exports.inspectNativeElement = inspectNativeElement; + function _createConditionalRootRenderer(rootRenderer) { + if (lang_1.assertionsEnabled()) { + return _createRootRenderer(rootRenderer); } + return rootRenderer; } - function _createDependency(token, optional, lowerBoundVisibility, upperBoundVisibility, depProps) { - return new Dependency(key_1.Key.get(token), optional, lowerBoundVisibility, upperBoundVisibility, depProps); + function _createRootRenderer(rootRenderer) { + dom_adapter_1.DOM.setGlobalVar(INSPECT_GLOBAL_NAME, inspectNativeElement); + dom_adapter_1.DOM.setGlobalVar(CORE_TOKENS_GLOBAL_NAME, CORE_TOKENS); + return new debug_renderer_1.DebugDomRootRenderer(rootRenderer); } + exports.ELEMENT_PROBE_PROVIDERS = lang_1.CONST_EXPR([new di_1.Provider(core_1.RootRenderer, { + useFactory: _createConditionalRootRenderer, + deps: [dom_renderer_1.DomRootRenderer] + })]); + exports.ELEMENT_PROBE_PROVIDERS_PROD_MODE = lang_1.CONST_EXPR([new di_1.Provider(core_1.RootRenderer, { + useFactory: _createRootRenderer, + deps: [dom_renderer_1.DomRootRenderer] + })]); + 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; }); @@ -10456,400 +9501,237 @@ System.register("angular2/src/animate/css_animation_builder", ["angular2/src/ani 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) { +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/parser/locals", "angular2/src/core/change_detection/constants", "angular2/src/core/profile/profile", "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 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 change_detector_ref_1 = require("angular2/src/core/change_detection/change_detector_ref"); + var exceptions_1 = require("angular2/src/core/change_detection/exceptions"); + var locals_1 = require("angular2/src/core/change_detection/parser/locals"); 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); + var profile_1 = require("angular2/src/core/profile/profile"); + var async_1 = require("angular2/src/facade/async"); + 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; } - 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; + return _Context; + })(); + var AbstractChangeDetector = (function() { + function AbstractChangeDetector(id, numberOfPropertyProtoRecords, bindingTargets, directiveIndices, strategy) { + this.id = id; + 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; }; - 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"); + AbstractChangeDetector.prototype.removeContentChild = function(cd) { + collection_1.ListWrapper.remove(this.contentChildren, cd); }; - 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; + 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, event) { + if (!this.hydrated()) { + this.throwDehydratedError(this.id + " -> " + eventName); } - if (proto.mode === proto_record_1.RecordType.SkipRecordsIfNot) { - var condition = this._readContext(proto, values); - return condition ? 0 : proto.fixedArgs[0] - protoIndex - 1; + try { + var locals = new Map(); + locals.set('$event', event); + var res = !this.handleEventInternal(eventName, elIndex, new locals_1.Locals(this.locals, locals)); + this.markPathToRootAsCheckOnce(); + return res; + } catch (e) { + var c = this.dispatcher.getDebugContext(null, elIndex, null); + var context = lang_1.isPresent(c) ? new exceptions_1.EventEvaluationErrorContext(c.element, c.componentElement, c.context, c.locals, c.injector) : null; + throw new exceptions_1.EventEvaluationError(eventName, e, e.stack, context); } - 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(); - } + AbstractChangeDetector.prototype.handleEventInternal = function(eventName, elIndex, locals) { + return false; }; - DynamicChangeDetector.prototype._matchingEventBindings = function(eventName, elIndex) { - return this._eventBindings.filter(function(eb) { - return eb.eventName == eventName && eb.elIndex === elIndex; - }); + AbstractChangeDetector.prototype.detectChanges = function() { + this.runDetectChanges(false); }; - 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); - } + AbstractChangeDetector.prototype.checkNoChanges = function() { + if (lang_1.assertionsEnabled()) { + this.runDetectChanges(true); } }; - 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); + 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); }; - 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]); + AbstractChangeDetector.prototype.detectChangesInRecords = function(throwOnChange) { + if (!this.hydrated()) { + this.throwDehydratedError(this.id); + } + try { + this.detectChangesInRecordsInternal(throwOnChange); + } catch (e) { + if (!(e instanceof exceptions_1.ExpressionChangedAfterItHasBeenCheckedException)) { + this.state = constants_1.ChangeDetectorState.Errored; } + this._throwError(e, e.stack); } }; - DynamicChangeDetector.prototype.checkNoChanges = function() { - this.runDetectChanges(true); + AbstractChangeDetector.prototype.detectChangesInRecordsInternal = function(throwOnChange) {}; + AbstractChangeDetector.prototype.hydrate = function(context, locals, dispatcher, pipes) { + this.dispatcher = dispatcher; + this.mode = change_detection_util_1.ChangeDetectionUtil.changeDetectionMode(this.strategy); + this.context = context; + this.locals = locals; + this.pipes = pipes; + this.hydrateDirectives(dispatcher); + this.state = constants_1.ChangeDetectorState.NeverChecked; }; - 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; - } - } + AbstractChangeDetector.prototype.hydrateDirectives = function(dispatcher) {}; + AbstractChangeDetector.prototype.dehydrate = function() { + this.dehydrateDirectives(true); + this._unsubscribeFromOutputs(); + this.dispatcher = null; + this.context = null; + this.locals = null; + this.pipes = null; }; - 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; + AbstractChangeDetector.prototype.dehydrateDirectives = function(destroyPipes) {}; + AbstractChangeDetector.prototype.hydrated = function() { + return lang_1.isPresent(this.context); }; - 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(); - } + AbstractChangeDetector.prototype.destroyRecursive = function() { + this.dispatcher.notifyOnDestroy(); + this.dehydrate(); + var children = this.contentChildren; + for (var i = 0; i < children.length; i++) { + children[i].destroyRecursive(); + } + children = this.viewChildren; + for (var i = 0; i < children.length; i++) { + children[i].destroyRecursive(); } }; - 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(); - } + 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); } }; - 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); + AbstractChangeDetector.prototype._detectChangesInViewChildren = function(throwOnChange) { + var c = this.viewChildren; + for (var i = 0; i < c.length; ++i) { + c[i].runDetectChanges(throwOnChange); } - if (this._genConfig.logBindingUpdate) { - _super.prototype.logBindingUpdate.call(this, change.currentValue); + }; + 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; } }; - DynamicChangeDetector.prototype._addChange = function(bindingRecord, change, changes) { - if (bindingRecord.callOnChanges()) { - return _super.prototype.addChange.call(this, changes, change.previousValue, change.currentValue); - } else { - return changes; + AbstractChangeDetector.prototype._unsubscribeFromOutputs = function() { + if (lang_1.isPresent(this.outputSubscriptions)) { + for (var i = 0; i < this.outputSubscriptions.length; ++i) { + async_1.ObservableWrapper.dispose(this.outputSubscriptions[i]); + this.outputSubscriptions[i] = null; + } } }; - DynamicChangeDetector.prototype._getDirectiveFor = function(directiveIndex) { - return this.directives.getDirectiveFor(directiveIndex); + AbstractChangeDetector.prototype.getDirectiveFor = function(directives, index) { + return directives.getDirectiveFor(this.directiveIndices[index]); }; - DynamicChangeDetector.prototype._getDetectorFor = function(directiveIndex) { - return this.directives.getDetectorFor(directiveIndex); + AbstractChangeDetector.prototype.getDetectorFor = function(directives, index) { + return directives.getDetectorFor(this.directiveIndices[index]); }; - 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); - } + AbstractChangeDetector.prototype.notifyDispatcher = function(value) { + this.dispatcher.notifyOnBinding(this._currentBinding(), value); }; - DynamicChangeDetector.prototype._referenceCheck = function(proto, throwOnChange, values, locals) { - if (this._pureFuncAndArgsDidNotChange(proto)) { - this._setChanged(proto, false); - return null; + AbstractChangeDetector.prototype.logBindingUpdate = function(value) { + this.dispatcher.logBindingUpdate(this._currentBinding(), value); + }; + AbstractChangeDetector.prototype.addChange = function(changes, oldValue, newValue) { + if (lang_1.isBlank(changes)) { + changes = {}; } - var currValue = this._calculateCurrValue(proto, values, locals); - if (this.strategy === constants_1.ChangeDetectionStrategy.OnPushObserve) { - _super.prototype.observeValue.call(this, currValue, proto.selfIndex); + 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(null, 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); } - 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); + throw error; }; - 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; + AbstractChangeDetector.prototype.throwOnChangeError = function(oldValue, newValue) { + throw new exceptions_1.ExpressionChangedAfterItHasBeenCheckedException(this._currentBinding().debug, oldValue, newValue, null); }; - DynamicChangeDetector.prototype._argsOrContextChanged = function(proto) { - return this._argsChanged(proto) || this.changes[proto.contextIndex]; + AbstractChangeDetector.prototype.throwDehydratedError = function(detail) { + throw new exceptions_1.DehydratedException(detail); }; - 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; + AbstractChangeDetector.prototype._currentBinding = function() { + return this.bindingTargets[this.propertyBindingIndex]; }; - return DynamicChangeDetector; - })(abstract_change_detector_1.AbstractChangeDetector); - exports.DynamicChangeDetector = DynamicChangeDetector; + return AbstractChangeDetector; + })(); + exports.AbstractChangeDetector = AbstractChangeDetector; global.define = __define; return module.exports; }); @@ -10889,15 +9771,15 @@ System.register("angular2/src/core/change_detection/change_detection_jit_generat 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._logic = new codegen_logic_util_1.CodegenLogicUtil(this._names, this.changeDetectionUtilVarName, this.changeDetectorStateVarName); 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 "; + var factorySource = "\n " + this.generateSource() + "\n return function() {\n return new " + this.typeName + "();\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 "; + return "\n var " + this.typeName + " = function " + this.typeName + "() {\n " + this.abstractChangeDetectorVarName + ".call(\n this, " + JSON.stringify(this.id) + ", " + 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); @@ -10941,7 +9823,7 @@ System.register("angular2/src/core/change_detection/change_detection_jit_generat var evalRecord = this._logic.genEventBindingEvalValue(eb, r); var markPath = this._genMarkPathToRootAsCheckOnce(r); var prevDefault = this._genUpdatePreventDefault(eb, r); - return evalRecord + "\n" + markPath + "\n" + prevDefault; + return markPath + "\n" + evalRecord + "\n" + prevDefault; } else { return this._logic.genEventBindingEvalValue(eb, r); } @@ -10960,13 +9842,11 @@ System.register("angular2/src/core/change_detection/change_detection_jit_generat }; ChangeDetectorJITGenerator.prototype._maybeGenDehydrateDirectives = function() { var destroyPipesCode = this._names.genPipeOnDestroy(); - if (destroyPipesCode) { - destroyPipesCode = "if (destroyPipes) { " + destroyPipesCode + " }"; - } + var destroyDirectivesCode = this._logic.genDirectivesOnDestroy(this.directiveRecords); var dehydrateFieldsCode = this._names.genDehydrateFields(); - if (!destroyPipesCode && !dehydrateFieldsCode) + if (!destroyPipesCode && !destroyDirectivesCode && !dehydrateFieldsCode) return ''; - return this.typeName + ".prototype.dehydrateDirectives = function(destroyPipes) {\n " + destroyPipesCode + "\n " + dehydrateFieldsCode + "\n }"; + return this.typeName + ".prototype.dehydrateDirectives = function(destroyPipes) {\n if (destroyPipes) {\n " + destroyPipesCode + "\n " + destroyDirectivesCode + "\n }\n " + dehydrateFieldsCode + "\n }"; }; ChangeDetectorJITGenerator.prototype._maybeGenHydrateDirectives = function() { var hydrateDirectivesCode = this._logic.genHydrateDirectives(this.directiveRecords); @@ -11063,7 +9943,7 @@ System.register("angular2/src/core/change_detection/change_detection_jit_generat }); 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 check = "\n " + this._genThrowOnChangeCheck(oldValue, newValue) + "\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 + "; }"; @@ -11076,7 +9956,7 @@ System.register("angular2/src/core/change_detection/change_detection_jit_generat 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 check = "\n " + this._genThrowOnChangeCheck(oldValue, newValue) + "\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) { @@ -11098,19 +9978,18 @@ System.register("angular2/src/core/change_detection/change_detection_jit_generat 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 "; + return "\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 "; + return "\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 "; + return "\n if (throwOnChange && !" + this.changeDetectionUtilVarName + ".devModeEqual(" + oldValue + ", " + newValue + ")) {\n this.throwOnChangeError(" + oldValue + ", " + newValue + ");\n }\n "; } else { return ''; } @@ -11158,19 +10037,10 @@ System.register("angular2/src/core/change_detection/change_detection_jit_generat 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) { +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/core/linker/element", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/core/render/api", "angular2/src/core/linker/view_ref", "angular2/src/core/pipes/pipes", "angular2/src/core/render/util", "angular2/src/core/change_detection/interfaces", "angular2/src/core/pipes/pipes", "angular2/src/core/linker/view_type"], 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, @@ -11187,903 +10057,1161 @@ System.register("angular2/src/core/linker/view_manager", ["angular2/src/core/di" 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 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 element_1 = require("angular2/src/core/linker/element"); 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'); + var view_ref_1 = require("angular2/src/core/linker/view_ref"); + var pipes_1 = require("angular2/src/core/pipes/pipes"); + var util_1 = require("angular2/src/core/render/util"); + var interfaces_2 = require("angular2/src/core/change_detection/interfaces"); + exports.DebugContext = interfaces_2.DebugContext; + var pipes_2 = require("angular2/src/core/pipes/pipes"); + var view_type_1 = require("angular2/src/core/linker/view_type"); + var REFLECT_PREFIX = 'ng-reflect-'; + var EMPTY_CONTEXT = lang_1.CONST_EXPR(new Object()); + var AppView = (function() { + function AppView(proto, renderer, viewManager, projectableNodes, containerAppElement, imperativelyCreatedProviders, rootInjector, changeDetector) { + this.proto = proto; + this.renderer = renderer; + this.viewManager = viewManager; + this.projectableNodes = projectableNodes; + this.containerAppElement = containerAppElement; + this.changeDetector = changeDetector; + this.context = null; + this.destroyed = false; + this.ref = new view_ref_1.ViewRef_(this); + var injectorWithHostBoundary = element_1.AppElement.getViewParentInjector(this.proto.type, containerAppElement, imperativelyCreatedProviders, rootInjector); + this.parentInjector = injectorWithHostBoundary.injector; + this.hostInjectorBoundary = injectorWithHostBoundary.hostInjectorBoundary; + var pipes; + var context; + switch (proto.type) { + case view_type_1.ViewType.COMPONENT: + pipes = new pipes_2.Pipes(proto.protoPipes, containerAppElement.getInjector()); + context = containerAppElement.getComponent(); + break; + case view_type_1.ViewType.EMBEDDED: + pipes = containerAppElement.parentView.pipes; + context = containerAppElement.parentView.context; + break; + case view_type_1.ViewType.HOST: + pipes = null; + context = EMPTY_CONTEXT; + break; } - 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; + this.pipes = pipes; + this.context = context; } - 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); + AppView.prototype.init = function(rootNodesOrAppElements, allNodes, disposables, appElements) { + this.rootNodesOrAppElements = rootNodesOrAppElements; + this.allNodes = allNodes; + this.disposables = disposables; + this.appElements = appElements; + var localsMap = new collection_1.Map(); + collection_1.StringMapWrapper.forEach(this.proto.templateVariableBindings, function(templateName, _) { + localsMap.set(templateName, null); + }); + for (var i = 0; i < appElements.length; i++) { + var appEl = appElements[i]; + var providerTokens = []; + if (lang_1.isPresent(appEl.proto.protoInjector)) { + for (var j = 0; j < appEl.proto.protoInjector.numberOfProviders; j++) { + providerTokens.push(appEl.proto.protoInjector.getProviderAtIndex(j).key.token); + } + } + collection_1.StringMapWrapper.forEach(appEl.proto.directiveVariableBindings, function(directiveIndex, name) { + if (lang_1.isBlank(directiveIndex)) { + localsMap.set(name, appEl.nativeElement); + } else { + localsMap.set(name, appEl.getDirectiveAtIndex(directiveIndex)); + } + }); + this.renderer.setElementDebugInfo(appEl.nativeElement, new api_1.RenderDebugInfo(appEl.getInjector(), appEl.getComponent(), providerTokens, localsMap)); } - var binderIdx = componentView.proto.variableLocations.get(variableName); - if (lang_1.isBlank(binderIdx)) { - throw new exceptions_1.BaseException("Could not find variable " + variableName); + var parentLocals = null; + if (this.proto.type !== view_type_1.ViewType.COMPONENT) { + parentLocals = lang_1.isPresent(this.containerAppElement) ? this.containerAppElement.parentView.locals : null; } - 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!'); + if (this.proto.type === view_type_1.ViewType.COMPONENT) { + this.containerAppElement.attachComponentView(this); + this.containerAppElement.parentView.changeDetector.addViewChild(this.changeDetector); } - this._protoViewFactory.initializeProtoViewIfNeeded(protoView); - return profile_1.wtfLeave(s, this._createViewInContainer(viewContainerLocation, index, protoView, templateRef.elementRef, null)); + this.locals = new change_detection_1.Locals(parentLocals, localsMap); + this.changeDetector.hydrate(this.context, this.locals, this, this.pipes); + this.viewManager.onViewCreated(this); }; - 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; + AppView.prototype.destroy = function() { + if (this.destroyed) { + throw new exceptions_1.BaseException('This view has already been destroyed!'); } - return view.ref; + this.changeDetector.destroyRecursive(); }; - 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); + AppView.prototype.notifyOnDestroy = function() { + this.destroyed = true; + var hostElement = this.proto.type === view_type_1.ViewType.COMPONENT ? this.containerAppElement.nativeElement : null; + this.renderer.destroyView(hostElement, this.allNodes); + for (var i = 0; i < this.disposables.length; i++) { + this.disposables[i](); } + this.viewManager.onViewDestroyed(this); }; - 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); + Object.defineProperty(AppView.prototype, "changeDetectorRef", { + get: function() { + return this.changeDetector.ref; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AppView.prototype, "flatRootNodes", { + get: function() { + return flattenNestedViewRenderNodes(this.rootNodesOrAppElements); + }, + enumerable: true, + configurable: true + }); + AppView.prototype.hasLocal = function(contextName) { + return collection_1.StringMapWrapper.contains(this.proto.templateVariableBindings, contextName); }; - 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); + AppView.prototype.setLocal = function(contextName, value) { + if (!this.hasLocal(contextName)) { + return ; + } + var templateName = this.proto.templateVariableBindings[contextName]; + this.locals.set(templateName, value); }; - 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); + AppView.prototype.notifyOnBinding = function(b, currentValue) { + if (b.isTextNode()) { + this.renderer.setText(this.allNodes[b.elementIndex], currentValue); + } else { + var nativeElement = this.appElements[b.elementIndex].nativeElement; + if (b.isElementProperty()) { + this.renderer.setElementProperty(nativeElement, b.name, currentValue); + } else if (b.isElementAttribute()) { + this.renderer.setElementAttribute(nativeElement, b.name, lang_1.isPresent(currentValue) ? "" + currentValue : null); + } else if (b.isElementClass()) { + this.renderer.setElementClass(nativeElement, b.name, currentValue); + } else if (b.isElementStyle()) { + var unit = lang_1.isPresent(b.unit) ? b.unit : ''; + this.renderer.setElementStyle(nativeElement, 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 nativeElement = this.appElements[b.elementIndex].nativeElement; + this.renderer.setBindingDebugInfo(nativeElement, "" + REFLECT_PREFIX + util_1.camelCaseToDashCase(b.name), "" + value); + } }; - 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; + AppView.prototype.notifyAfterContentChecked = function() { + var count = this.appElements.length; + for (var i = count - 1; i >= 0; i--) { + this.appElements[i].ngAfterContentChecked(); + } }; - 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)); + AppView.prototype.notifyAfterViewChecked = function() { + var count = this.appElements.length; + for (var i = count - 1; i >= 0; i--) { + this.appElements[i].ngAfterViewChecked(); } - return view; }; - AppViewManager_.prototype._destroyPooledView = function(view) { - var wasReturned = this._viewPool.returnView(view); - if (!wasReturned) { - this._viewListener.onViewDestroyed(view); - this._renderer.destroyView(view.render); + AppView.prototype.getDebugContext = function(appElement, elementIndex, directiveIndex) { + try { + if (lang_1.isBlank(appElement) && elementIndex < this.appElements.length) { + appElement = this.appElements[elementIndex]; + } + var container = this.containerAppElement; + var element = lang_1.isPresent(appElement) ? appElement.nativeElement : null; + var componentElement = lang_1.isPresent(container) ? container.nativeElement : null; + var directive = lang_1.isPresent(directiveIndex) ? appElement.getDirectiveAtIndex(directiveIndex) : null; + var injector = lang_1.isPresent(appElement) ? appElement.getInjector() : null; + return new interfaces_1.DebugContext(element, componentElement, directive, this.context, _localsToStringMap(this.locals), injector); + } catch (e) { + return null; + } + }; + AppView.prototype.getDirectiveFor = function(directive) { + return this.appElements[directive.elementIndex].getDirectiveAtIndex(directive.directiveIndex); + }; + AppView.prototype.getDetectorFor = function(directive) { + var componentView = this.appElements[directive.elementIndex].componentView; + return lang_1.isPresent(componentView) ? componentView.changeDetector : null; + }; + AppView.prototype.triggerEventHandlers = function(eventName, eventObj, boundElementIndex) { + return this.changeDetector.handleEvent(eventName, boundElementIndex, eventObj); + }; + 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 AppProtoView = (function() { + function AppProtoView(type, protoPipes, templateVariableBindings) { + this.type = type; + this.protoPipes = protoPipes; + this.templateVariableBindings = templateVariableBindings; + } + AppProtoView.create = function(metadataCache, type, pipes, templateVariableBindings) { + var protoPipes = null; + if (lang_1.isPresent(pipes) && pipes.length > 0) { + var boundPipes = collection_1.ListWrapper.createFixedSize(pipes.length); + for (var i = 0; i < pipes.length; i++) { + boundPipes[i] = metadataCache.getResolvedPipeMetadata(pipes[i]); + } + protoPipes = pipes_1.ProtoPipes.fromProviders(boundPipes); } + return new AppProtoView(type, protoPipes, templateVariableBindings); }; - 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); + return AppProtoView; + })(); + exports.AppProtoView = AppProtoView; + var HostViewFactory = (function() { + function HostViewFactory(selector, viewFactory) { + this.selector = selector; + this.viewFactory = viewFactory; + } + HostViewFactory = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [String, Function])], HostViewFactory); + return HostViewFactory; + })(); + exports.HostViewFactory = HostViewFactory; + function flattenNestedViewRenderNodes(nodes) { + return _flattenNestedViewRenderNodes(nodes, []); + } + exports.flattenNestedViewRenderNodes = flattenNestedViewRenderNodes; + function _flattenNestedViewRenderNodes(nodes, renderNodes) { + for (var i = 0; i < nodes.length; i++) { + var node = nodes[i]; + if (node instanceof element_1.AppElement) { + var appEl = node; + renderNodes.push(appEl.nativeElement); + if (lang_1.isPresent(appEl.nestedViews)) { + for (var k = 0; k < appEl.nestedViews.length; k++) { + _flattenNestedViewRenderNodes(appEl.nestedViews[k].rootNodesOrAppElements, renderNodes); + } + } } 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); - } + renderNodes.push(node); + } + } + return renderNodes; + } + function findLastRenderNode(node) { + var lastNode; + if (node instanceof element_1.AppElement) { + var appEl = node; + lastNode = appEl.nativeElement; + if (lang_1.isPresent(appEl.nestedViews)) { + for (var i = appEl.nestedViews.length - 1; i >= 0; i--) { + var nestedView = appEl.nestedViews[i]; + if (nestedView.rootNodesOrAppElements.length > 0) { + lastNode = findLastRenderNode(nestedView.rootNodesOrAppElements[nestedView.rootNodesOrAppElements.length - 1]); } } } - }; - 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_; + } else { + lastNode = node; + } + return lastNode; + } + exports.findLastRenderNode = findLastRenderNode; + function checkSlotCount(componentName, expectedSlotCount, projectableNodes) { + var givenSlotCount = lang_1.isPresent(projectableNodes) ? projectableNodes.length : 0; + if (givenSlotCount < expectedSlotCount) { + throw new exceptions_1.BaseException(("The component " + componentName + " has " + expectedSlotCount + " elements,") + (" but only " + givenSlotCount + " slots were provided.")); + } + } + exports.checkSlotCount = checkSlotCount; 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) { +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/resolved_metadata_cache", "angular2/src/core/linker/view_manager", "angular2/src/core/linker/view_manager", "angular2/src/core/linker/view_resolver", "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 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 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 resolved_metadata_cache_1 = require("angular2/src/core/linker/resolved_metadata_cache"); + var view_manager_1 = require("angular2/src/core/linker/view_manager"); + var view_manager_2 = require("angular2/src/core/linker/view_manager"); + var view_resolver_1 = require("angular2/src/core/linker/view_resolver"); + 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, resolved_metadata_cache_1.ResolvedMetadataCache, new di_1.Provider(view_manager_1.AppViewManager, {useClass: view_manager_2.AppViewManager_}), 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/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 _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; - } + 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; } - 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); + Dependency.fromKey = function(key) { + return new Dependency(key, false, null, null, []); }; - return ProtoInjectorInlineStrategy; + return Dependency; })(); - 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; - } + 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; } - 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; + 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.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); + 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 + }); } - ProtoInjector.prototype.getProviderAtIndex = function(index) { - return this._strategy.getProviderAtIndex(index); - }; - return ProtoInjector; + 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.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; + exports.ResolvedProvider_ = ResolvedProvider_; + var ResolvedFactory = (function() { + function ResolvedFactory(factory, dependencies) { + this.factory = factory; + this.dependencies = dependencies; } - InjectorInlineStrategy.prototype.resetConstructionCounter = function() { - this.injector._constructionCounter = 0; + 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}); }; - InjectorInlineStrategy.prototype.instantiateProvider = function(provider, visibility) { - return this.injector._new(provider, visibility); + ProviderBuilder.prototype.toValue = function(value) { + return new Provider(this.token, {useValue: value}); }; - InjectorInlineStrategy.prototype.attach = function(parent, isHost) { - var inj = this.injector; - inj._parent = parent; - inj._isHost = isHost; + 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}); }; - 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; + 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!"); } - if (p.keyId1 === keyId && canSee(p.visibility1, visibility)) { - if (this.obj1 === exports.UNDEFINED) { - this.obj1 = inj._new(p.provider1, p.visibility1); + 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)], provider.multi); + } + exports.resolveProvider = resolveProvider; + function resolveProviders(providers) { + var normalized = _normalizeProviders(providers, []); + var resolved = normalized.map(resolveProvider); + return collection_1.MapWrapper.values(mergeResolvedProviders(resolved, new Map())); + } + exports.resolveProviders = resolveProviders; + function mergeResolvedProviders(providers, normalizedProvidersMap) { + for (var i = 0; i < providers.length; i++) { + var provider = providers[i]; + var existing = normalizedProvidersMap.get(provider.key.id); + if (lang_1.isPresent(existing)) { + if (provider.multiProvider !== existing.multiProvider) { + throw new exceptions_2.MixingMultiProvidersWithRegularProvidersError(existing, provider); + } + if (provider.multiProvider) { + for (var j = 0; j < provider.resolvedFactories.length; j++) { + existing.resolvedFactories.push(provider.resolvedFactories[j]); + } + } else { + normalizedProvidersMap.set(provider.key.id, provider); } - return this.obj1; - } - if (p.keyId2 === keyId && canSee(p.visibility2, visibility)) { - if (this.obj2 === exports.UNDEFINED) { - this.obj2 = inj._new(p.provider2, p.visibility2); + } else { + var resolvedProvider; + if (provider.multiProvider) { + resolvedProvider = new ResolvedProvider_(provider.key, collection_1.ListWrapper.clone(provider.resolvedFactories), provider.multiProvider); + } else { + resolvedProvider = provider; } - return this.obj2; + normalizedProvidersMap.set(provider.key.id, resolvedProvider); } - if (p.keyId3 === keyId && canSee(p.visibility3, visibility)) { - if (this.obj3 === exports.UNDEFINED) { - this.obj3 = inj._new(p.provider3, p.visibility3); - } - return this.obj3; + } + return normalizedProvidersMap; + } + exports.mergeResolvedProviders = mergeResolvedProviders; + function _normalizeProviders(providers, res) { + providers.forEach(function(b) { + if (b instanceof lang_1.Type) { + res.push(provide(b, {useClass: b})); + } else if (b instanceof Provider) { + res.push(b); + } 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); } - if (p.keyId4 === keyId && canSee(p.visibility4, visibility)) { - if (this.obj4 === exports.UNDEFINED) { - this.obj4 = inj._new(p.provider4, p.visibility4); - } - return this.obj4; + }); + return res; + } + 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); } - if (p.keyId5 === keyId && canSee(p.visibility5, visibility)) { - if (this.obj5 === exports.UNDEFINED) { - this.obj5 = inj._new(p.provider5, p.visibility5); + } + 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; } - return this.obj5; + depProps.push(paramMetadata); } - if (p.keyId6 === keyId && canSee(p.visibility6, visibility)) { - if (this.obj6 === exports.UNDEFINED) { - this.obj6 = inj._new(p.provider6, p.visibility6); + } + 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/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/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", "angular2/src/core/reflection/reflection", "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 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 reflection_1 = require("angular2/src/core/reflection/reflection"); + var async_1 = require("angular2/src/facade/async"); + var DynamicChangeDetector = (function(_super) { + __extends(DynamicChangeDetector, _super); + function DynamicChangeDetector(id, numberOfPropertyProtoRecords, propertyBindingTargets, directiveIndices, strategy, _records, _eventBindings, _directiveRecords, _genConfig) { + _super.call(this, id, numberOfPropertyProtoRecords, propertyBindingTargets, directiveIndices, strategy); + this._records = _records; + this._eventBindings = _eventBindings; + this._directiveRecords = _directiveRecords; + this._genConfig = _genConfig; + 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 this.obj6; - } - if (p.keyId7 === keyId && canSee(p.visibility7, visibility)) { - if (this.obj7 === exports.UNDEFINED) { - this.obj7 = inj._new(p.provider7, p.visibility7); + }); + 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 { + if (proto.lastInBinding) { + this._markPathAsCheckOnce(proto); + } + var res = this._calculateCurrValue(proto, values, locals); + if (proto.lastInBinding) { + return res; + } else { + this._writeSelf(proto, res, values); + } } - 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; + 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 (p.keyId9 === keyId && canSee(p.visibility9, visibility)) { - if (this.obj9 === exports.UNDEFINED) { - this.obj9 = inj._new(p.provider9, p.visibility9); - } - return this.obj9; + if (proto.mode === proto_record_1.RecordType.SkipRecordsIf) { + var condition = this._readContext(proto, values); + return condition ? proto.fixedArgs[0] - protoIndex - 1 : 0; } - return exports.UNDEFINED; + 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"); }; - 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); + DynamicChangeDetector.prototype._markPathAsCheckOnce = function(proto) { + if (!proto.bindingRecord.isDefaultChangeDetection()) { + var dir = proto.bindingRecord.directiveRecord; + this._getDetectorFor(dir.directiveIndex).markPathToRootAsCheckOnce(); + } }; - InjectorInlineStrategy.prototype.getMaxNumberOfObjects = function() { - return _MAX_CONSTRUCTION_COUNTER; + DynamicChangeDetector.prototype._matchingEventBindings = function(eventName, elIndex) { + return this._eventBindings.filter(function(eb) { + return eb.eventName == eventName && eb.elIndex === elIndex; + }); }; - 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; + DynamicChangeDetector.prototype.hydrateDirectives = function(dispatcher) { + var _this = this; + this.values[0] = this.context; + this.dispatcher = dispatcher; + this.outputSubscriptions = []; + for (var i = 0; i < this._directiveRecords.length; ++i) { + var r = this._directiveRecords[i]; + if (lang_1.isPresent(r.outputs)) { + r.outputs.forEach(function(output) { + var eventHandler = _this._createEventHandler(r.directiveIndex.elementIndex, output[1]); + var directive = _this._getDirectiveFor(r.directiveIndex); + var getter = reflection_1.reflector.getter(output[0]); + _this.outputSubscriptions.push(async_1.ObservableWrapper.subscribe(getter(directive), eventHandler)); + }); + } + } }; - InjectorDynamicStrategy.prototype.instantiateProvider = function(provider, visibility) { - return this.injector._new(provider, visibility); + DynamicChangeDetector.prototype._createEventHandler = function(boundElementIndex, eventName) { + var _this = this; + return function(event) { + return _this.handleEvent(eventName, boundElementIndex, event); + }; }; - InjectorDynamicStrategy.prototype.attach = function(parent, isHost) { - var inj = this.injector; - inj._parent = parent; - inj._isHost = isHost; + DynamicChangeDetector.prototype.dehydrateDirectives = function(destroyPipes) { + if (destroyPipes) { + this._destroyPipes(); + this._destroyDirectives(); + } + this.values[0] = 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); }; - 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]; + 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]); } } - return exports.UNDEFINED; }; - InjectorDynamicStrategy.prototype.getObjAtIndex = function(index) { - if (index < 0 || index >= this.objs.length) { - throw new exceptions_1.OutOfBoundsError(index); + DynamicChangeDetector.prototype._destroyDirectives = function() { + for (var i = 0; i < this._directiveRecords.length; ++i) { + var record = this._directiveRecords[i]; + if (record.callOnDestroy) { + this._getDirectiveFor(record.directiveIndex).ngOnDestroy(); + } } - 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; + DynamicChangeDetector.prototype.checkNoChanges = function() { + this.runDetectChanges(true); }; - 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; + 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; + } } - 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); + 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; }; - Injector.prototype.getAt = function(index) { - return this._strategy.getObjAtIndex(index); + 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(); + } + } }; - 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); + 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(); + } + } }; - 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; + 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); + } }; - Injector.prototype.resolveAndInstantiate = function(provider) { - return this.instantiateResolved(Injector.resolve([provider])[0]); + DynamicChangeDetector.prototype._addChange = function(bindingRecord, change, changes) { + if (bindingRecord.callOnChanges()) { + return _super.prototype.addChange.call(this, changes, change.previousValue, change.currentValue); + } else { + return changes; + } }; - Injector.prototype.instantiateResolved = function(provider) { - return this._instantiateProvider(provider, Visibility.PublicAndPrivate); + DynamicChangeDetector.prototype._getDirectiveFor = function(directiveIndex) { + return this.dispatcher.getDirectiveFor(directiveIndex); }; - 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); + DynamicChangeDetector.prototype._getDetectorFor = function(directiveIndex) { + return this.dispatcher.getDetectorFor(directiveIndex); }; - 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; + DynamicChangeDetector.prototype._check = function(proto, throwOnChange, values, locals) { + if (proto.isPipeRecord()) { + return this._pipeCheck(proto, throwOnChange, values); } else { - return this._instantiate(provider, provider.resolvedFactories[0], visibility); + return this._referenceCheck(proto, throwOnChange, values, locals); } }; - 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; + DynamicChangeDetector.prototype._referenceCheck = function(proto, throwOnChange, values, locals) { + if (this._pureFuncAndArgsDidNotChange(proto)) { + this._setChanged(proto, false); + return null; } - 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; + var currValue = this._calculateCurrValue(proto, values, locals); + if (proto.shouldBeChecked()) { + var prevValue = this._readSelf(proto, values); + var detectedChange = throwOnChange ? !change_detection_util_1.ChangeDetectionUtil.devModeEqual(prevValue, currValue) : change_detection_util_1.ChangeDetectionUtil.looseNotIdentical(prevValue, currValue); + if (detectedChange) { + 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; } - } 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) { + this._writeSelf(proto, currValue, values); + this._setChanged(proto, true); 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; - } + 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); } - 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); + }; + 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); + var detectedChange = throwOnChange ? !change_detection_util_1.ChangeDetectionUtil.devModeEqual(prevValue, currValue) : change_detection_util_1.ChangeDetectionUtil.looseNotIdentical(prevValue, currValue); + if (detectedChange) { + 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 { - inj = inj._parent; + this._writeSelf(proto, currValue, values); + this._setChanged(proto, true); + return null; } } - 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); + 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; }; - 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; + DynamicChangeDetector.prototype._readContext = function(proto, values) { + if (proto.contextIndex == -1) { + return this._getDirectiveFor(proto.directiveIndex); } - return this._throwOrNull(key, optional); + return values[proto.contextIndex]; }; - 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; + DynamicChangeDetector.prototype._readSelf = function(proto, values) { + return values[proto.selfIndex]; }; - 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))); + 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/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); } - return res; - } + JitProtoChangeDetector.isSupported = function() { + return true; + }; + JitProtoChangeDetector.prototype.instantiate = function() { + return this._factory(); + }; + 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/animate/animation_builder", ["angular2/src/core/di", "angular2/src/animate/css_animation_builder", "angular2/src/animate/browser_details"], true, function(require, exports, module) { +System.register("angular2/src/core/linker/compiler", ["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/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 __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, @@ -12101,1550 +11229,1127 @@ System.register("angular2/src/animate/animation_builder", ["angular2/src/core/di 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; + 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 view_1 = require("angular2/src/core/linker/view"); + var view_ref_1 = require("angular2/src/core/linker/view_ref"); + var Compiler = (function() { + function Compiler() {} + return Compiler; + })(); + exports.Compiler = Compiler; + function isHostViewFactory(type) { + return type instanceof view_1.HostViewFactory; + } + var Compiler_ = (function(_super) { + __extends(Compiler_, _super); + function Compiler_() { + _super.apply(this, arguments); } - AnimationBuilder.prototype.css = function() { - return new css_animation_builder_1.CssAnimationBuilder(this.browserDetails); + Compiler_.prototype.compileInHost = function(componentType) { + var metadatas = reflection_1.reflector.annotations(componentType); + var hostViewFactory = metadatas.find(isHostViewFactory); + if (lang_1.isBlank(hostViewFactory)) { + throw new exceptions_1.BaseException("No precompiled component " + lang_1.stringify(componentType) + " found"); + } + return async_1.PromiseWrapper.resolve(new view_ref_1.HostViewFactoryRef_(hostViewFactory)); }; - AnimationBuilder = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [browser_details_1.BrowserDetails])], AnimationBuilder); - return AnimationBuilder; - })(); - exports.AnimationBuilder = AnimationBuilder; + Compiler_.prototype.clearCache = function() {}; + Compiler_ = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], Compiler_); + return Compiler_; + })(Compiler); + exports.Compiler_ = Compiler_; 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) { +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/facade/exceptions", "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 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); - }); + 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 exceptions_2 = require("angular2/src/facade/exceptions"); + 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); } - 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); + 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; } - }; - 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; - } + if (length > 1) { + this.provider1 = bwv[1].provider; + this.keyId1 = bwv[1].getKeyId(); + this.visibility1 = bwv[1].visibility; } - }; - 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); + if (length > 2) { + this.provider2 = bwv[2].provider; + this.keyId2 = bwv[2].getKeyId(); + this.visibility2 = bwv[2].visibility; } - }; - 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); + if (length > 3) { + this.provider3 = bwv[3].provider; + this.keyId3 = bwv[3].getKeyId(); + this.visibility3 = bwv[3].visibility; } - }; - _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); + if (length > 4) { + this.provider4 = bwv[4].provider; + this.keyId4 = bwv[4].getKeyId(); + this.visibility4 = bwv[4].visibility; } - }; - _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); + if (length > 5) { + this.provider5 = bwv[5].provider; + this.keyId5 = bwv[5].getKeyId(); + this.visibility5 = bwv[5].visibility; } - }; - _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); + 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); }; - _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); + ProtoInjectorInlineStrategy.prototype.createInjectorStrategy = function(injector) { + return new InjectorInlineStrategy(injector, this); }; - _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); + 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]; }; - _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); + ProtoInjectorDynamicStrategy.prototype.createInjectorStrategy = function(ei) { + return new InjectorDynamicStrategy(this, ei); }; - _ConvertAstIntoProtoRecords.prototype.visitChain = function(ast) { - var _this = this; - var args = ast.expressions.map(function(e) { - return e.visit(_this); + 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.fromResolvedProviders = function(providers) { + var bd = providers.map(function(b) { + return new ProviderWithVisibility(b, Visibility.Public); }); - 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; + return new ProtoInjector(bd); }; - _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; + ProtoInjector.prototype.getProviderAtIndex = function(index) { + return this._strategy.getProviderAtIndex(index); }; - return _ConvertAstIntoProtoRecords; + return ProtoInjector; })(); - 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); + 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; } - 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(); + InjectorInlineStrategy.prototype.resetConstructionCounter = function() { + this.injector._constructionCounter = 0; }; - 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; + InjectorInlineStrategy.prototype.instantiateProvider = function(provider, visibility) { + return this.injector._new(provider, visibility); }; - return StaticKeys; - })(); - exports.StaticKeys = StaticKeys; - var TreeNode = (function() { - function TreeNode(parent) { - if (lang_1.isPresent(parent)) { - parent.addChild(this); - } else { - this._parent = null; + 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; } - } - 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(); + if (p.keyId1 === keyId && canSee(p.visibility1, visibility)) { + if (this.obj1 === exports.UNDEFINED) { + this.obj1 = inj._new(p.provider1, p.visibility1); + } + return this.obj1; } - 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)); - }); + if (p.keyId2 === keyId && canSee(p.visibility2, visibility)) { + if (this.obj2 === exports.UNDEFINED) { + this.obj2 = inj._new(p.provider2, p.visibility2); + } + return this.obj2; } - }); - 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]); + if (p.keyId3 === keyId && canSee(p.visibility3, visibility)) { + if (this.obj3 === exports.UNDEFINED) { + this.obj3 = inj._new(p.provider3, p.visibility3); + } + return this.obj3; } - 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); + if (p.keyId4 === keyId && canSee(p.visibility4, visibility)) { + if (this.obj4 === exports.UNDEFINED) { + this.obj4 = inj._new(p.provider4, p.visibility4); + } + return this.obj4; } - 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); + if (p.keyId5 === keyId && canSee(p.visibility5, visibility)) { + if (this.obj5 === exports.UNDEFINED) { + this.obj5 = inj._new(p.provider5, p.visibility5); } - } 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); + return this.obj5; + } + if (p.keyId6 === keyId && canSee(p.visibility6, visibility)) { + if (this.obj6 === exports.UNDEFINED) { + this.obj6 = inj._new(p.provider6, p.visibility6); } - } else { - if (lang_1.isPresent(imperativelyCreatedInjector)) { - this._reattachInjector(this._injector, imperativelyCreatedInjector, true); + 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; }; - 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; + 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); }; - ElementInjector.prototype.getView = function() { - return this._preBuiltObjects.view; + InjectorInlineStrategy.prototype.getMaxNumberOfObjects = function() { + return _MAX_CONSTRUCTION_COUNTER; }; - ElementInjector.prototype.directParent = function() { - return this._proto.distanceToParent < 2 ? this.parent : null; + 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; }; - ElementInjector.prototype.isComponentKey = function(key) { - return this._strategy.isComponentKey(key); + InjectorDynamicStrategy.prototype.instantiateProvider = function(provider, visibility) { + return this.injector._new(provider, visibility); }; - 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); + 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._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 this.objs[i]; } } - return injector_1.UNDEFINED; + return exports.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; + InjectorDynamicStrategy.prototype.getObjAtIndex = function(index) { + if (index < 0 || index >= this.objs.length) { + throw new exceptions_1.OutOfBoundsError(index); } + return this.objs[index]; }; - 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); + InjectorDynamicStrategy.prototype.getMaxNumberOfObjects = function() { + return this.objs.length; }; - 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); - } + 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; }; - ElementInjector.prototype.link = function(parent) { - parent.addChild(this); + return ProviderWithVisibility; + })(); + exports.ProviderWithVisibility = ProviderWithVisibility; + var Injector = (function() { + function Injector(_proto, _parent, _isHostBoundary, _depProvider, _debugContext) { + if (_parent === void 0) { + _parent = null; + } + if (_isHostBoundary === void 0) { + _isHostBoundary = false; + } + if (_depProvider === void 0) { + _depProvider = null; + } + if (_debugContext === void 0) { + _debugContext = null; + } + this._isHostBoundary = _isHostBoundary; + this._depProvider = _depProvider; + this._debugContext = _debugContext; + this._constructionCounter = 0; + this._proto = _proto; + this._parent = _parent; + this._strategy = _proto._strategy.createInjectorStrategy(this); + } + Injector.resolve = function(providers) { + return provider_1.resolveProviders(providers); }; - ElementInjector.prototype.unlink = function() { - this.remove(); + Injector.resolveAndCreate = function(providers) { + var resolvedProviders = Injector.resolve(providers); + return Injector.fromResolvedProviders(resolvedProviders); }; - ElementInjector.prototype.getDirectiveAtIndex = function(index) { - return this._injector.getAt(index); + Injector.fromResolvedProviders = function(providers) { + return new Injector(ProtoInjector.fromResolvedProviders(providers)); }; - ElementInjector.prototype.hasInstances = function() { - return this._proto.hasBindings && this.hydrated; + Injector.fromResolvedBindings = function(providers) { + return Injector.fromResolvedProviders(providers); }; - ElementInjector.prototype.getHost = function() { - return this._host; + Object.defineProperty(Injector.prototype, "hostBoundary", { + get: function() { + return this._isHostBoundary; + }, + enumerable: true, + configurable: true + }); + Injector.prototype.debugContext = function() { + return this._debugContext(); }; - ElementInjector.prototype.getBoundElementIndex = function() { - return this._proto.index; + Injector.prototype.get = function(token) { + return this._getByKey(key_1.Key.get(token), null, null, false, Visibility.PublicAndPrivate); }; - 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 : []; + Injector.prototype.getOptional = function(token) { + return this._getByKey(key_1.Key.get(token), null, null, true, Visibility.PublicAndPrivate); }; - ElementInjector.prototype.ngAfterViewChecked = function() { - this._queryStrategy.updateViewQueries(); + Injector.prototype.getAt = function(index) { + return this._strategy.getObjAtIndex(index); }; - ElementInjector.prototype.ngAfterContentChecked = function() { - this._queryStrategy.updateContentQueries(); + 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); }; - ElementInjector.prototype.traverseAndSetQueriesAsDirty = function() { - var inj = this; - while (lang_1.isPresent(inj)) { - inj._setQueriesAsDirty(); - inj = inj.parent; - } + 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); + inj._parent = this; + return inj; }; - ElementInjector.prototype._setQueriesAsDirty = function() { - this._queryStrategy.setContentQueriesAsDirty(); - if (lang_1.isPresent(this._host)) - this._host._queryStrategy.setViewQueriesAsDirty(); + Injector.prototype.resolveAndInstantiate = function(provider) { + return this.instantiateResolved(Injector.resolve([provider])[0]); }; - 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 + "."); + Injector.prototype.instantiateResolved = function(provider) { + return this._instantiateProvider(provider, Visibility.PublicAndPrivate); }; - 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; + 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); }; - 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; + 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); + } }; - 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(); + Injector.prototype._instantiate = function(provider, resolvedFactory, visibility) { + var factory = resolvedFactory.factory; + var deps = resolvedFactory.dependencies; + var length = deps.length; + var d0; + var d1; + var d2; + var d3; + var d4; + var d5; + var d6; + var d7; + var d8; + var d9; + var d10; + var d11; + var d12; + var d13; + var d14; + var d15; + var d16; + var d17; + var d18; + var 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; + default: + throw new exceptions_2.BaseException("Cannot instantiate '" + provider.key.displayName + "' because it has more than 20 dependencies"); + } + } catch (e) { + throw new exceptions_1.InstantiationError(this, e, e.stack, provider.key); + } + return obj; }; - InlineQueryStrategy.prototype.updateContentQueries = function() { - if (lang_1.isPresent(this.query0) && !this.query0.isViewQuery) { - this.query0.update(); + 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); } - if (lang_1.isPresent(this.query1) && !this.query1.isViewQuery) { - this.query1.update(); + }; + Injector.prototype._getByKey = function(key, lowerBoundVisibility, upperBoundVisibility, optional, providerVisibility) { + if (key === INJECTOR_KEY) { + return this; } - if (lang_1.isPresent(this.query2) && !this.query2.isViewQuery) { - this.query2.update(); + 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); } }; - InlineQueryStrategy.prototype.updateViewQueries = function() { - if (lang_1.isPresent(this.query0) && this.query0.isViewQuery) { - this.query0.update(); + Injector.prototype._throwOrNull = function(key, optional) { + if (optional) { + return null; + } else { + throw new exceptions_1.NoProviderError(this, key); } - if (lang_1.isPresent(this.query1) && this.query1.isViewQuery) { - this.query1.update(); + }; + 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._isHostBoundary) { + return this._getPrivateDependency(key, optional, inj); + } else { + inj = inj._parent; + } } - if (lang_1.isPresent(this.query2) && this.query2.isViewQuery) { - this.query2.update(); + while (inj != null) { + var obj = inj._strategy.getObjByKeyId(key.id, providerVisibility); + if (obj !== exports.UNDEFINED) + return obj; + if (lang_1.isPresent(inj._parent) && inj._isHostBoundary) { + return this._getPrivateDependency(key, optional, inj); + } else { + inj = inj._parent; + } } + return this._throwOrNull(key, optional); }; - 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; + 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._isHostBoundary ? Visibility.PublicAndPrivate : Visibility.Public; + inj = inj._parent; } - if (lang_1.isPresent(this.query2) && this.query2.protoQueryRef.query === query) { - return this.query2; + while (inj != null) { + var obj = inj._strategy.getObjByKeyId(key.id, providerVisibility); + if (obj !== exports.UNDEFINED) + return obj; + providerVisibility = inj._isHostBoundary ? Visibility.PublicAndPrivate : Visibility.Public; + inj = inj._parent; } - throw new exceptions_1.BaseException("Cannot find query for directive " + query + "."); + return this._throwOrNull(key, optional); }; - InlineQueryStrategy.NUMBER_OF_SUPPORTED_QUERIES = 3; - return InlineQueryStrategy; + 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; })(); - var DynamicQueryStrategy = (function() { - function DynamicQueryStrategy(ei) { - this.queries = ei._proto.protoQueryRefs.map(function(p) { - return new QueryRef(p, ei); + 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/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; }); } - DynamicQueryStrategy.prototype.setContentQueriesAsDirty = function() { - for (var i = 0; i < this.queries.length; ++i) { - var q = this.queries[i]; - if (!q.isViewQuery) - q.dirty = true; - } + DynamicProtoChangeDetector.prototype.instantiate = function() { + return new dynamic_change_detector_1.DynamicChangeDetector(this._definition.id, this._propertyBindingRecords.length, this._propertyBindingTargets, this._directiveIndices, this._definition.strategy, this._propertyBindingRecords, this._eventBindingRecords, this._definition.directiveRecords, this._definition.genConfig); }; - 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(); + 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; } - }; - DynamicQueryStrategy.prototype.dehydrate = function() { - for (var i = 0; i < this.queries.length; ++i) { - var q = this.queries[i]; - q.dehydrate(); + 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); } }; - DynamicQueryStrategy.prototype.updateContentQueries = function() { - for (var i = 0; i < this.queries.length; ++i) { - var q = this.queries[i]; - if (!q.isViewQuery) { - q.update(); + 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; + }); } - } - }; - DynamicQueryStrategy.prototype.updateViewQueries = function() { - for (var i = 0; i < this.queries.length; ++i) { - var q = this.queries[i]; - if (q.isViewQuery) { - q.update(); + 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; } } }; - 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; - } + 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); } - throw new exceptions_1.BaseException("Cannot find query for directive " + query + "."); }; - return DynamicQueryStrategy; + return ProtoRecordBuilder; })(); - var ElementInjectorInlineStrategy = (function() { - function ElementInjectorInlineStrategy(injectorStrategy, _ei) { - this.injectorStrategy = injectorStrategy; - this._ei = _ei; + exports.ProtoRecordBuilder = ProtoRecordBuilder; + var _ConvertAstIntoProtoRecords = (function() { + function _ConvertAstIntoProtoRecords(_records, _bindingRecord, _variableNames, _bindingIndex) { + this._records = _records; + this._bindingRecord = _bindingRecord; + this._variableNames = _variableNames; + this._bindingIndex = _bindingIndex; } - 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); + _ConvertAstIntoProtoRecords.append = function(records, b, variableNames, bindingIndex) { + var c = new _ConvertAstIntoProtoRecords(records, b, variableNames, bindingIndex); + b.ast.visit(c); }; - 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(); - } + _ConvertAstIntoProtoRecords.create = function(b, variableNames) { + var rec = []; + _ConvertAstIntoProtoRecords.append(rec, b, variableNames, null); + rec[rec.length - 1].lastInBinding = true; + return rec; }; - ElementInjectorInlineStrategy.prototype.getComponent = function() { - return this.injectorStrategy.obj0; + _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); }; - ElementInjectorInlineStrategy.prototype.isComponentKey = function(key) { - return this._ei._proto._firstProviderIsComponent && lang_1.isPresent(key) && key.id === this.injectorStrategy.protoStrategy.keyId0; + _ConvertAstIntoProtoRecords.prototype.visitLiteralPrimitive = function(ast) { + return this._addRecord(proto_record_1.RecordType.Const, "literal", ast.value, [], null, 0); }; - 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); + _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); } }; - 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]); - } + _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); } }; - ElementInjectorDynamicStrategy.prototype.dehydrate = function() { - var inj = this.injectorStrategy; - collection_1.ListWrapper.fill(inj.objs, injector_1.UNDEFINED); + _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); }; - 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(); - } + _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); } }; - ElementInjectorDynamicStrategy.prototype.getComponent = function() { - return this.injectorStrategy.objs[0]; + _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); }; - ElementInjectorDynamicStrategy.prototype.isComponentKey = function(key) { - var p = this.injectorStrategy.protoStrategy; - return this._ei._proto._firstProviderIsComponent && lang_1.isPresent(key) && key.id === p.keyIds[0]; + _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); }; - 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]); - } - } + _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); }; - 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(); + _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); }; - 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); + _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); } - 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); - } + _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); }; - QueryRef.prototype._visitInjector = function(inj, aggregator) { - if (this.protoQueryRef.query.isVarBindingQuery) { - this._aggregateVariableBinding(inj, aggregator); - } else { - this._aggregateDirective(inj, aggregator); - } + _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); }; - QueryRef.prototype._visitViewContainer = function(vc, aggregator) { - for (var j = 0; j < vc.views.length; j++) { - this._visitView(vc.views[j], aggregator); - } + _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); }; - 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); - } + _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); }; - 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])); - } - } + _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); }; - QueryRef.prototype._aggregateDirective = function(inj, aggregator) { - inj.addDirectivesMatchingQuery(this.protoQueryRef.query, aggregator); + _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.")); }; - QueryRef.prototype.dehydrate = function() { - this.list = null; + _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; }; - QueryRef.prototype.hydrate = function() { - this.list = new query_list_1.QueryList(); - this.dirty = true; + _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 QueryRef; + return _ConvertAstIntoProtoRecords; })(); - 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]; + 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"); + } } - 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) { +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, @@ -13661,385 +12366,234 @@ System.register("angular2/src/core/linker/proto_view_factory", ["angular2/src/fa 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; + 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.internalElement.parentView.ref; + }, + 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; } - 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; + Object.defineProperty(ComponentRef_.prototype, "hostComponentType", { + get: function() { + return this.componentType; + }, + enumerable: true, + configurable: true + }); + ComponentRef_.prototype.dispose = function() { + this._dispose(); }; - 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; + return ComponentRef_; + })(ComponentRef); + exports.ComponentRef_ = ComponentRef_; + var DynamicComponentLoader = (function() { + function DynamicComponentLoader() {} + return DynamicComponentLoader; })(); - 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(); + 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, projectableNodes) { + var _this = this; + return this._compiler.compileInHost(type).then(function(hostProtoViewRef) { + var hostViewRef = _this._viewManager.createRootHostView(hostProtoViewRef, overrideSelector, injector, projectableNodes); + 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); + }); }; - _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; + DynamicComponentLoader_.prototype.loadIntoLocation = function(type, hostLocation, anchorName, providers, projectableNodes) { + if (providers === void 0) { + providers = null; } - 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); + if (projectableNodes === void 0) { + projectableNodes = null; } - 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 this.loadNextToLocation(type, this._viewManager.getNamedElementInComponentView(hostLocation, anchorName), providers, projectableNodes); }; - 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); + DynamicComponentLoader_.prototype.loadNextToLocation = function(type, location, providers, projectableNodes) { + var _this = this; + if (providers === void 0) { + providers = null; } - } - } - 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); + if (projectableNodes === void 0) { + projectableNodes = null; } - } - return out; - } + return this._compiler.compileInHost(type).then(function(hostProtoViewRef) { + var viewContainer = _this._viewManager.getViewContainer(location); + var hostViewRef = viewContainer.createHostView(hostProtoViewRef, viewContainer.length, providers, projectableNodes); + var newLocation = _this._viewManager.getHostElement(hostViewRef); + var component = _this._viewManager.getComponent(newLocation); + var dispose = function() { + var index = viewContainer.indexOf(hostViewRef); + if (!hostViewRef.destroyed && 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/change_detection", ["angular2/src/core/change_detection/change_detection"], true, function(require, exports, module) { +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; - 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; + 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; + 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/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) { +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/differs/default_keyvalue_differ", "angular2/src/core/change_detection/differs/default_iterable_differ", "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 __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 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 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; + var default_keyvalue_differ_2 = require("angular2/src/core/change_detection/differs/default_keyvalue_differ"); + exports.DefaultKeyValueDifferFactory = default_keyvalue_differ_2.DefaultKeyValueDifferFactory; + exports.KeyValueChangeRecord = default_keyvalue_differ_2.KeyValueChangeRecord; + var default_iterable_differ_2 = require("angular2/src/core/change_detection/differs/default_iterable_differ"); + exports.DefaultIterableDifferFactory = default_iterable_differ_2.DefaultIterableDifferFactory; + exports.CollectionChangeRecord = default_iterable_differ_2.CollectionChangeRecord; + 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/metadata/directives", ["angular2/src/facade/lang", "angular2/src/core/di/metadata", "angular2/src/core/change_detection"], true, function(require, exports, module) { +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/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; @@ -14052,223 +12606,451 @@ System.register("angular2/src/core/metadata/directives", ["angular2/src/facade/l } 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 ng_zone_1 = require("angular2/src/core/zone/ng_zone"); 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; + 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 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; + var testability = injector.getOptional(testability_1.Testability); + if (lang_1.isPresent(testability)) { + injector.get(testability_1.TestabilityRegistry).registerApplication(componentRef.location.nativeElement, 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; } - 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 + } + exports.disposePlatform = disposePlatform; + function _createPlatform(providers) { + _platformProviders = providers; + var injector = di_1.Injector.resolveAndCreate(providers); + _platform = new PlatformRef_(injector, function() { + _platform = null; + _platformProviders = null; }); - Object.defineProperty(DirectiveMetadata.prototype, "properties", { + _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 this.inputs; + throw exceptions_1.unimplemented(); }, enumerable: true, configurable: true }); - Object.defineProperty(DirectiveMetadata.prototype, "outputs", { + ; + 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 lang_1.isPresent(this._events) && this._events.length > 0 ? this._events : this._outputs; + return this._injector; }, enumerable: true, configurable: true }); - Object.defineProperty(DirectiveMetadata.prototype, "events", { + PlatformRef_.prototype.application = function(providers) { + var app = this._initApp(createNgZone(), providers); + if (async_1.PromiseWrapper.isPromise(app)) { + throw new exceptions_1.BaseException("Cannot use asyncronous app initializers with application. Use asyncApplication instead."); + } + return app; + }; + PlatformRef_.prototype.asyncApplication = function(bindingFn, additionalProviders) { + var _this = this; + var zone = createNgZone(); + var completer = async_1.PromiseWrapper.completer(); + if (bindingFn === null) { + completer.resolve(this._initApp(zone, additionalProviders)); + } else { + zone.run(function() { + async_1.PromiseWrapper.then(bindingFn(zone), function(providers) { + if (lang_1.isPresent(additionalProviders)) { + providers = collection_1.ListWrapper.concat(providers, additionalProviders); + } + var promise = _this._initApp(zone, providers); + completer.resolve(promise); + }); + }); + } + 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); + async_1.ObservableWrapper.subscribe(zone.onError, function(error) { + exceptionHandler.call(error.error, error.stackTrace); + }); + } 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); + var promise = _runAppInitializers(injector); + if (promise !== null) { + return async_1.PromiseWrapper.then(promise, function(_) { + return app; + }); + } else { + 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); + var promises = []; + if (lang_1.isPresent(inits)) { + inits.forEach(function(init) { + var retVal = init(); + if (async_1.PromiseWrapper.isPromise(retVal)) { + promises.push(retVal); + } + }); + } + if (promises.length > 0) { + return async_1.PromiseWrapper.all(promises); + } else { + return null; + } + } + var ApplicationRef = (function() { + function ApplicationRef() {} + Object.defineProperty(ApplicationRef.prototype, "injector", { get: function() { - return this.outputs; + return exceptions_1.unimplemented(); }, enumerable: true, configurable: true }); - Object.defineProperty(DirectiveMetadata.prototype, "providers", { + ; + Object.defineProperty(ApplicationRef.prototype, "zone", { get: function() { - return lang_1.isPresent(this._bindings) && this._bindings.length > 0 ? this._bindings : this._providers; + return exceptions_1.unimplemented(); }, enumerable: true, configurable: true }); - Object.defineProperty(DirectiveMetadata.prototype, "bindings", { + ; + Object.defineProperty(ApplicationRef.prototype, "componentTypes", { get: function() { - return this.providers; + return exceptions_1.unimplemented(); }, 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; + ; + 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.onMicrotaskEmpty, function(_) { + _this._zone.run(function() { + _this.tick(); + }); + }); + } + this._enforceNoNewChanges = lang_1.assertionsEnabled(); } - Object.defineProperty(ComponentMetadata.prototype, "viewProviders", { + 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); + async_1.PromiseWrapper.then(tickResult, null, function(err, stackTrace) { + completer.reject(err, stackTrace); + exceptionHandler.call(err, stackTrace); + }); + } catch (e) { + exceptionHandler.call(e, e.stack); + completer.reject(e, e.stack); + } + }); + return completer.promise.then(function(ref) { + var c = _this._injector.get(console_1.Console); + if (lang_1.assertionsEnabled()) { + c.log("Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode."); + } + return ref; + }); + }; + ApplicationRef_.prototype._loadComponent = function(componentRef) { + var appChangeDetector = componentRef.location.internalElement.parentView.changeDetector; + this._changeDetectorRefs.push(appChangeDetector.ref); + this.tick(); + this._rootComponents.push(componentRef); + this._bootstrapListeners.forEach(function(listener) { + return listener(componentRef); + }); + }; + ApplicationRef_.prototype._unloadComponent = function(componentRef) { + if (!collection_1.ListWrapper.contains(this._rootComponents, componentRef)) { + return ; + } + this.unregisterChangeDetector(componentRef.location.internalElement.parentView.changeDetector.ref); + collection_1.ListWrapper.remove(this._rootComponents, componentRef); + }; + Object.defineProperty(ApplicationRef_.prototype, "injector", { get: function() { - return lang_1.isPresent(this._viewBindings) && this._viewBindings.length > 0 ? this._viewBindings : this._viewProviders; + return this._injector; }, enumerable: true, configurable: true }); - Object.defineProperty(ComponentMetadata.prototype, "viewBindings", { + Object.defineProperty(ApplicationRef_.prototype, "zone", { get: function() { - return this.viewProviders; + return this._zone; }, 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", { + 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 lang_1.isPresent(this._pure) ? this._pure : true; + return this._rootComponentTypes; }, 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; + ApplicationRef_._tickScope = profile_1.wtfCreateScope('ApplicationRef#tick()'); + return ApplicationRef_; + })(ApplicationRef); + exports.ApplicationRef_ = ApplicationRef_; + 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; + exports.CollectionChangeRecord = change_detection_1.CollectionChangeRecord; + exports.KeyValueChangeRecord = change_detection_1.KeyValueChangeRecord; + 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_node", "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_node_1 = require("angular2/src/core/debug/debug_node"); + exports.DebugElement = debug_node_1.DebugElement; + exports.DebugNode = debug_node_1.DebugNode; + exports.asNativeElements = debug_node_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/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) { +System.register("angular2/src/facade/async", ["angular2/src/facade/lang", "angular2/src/facade/promise", "rxjs/Subject", "rxjs/observable/PromiseObservable", "rxjs/operator/toPromise", "rxjs/Observable", "rxjs/Subject"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -14284,9 +13066,9 @@ System.register("angular2/src/facade/async", ["angular2/src/facade/lang", "angul 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; + exports.PromiseCompleter = promise_1.PromiseCompleter; var Subject_1 = require("rxjs/Subject"); - var fromPromise_1 = require("rxjs/observable/fromPromise"); + var PromiseObservable_1 = require("rxjs/observable/PromiseObservable"); var toPromise_1 = require("rxjs/operator/toPromise"); var Observable_1 = require("rxjs/Observable"); exports.Observable = Observable_1.Observable; @@ -14345,7 +13127,7 @@ System.register("angular2/src/facade/async", ["angular2/src/facade/lang", "angul emitter.complete(); }; ObservableWrapper.fromPromise = function(promise) { - return fromPromise_1.PromiseObservable.create(promise); + return PromiseObservable_1.PromiseObservable.create(promise); }; ObservableWrapper.toPromise = function(obj) { return toPromise_1.toPromise.call(obj); @@ -14438,7 +13220,7 @@ System.register("angular2/src/facade/async", ["angular2/src/facade/lang", "angul 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) { +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; @@ -14449,197 +13231,225 @@ System.register("angular2/src/core/linker/dynamic_component_loader", ["angular2/ 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", { + 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 this.location.parentView; + return lang_1.isPresent(this._viewBindings) && this._viewBindings.length > 0 ? this._viewBindings : this._viewProviders; }, enumerable: true, configurable: true }); - Object.defineProperty(ComponentRef.prototype, "hostComponent", { + Object.defineProperty(ComponentMetadata.prototype, "viewBindings", { get: function() { - return this.instance; + return this.viewProviders; }, enumerable: true, configurable: true }); - return ComponentRef; - })(); - exports.ComponentRef = ComponentRef; - var ComponentRef_ = (function(_super) { - __extends(ComponentRef_, _super); - function ComponentRef_(location, instance, componentType, injector, _dispose) { + 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._dispose = _dispose; - this.location = location; - this.instance = instance; - this.componentType = componentType; - this.injector = injector; + this.name = name; + this._pure = pure; } - Object.defineProperty(ComponentRef_.prototype, "hostComponentType", { + Object.defineProperty(PipeMetadata.prototype, "pure", { get: function() { - return this.componentType; + return lang_1.isPresent(this._pure) ? this._pure : true; }, enumerable: true, configurable: true }); - ComponentRef_.prototype.dispose = function() { - this._dispose(); - }; - return ComponentRef_; - })(ComponentRef); - exports.ComponentRef_ = ComponentRef_; - var DynamicComponentLoader = (function() { - function DynamicComponentLoader() {} - return DynamicComponentLoader; + 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.DynamicComponentLoader = DynamicComponentLoader; - var DynamicComponentLoader_ = (function(_super) { - __extends(DynamicComponentLoader_, _super); - function DynamicComponentLoader_(_compiler, _viewManager) { - _super.call(this); - this._compiler = _compiler; - this._viewManager = _viewManager; + exports.InputMetadata = InputMetadata; + var OutputMetadata = (function() { + function OutputMetadata(bindingPropertyName) { + this.bindingPropertyName = bindingPropertyName; } - 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; + 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/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) { +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; @@ -14652,410 +13462,973 @@ System.register("angular2/src/core/application_ref", ["angular2/src/core/zone/ng } 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 __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); + }); + }; + return this.manager.getZone().runOutsideAngular(function() { + return dom_adapter_1.DOM.onAndCancel(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/core/zone/ng_zone", ["angular2/src/facade/async", "angular2/src/core/zone/ng_zone_impl", "angular2/src/facade/exceptions", "angular2/src/core/zone/ng_zone_impl"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; 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 ng_zone_impl_1 = require("angular2/src/core/zone/ng_zone_impl"); 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)); + var ng_zone_impl_2 = require("angular2/src/core/zone/ng_zone_impl"); + exports.NgZoneError = ng_zone_impl_2.NgZoneError; + var NgZone = (function() { + function NgZone(_a) { + var _this = this; + var _b = _a.enableLongStackTrace, + enableLongStackTrace = _b === void 0 ? false : _b; + this._hasPendingMicrotasks = false; + this._hasPendingMacrotasks = false; + this._isStable = true; + this._nesting = 0; + this._onUnstable = new async_1.EventEmitter(false); + this._onMicrotaskEmpty = new async_1.EventEmitter(false); + this._onStable = new async_1.EventEmitter(false); + this._onErrorEvents = new async_1.EventEmitter(false); + this._zoneImpl = new ng_zone_impl_1.NgZoneImpl({ + trace: enableLongStackTrace, + onEnter: function() { + _this._nesting++; + if (_this._isStable) { + _this._isStable = false; + _this._onUnstable.emit(null); } - 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(); + }, + onLeave: function() { + _this._nesting--; + _this._checkStable(); + }, + setMicrotask: function(hasMicrotasks) { + _this._hasPendingMicrotasks = hasMicrotasks; + _this._checkStable(); + }, + setMacrotask: function(hasMacrotasks) { + _this._hasPendingMacrotasks = hasMacrotasks; + }, + onError: function(error) { + return _this._onErrorEvents.emit(error); + } }); - } - var PlatformRef = (function() { - function PlatformRef() {} - Object.defineProperty(PlatformRef.prototype, "injector", { + } + NgZone.isInAngularZone = function() { + return ng_zone_impl_1.NgZoneImpl.isInAngularZone(); + }; + NgZone.assertInAngularZone = function() { + if (!ng_zone_impl_1.NgZoneImpl.isInAngularZone()) { + throw new exceptions_1.BaseException('Expected to be in Angular Zone, but it is not!'); + } + }; + NgZone.assertNotInAngularZone = function() { + if (ng_zone_impl_1.NgZoneImpl.isInAngularZone()) { + throw new exceptions_1.BaseException('Expected to not be in Angular Zone, but it is!'); + } + }; + NgZone.prototype._checkStable = function() { + var _this = this; + if (this._nesting == 0) { + if (!this._hasPendingMicrotasks && !this._isStable) { + try { + this._nesting++; + this._onMicrotaskEmpty.emit(null); + } finally { + this._nesting--; + if (!this._hasPendingMicrotasks) { + try { + this.runOutsideAngular(function() { + return _this._onStable.emit(null); + }); + } finally { + this._isStable = true; + } + } + } + } + } + }; + ; + Object.defineProperty(NgZone.prototype, "onUnstable", { get: function() { - return exceptions_1.unimplemented(); + return this._onUnstable; }, 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", { + Object.defineProperty(NgZone.prototype, "onMicrotaskEmpty", { get: function() { - return this._injector; + return this._onMicrotaskEmpty; }, 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", { + Object.defineProperty(NgZone.prototype, "onStable", { get: function() { - return exceptions_1.unimplemented(); + return this._onStable; }, enumerable: true, configurable: true }); - ; - Object.defineProperty(ApplicationRef.prototype, "zone", { + Object.defineProperty(NgZone.prototype, "onError", { get: function() { - return exceptions_1.unimplemented(); + return this._onErrorEvents; }, enumerable: true, configurable: true }); - ; - Object.defineProperty(ApplicationRef.prototype, "componentTypes", { + Object.defineProperty(NgZone.prototype, "hasPendingMicrotasks", { get: function() { - return exceptions_1.unimplemented(); + return this._hasPendingMicrotasks; }, enumerable: true, configurable: true }); - ; - return ApplicationRef; + Object.defineProperty(NgZone.prototype, "hasPendingMacrotasks", { + get: function() { + return this._hasPendingMacrotasks; + }, + enumerable: true, + configurable: true + }); + NgZone.prototype.run = function(fn) { + return this._zoneImpl.runInner(fn); + }; + NgZone.prototype.runOutsideAngular = function(fn) { + return this._zoneImpl.runOuter(fn); + }; + return NgZone; })(); - exports.ApplicationRef = ApplicationRef; - var ApplicationRef_ = (function(_super) { - __extends(ApplicationRef_, _super); - function ApplicationRef_(_platform, _zone, _injector) { + exports.NgZone = NgZone; + 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 = View; + }); + exports.Directive = decorators_1.makeDecorator(directives_2.DirectiveMetadata); + var View = decorators_1.makeDecorator(view_2.ViewMetadata, function(fn) { + return fn.View = 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/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; - _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(); - }); - }); + 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); + return 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/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/platform/dom/events/event_manager", "angular2/src/platform/dom/dom_tokens", "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 event_manager_1 = require("angular2/src/platform/dom/events/event_manager"); + var dom_tokens_1 = require("angular2/src/platform/dom/dom_tokens"); + 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 DomRootRenderer = (function() { + function DomRootRenderer(document, eventManager, sharedStylesHost, animate) { + this.document = document; + this.eventManager = eventManager; + this.sharedStylesHost = sharedStylesHost; + this.animate = animate; + this._registeredComponents = new Map(); + } + DomRootRenderer.prototype.renderComponent = function(componentProto) { + var renderer = this._registeredComponents.get(componentProto.id); + if (lang_1.isBlank(renderer)) { + renderer = new DomRenderer(this, componentProto); + this._registeredComponents.set(componentProto.id, renderer); + } + return renderer; + }; + return DomRootRenderer; + })(); + exports.DomRootRenderer = DomRootRenderer; + var DomRootRenderer_ = (function(_super) { + __extends(DomRootRenderer_, _super); + function DomRootRenderer_(_document, _eventManager, sharedStylesHost, animate) { + _super.call(this, _document, _eventManager, sharedStylesHost, animate); + } + DomRootRenderer_ = __decorate([di_1.Injectable(), __param(0, di_1.Inject(dom_tokens_1.DOCUMENT)), __metadata('design:paramtypes', [Object, event_manager_1.EventManager, shared_styles_host_1.DomSharedStylesHost, animation_builder_1.AnimationBuilder])], DomRootRenderer_); + return DomRootRenderer_; + })(DomRootRenderer); + exports.DomRootRenderer_ = DomRootRenderer_; + var DomRenderer = (function() { + function DomRenderer(_rootRenderer, componentProto) { + this._rootRenderer = _rootRenderer; + this.componentProto = componentProto; + this._styles = _flattenStyles(componentProto.id, componentProto.styles, []); + if (componentProto.encapsulation !== metadata_1.ViewEncapsulation.Native) { + this._rootRenderer.sharedStylesHost.addStyles(this._styles); + } + if (this.componentProto.encapsulation === metadata_1.ViewEncapsulation.Emulated) { + this._contentAttr = _shimContentAttribute(componentProto.id); + this._hostAttr = _shimHostAttribute(componentProto.id); + } else { + this._contentAttr = null; + this._hostAttr = null; + } + } + DomRenderer.prototype.renderComponent = function(componentProto) { + return this._rootRenderer.renderComponent(componentProto); + }; + DomRenderer.prototype.selectRootElement = function(selector) { + var el = dom_adapter_1.DOM.querySelector(this._rootRenderer.document, selector); + if (lang_1.isBlank(el)) { + throw new exceptions_1.BaseException("The selector \"" + selector + "\" did not match any elements"); + } + dom_adapter_1.DOM.clearNodes(el); + return el; + }; + DomRenderer.prototype.createElement = function(parent, name) { + 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]); + if (lang_1.isPresent(this._contentAttr)) { + dom_adapter_1.DOM.setAttribute(el, this._contentAttr, ''); + } + if (lang_1.isPresent(parent)) { + dom_adapter_1.DOM.appendChild(parent, el); + } + return el; + }; + DomRenderer.prototype.createViewRoot = function(hostElement) { + var nodesParent; + if (this.componentProto.encapsulation === metadata_1.ViewEncapsulation.Native) { + nodesParent = dom_adapter_1.DOM.createShadowRoot(hostElement); + this._rootRenderer.sharedStylesHost.addHost(nodesParent); + for (var i = 0; i < this._styles.length; i++) { + dom_adapter_1.DOM.appendChild(nodesParent, dom_adapter_1.DOM.createStyleElement(this._styles[i])); + } + } else { + if (lang_1.isPresent(this._hostAttr)) { + dom_adapter_1.DOM.setAttribute(hostElement, this._hostAttr, ''); + } + nodesParent = hostElement; + } + return nodesParent; + }; + DomRenderer.prototype.createTemplateAnchor = function(parentElement) { + var comment = dom_adapter_1.DOM.createComment(TEMPLATE_COMMENT_TEXT); + if (lang_1.isPresent(parentElement)) { + dom_adapter_1.DOM.appendChild(parentElement, comment); + } + return comment; + }; + DomRenderer.prototype.createText = function(parentElement, value) { + var node = dom_adapter_1.DOM.createTextNode(value); + if (lang_1.isPresent(parentElement)) { + dom_adapter_1.DOM.appendChild(parentElement, node); + } + return node; + }; + DomRenderer.prototype.projectNodes = function(parentElement, nodes) { + if (lang_1.isBlank(parentElement)) + return ; + appendNodes(parentElement, nodes); + }; + DomRenderer.prototype.attachViewAfter = function(node, viewRootNodes) { + moveNodesAfterSibling(node, viewRootNodes); + for (var i = 0; i < viewRootNodes.length; i++) + this.animateNodeEnter(viewRootNodes[i]); + }; + DomRenderer.prototype.detachView = function(viewRootNodes) { + for (var i = 0; i < viewRootNodes.length; i++) { + var node = viewRootNodes[i]; + dom_adapter_1.DOM.remove(node); + this.animateNodeLeave(node); + } + }; + DomRenderer.prototype.destroyView = function(hostElement, viewAllNodes) { + if (this.componentProto.encapsulation === metadata_1.ViewEncapsulation.Native && lang_1.isPresent(hostElement)) { + this._rootRenderer.sharedStylesHost.removeHost(dom_adapter_1.DOM.getShadowRoot(hostElement)); + } + }; + DomRenderer.prototype.listen = function(renderElement, name, callback) { + return this._rootRenderer.eventManager.addEventListener(renderElement, name, decoratePreventDefault(callback)); + }; + DomRenderer.prototype.listenGlobal = function(target, name, callback) { + return this._rootRenderer.eventManager.addGlobalEventListener(target, name, decoratePreventDefault(callback)); + }; + DomRenderer.prototype.setElementProperty = function(renderElement, propertyName, propertyValue) { + dom_adapter_1.DOM.setProperty(renderElement, propertyName, propertyValue); + }; + DomRenderer.prototype.setElementAttribute = function(renderElement, attributeName, attributeValue) { + var attrNs; + var nsAndName = splitNamespace(attributeName); + if (lang_1.isPresent(nsAndName[0])) { + attributeName = nsAndName[0] + ':' + nsAndName[1]; + attrNs = NAMESPACE_URIS[nsAndName[0]]; + } + if (lang_1.isPresent(attributeValue)) { + if (lang_1.isPresent(attrNs)) { + dom_adapter_1.DOM.setAttributeNS(renderElement, attrNs, attributeName, attributeValue); + } else { + dom_adapter_1.DOM.setAttribute(renderElement, attributeName, attributeValue); + } + } else { + if (lang_1.isPresent(attrNs)) { + dom_adapter_1.DOM.removeAttributeNS(renderElement, attrNs, nsAndName[1]); + } else { + dom_adapter_1.DOM.removeAttribute(renderElement, attributeName); + } } - this._enforceNoNewChanges = lang_1.assertionsEnabled(); - } - ApplicationRef_.prototype.registerBootstrapListener = function(listener) { - this._bootstrapListeners.push(listener); }; - ApplicationRef_.prototype.registerDisposeListener = function(dispose) { - this._disposeListeners.push(dispose); + DomRenderer.prototype.setBindingDebugInfo = function(renderElement, propertyName, propertyValue) { + var dashCasedPropertyName = util_1.camelCaseToDashCase(propertyName); + if (dom_adapter_1.DOM.isCommentNode(renderElement)) { + var existingBindings = lang_1.RegExpWrapper.firstMatch(TEMPLATE_BINDINGS_EXP, lang_1.StringWrapper.replaceAll(dom_adapter_1.DOM.getText(renderElement), /\n/g, '')); + var parsedBindings = lang_1.Json.parse(existingBindings[1]); + parsedBindings[dashCasedPropertyName] = propertyValue; + dom_adapter_1.DOM.setText(renderElement, lang_1.StringWrapper.replace(TEMPLATE_COMMENT_TEXT, '{}', lang_1.Json.stringify(parsedBindings))); + } else { + this.setElementAttribute(renderElement, propertyName, propertyValue); + } }; - ApplicationRef_.prototype.registerChangeDetector = function(changeDetector) { - this._changeDetectorRefs.push(changeDetector); + DomRenderer.prototype.setElementDebugInfo = function(renderElement, info) {}; + DomRenderer.prototype.setElementClass = function(renderElement, className, isAdd) { + if (isAdd) { + dom_adapter_1.DOM.addClass(renderElement, className); + } else { + dom_adapter_1.DOM.removeClass(renderElement, className); + } }; - ApplicationRef_.prototype.unregisterChangeDetector = function(changeDetector) { - collection_1.ListWrapper.remove(this._changeDetectorRefs, changeDetector); + DomRenderer.prototype.setElementStyle = function(renderElement, styleName, styleValue) { + if (lang_1.isPresent(styleValue)) { + dom_adapter_1.DOM.setStyle(renderElement, styleName, lang_1.stringify(styleValue)); + } else { + dom_adapter_1.DOM.removeStyle(renderElement, styleName); + } }; - 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); + DomRenderer.prototype.invokeElementMethod = function(renderElement, methodName, args) { + dom_adapter_1.DOM.invoke(renderElement, methodName, args); + }; + DomRenderer.prototype.setText = function(renderNode, text) { + dom_adapter_1.DOM.setText(renderNode, text); + }; + 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._rootRenderer.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._rootRenderer.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); + } + }; + return DomRenderer; + })(); + exports.DomRenderer = DomRenderer; + 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]); } - 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); + } else { + for (var i = 0; i < nodes.length; i++) { + dom_adapter_1.DOM.appendChild(parent, nodes[i]); } - }); - 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 _; - }); + } + } + } + function appendNodes(parent, nodes) { + 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 === false) { + dom_adapter_1.DOM.preventDefault(event); + } }; - 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); - }); + } + 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); + } + function _flattenStyles(compId, styles, target) { + for (var i = 0; i < styles.length; i++) { + var style = styles[i]; + if (lang_1.isArray(style)) { + _flattenStyles(compId, style, target); + } else { + style = lang_1.StringWrapper.replaceAll(style, COMPONENT_REGEX, compId); + target.push(style); + } + } + return target; + } + 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/ng_probe"], 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/ng_probe")); + 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/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); }; - ApplicationRef_.prototype._unloadComponent = function(ref) { - if (!collection_1.ListWrapper.contains(this._rootComponents, ref)) { - return ; + return DateFormatter; + })(); + exports.DateFormatter = DateFormatter; + 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; } - this.unregisterChangeDetector(view_ref_1.internalView(ref.hostView).changeDetector.ref); - collection_1.ListWrapper.remove(this._rootComponents, ref); + return lang_1.Json.stringify(value); }; - 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"); + 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; } - 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); + 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); }; - 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); + SlicePipe.prototype.supports = function(obj) { + return lang_1.isString(obj) || lang_1.isArray(obj); }; - 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_; + 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/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) { +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; - 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 __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"); - 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")); + 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/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) { +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; @@ -15084,362 +14457,99 @@ System.register("angular2/src/platform/dom/dom_renderer", ["angular2/src/core/di 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 intl_1 = require("angular2/src/facade/intl"); 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'); - }); + 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; } - }; - 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); + if (currencyAsSymbol === void 0) { + currencyAsSymbol = false; } - }; - 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]); + if (lang_1.isBlank(value)) + return null; + if (!lang_1.isNumber(value)) { + throw new invalid_pipe_argument_exception_1.InvalidPipeArgumentException(NumberPipe, value); } - 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 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"); } - 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); + if (lang_1.isPresent(parts[1])) { + minInt = lang_1.NumberWrapper.parseIntAutoRadix(parts[1]); } - } - }; - 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]); + if (lang_1.isPresent(parts[3])) { + minFraction = lang_1.NumberWrapper.parseIntAutoRadix(parts[3]); } - } else { - for (var i = 0; i < nodes.length; i++) { - dom_adapter_1.DOM.appendChild(parent, nodes[i]); + if (lang_1.isPresent(parts[5])) { + maxFraction = lang_1.NumberWrapper.parseIntAutoRadix(parts[5]); } } - } - } - function decoratePreventDefault(eventHandler) { - return function(event) { - var allowDefaultBehavior = eventHandler(event); - if (!allowDefaultBehavior) { - dom_adapter_1.DOM.preventDefault(event); - } + return intl_1.NumberFormatter.format(value, defaultLocale, style, { + minimumIntegerDigits: minInt, + minimumFractionDigits: minFraction, + maximumFractionDigits: maxFraction, + currency: currency, + currencyAsSymbol: currencyAsSymbol + }); }; - } - var NS_PREFIX_RE = /^@([^:]+):(.+)/g; - function splitNamespace(name) { - if (name[0] != '@') { - return [null, name]; + 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); } - 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; + 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); } - 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) + "'"); + 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); } - return InvalidPipeArgumentException; - })(exceptions_1.BaseException); - exports.InvalidPipeArgumentException = InvalidPipeArgumentException; + 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; }); @@ -15488,7 +14598,7 @@ System.register("angular2/src/common/pipes/uppercase_pipe", ["angular2/src/facad 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) { +System.register("angular2/src/common/pipes/replace_pipe", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "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; @@ -15509,71 +14619,57 @@ System.register("angular2/src/common/pipes/lowercase_pipe", ["angular2/src/facad return Reflect.metadata(k, v); }; var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); 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; + var ReplacePipe = (function() { + function ReplacePipe() {} + ReplacePipe.prototype.transform = function(value, args) { + if (lang_1.isBlank(args) || args.length !== 2) { + throw new exceptions_1.BaseException('ReplacePipe requires two arguments'); } - if (lang_1.isBlank(value)) + 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; + if (!this._supportedInput(value)) { + throw new invalid_pipe_argument_exception_1.InvalidPipeArgumentException(ReplacePipe, value); } - return lang_1.Json.stringify(value); + var input = value.toString(); + var pattern = args[0]; + var replacement = args[1]; + if (!this._supportedPattern(pattern)) { + throw new invalid_pipe_argument_exception_1.InvalidPipeArgumentException(ReplacePipe, pattern); + } + if (!this._supportedReplacement(replacement)) { + throw new invalid_pipe_argument_exception_1.InvalidPipeArgumentException(ReplacePipe, replacement); + } + if (lang_1.isFunction(replacement)) { + var rgxPattern = lang_1.isString(pattern) ? lang_1.RegExpWrapper.create(pattern) : pattern; + return lang_1.StringWrapper.replaceAllMapped(input, rgxPattern, replacement); + } + if (pattern instanceof RegExp) { + return lang_1.StringWrapper.replaceAll(input, pattern, replacement); + } + return lang_1.StringWrapper.replace(input, pattern, replacement); }; - JsonPipe = __decorate([lang_1.CONST(), core_1.Pipe({ - name: 'json', - pure: false - }), core_1.Injectable(), __metadata('design:paramtypes', [])], JsonPipe); - return JsonPipe; + ReplacePipe.prototype._supportedInput = function(input) { + return lang_1.isString(input) || lang_1.isNumber(input); + }; + ReplacePipe.prototype._supportedPattern = function(pattern) { + return lang_1.isString(pattern) || pattern instanceof RegExp; + }; + ReplacePipe.prototype._supportedReplacement = function(replacement) { + return lang_1.isString(replacement) || lang_1.isFunction(replacement); + }; + ReplacePipe = __decorate([core_1.Pipe({name: 'replace'}), core_1.Injectable(), __metadata('design:paramtypes', [])], ReplacePipe); + return ReplacePipe; })(); - exports.JsonPipe = JsonPipe; + exports.ReplacePipe = ReplacePipe; 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) { +System.register("angular2/src/common/pipes/i18n_plural_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; @@ -15594,177 +14690,40 @@ System.register("angular2/src/common/pipes/slice_pipe", ["angular2/src/facade/la 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) { + var interpolationExp = lang_1.RegExpWrapper.create('#'); + var I18nPluralPipe = (function() { + function I18nPluralPipe() {} + I18nPluralPipe.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 key; + var valueStr; + var pluralMap = (args[0]); + if (!lang_1.isStringMap(pluralMap)) { + throw new invalid_pipe_argument_exception_1.InvalidPipeArgumentException(I18nPluralPipe, pluralMap); } - var formatter = new Intl.DateTimeFormat(locale, extractComponents(pattern)); - dateFormatterCache.set(key, formatter); - return formatter.format(date); + key = value === 0 || value === 1 ? "=" + value : 'other'; + valueStr = lang_1.isPresent(value) ? value.toString() : ''; + return lang_1.StringWrapper.replaceAll(pluralMap[key], interpolationExp, valueStr); }; - return DateFormatter; + I18nPluralPipe = __decorate([lang_1.CONST(), core_1.Pipe({ + name: 'i18nPlural', + pure: true + }), core_1.Injectable(), __metadata('design:paramtypes', [])], I18nPluralPipe); + return I18nPluralPipe; })(); - exports.DateFormatter = DateFormatter; + exports.I18nPluralPipe = I18nPluralPipe; 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) { +System.register("angular2/src/common/pipes/i18n_select_pipe", ["angular2/src/facade/lang", "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 __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, @@ -15773,107 +14732,57 @@ System.register("angular2/src/common/pipes/number_pipe", ["angular2/src/facade/l 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); + 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 core_1 = require("angular2/core"); + var invalid_pipe_argument_exception_1 = require("angular2/src/common/pipes/invalid_pipe_argument_exception"); + var I18nSelectPipe = (function() { + function I18nSelectPipe() {} + I18nSelectPipe.prototype.transform = function(value, args) { + if (args === void 0) { + args = null; } - 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]); - } + var mapping = (args[0]); + if (!lang_1.isStringMap(mapping)) { + throw new invalid_pipe_argument_exception_1.InvalidPipeArgumentException(I18nSelectPipe, mapping); } - return intl_1.NumberFormatter.format(value, defaultLocale, style, { - minimumIntegerDigits: minInt, - minimumFractionDigits: minFraction, - maximumFractionDigits: maxFraction, - currency: currency, - currencyAsSymbol: currencyAsSymbol - }); + return collection_1.StringMapWrapper.contains(mapping, value) ? mapping[value] : mapping['other']; }; - NumberPipe = __decorate([lang_1.CONST(), core_1.Injectable(), __metadata('design:paramtypes', [])], NumberPipe); - return NumberPipe; + I18nSelectPipe = __decorate([lang_1.CONST(), core_1.Pipe({ + name: 'i18nSelect', + pure: true + }), core_1.Injectable(), __metadata('design:paramtypes', [])], I18nSelectPipe); + return I18nSelectPipe; })(); - 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; + exports.I18nSelectPipe = I18nSelectPipe; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/common/pipes/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/common/pipes/replace_pipe", "angular2/src/common/pipes/i18n_plural_pipe", "angular2/src/common/pipes/i18n_select_pipe", "angular2/src/facade/lang"], 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 replace_pipe_1 = require("angular2/src/common/pipes/replace_pipe"); + var i18n_plural_pipe_1 = require("angular2/src/common/pipes/i18n_plural_pipe"); + var i18n_select_pipe_1 = require("angular2/src/common/pipes/i18n_select_pipe"); + var lang_1 = require("angular2/src/facade/lang"); + 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, replace_pipe_1.ReplacePipe, i18n_plural_pipe_1.I18nPluralPipe, i18n_select_pipe_1.I18nSelectPipe]); global.define = __define; return module.exports; }); @@ -15926,30 +14835,30 @@ System.register("angular2/src/common/directives/ng_class", ["angular2/src/facade v = v.split(' '); } this._rawClass = v; + this._iterableDiffer = null; + this._keyValueDiffer = null; if (lang_1.isPresent(v)) { if (collection_1.isListLikeIterable(v)) { - this._differ = this._iterableDiffers.find(v).create(null); - this._mode = 'iterable'; + this._iterableDiffer = this._iterableDiffers.find(v).create(null); } else { - this._differ = this._keyValueDiffers.find(v).create(null); - this._mode = 'keyValue'; + this._keyValueDiffer = this._keyValueDiffers.find(v).create(null); } - } 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(this._iterableDiffer)) { + var changes = this._iterableDiffer.diff(this._rawClass); if (lang_1.isPresent(changes)) { - if (this._mode == 'iterable') { - this._applyIterableChanges(changes); - } else { - this._applyKeyValueChanges(changes); - } + this._applyIterableChanges(changes); + } + } + if (lang_1.isPresent(this._keyValueDiffer)) { + var changes = this._keyValueDiffer.diff(this._rawClass); + if (lang_1.isPresent(changes)) { + this._applyKeyValueChanges(changes); } } }; @@ -16002,7 +14911,7 @@ System.register("angular2/src/common/directives/ng_class", ["angular2/src/facade }); } else { collection_1.StringMapWrapper.forEach(rawClassVal, function(expVal, className) { - if (expVal) + if (lang_1.isPresent(expVal)) _this._toggleClass(className, !isCleanup); }); } @@ -16015,10 +14924,10 @@ System.register("angular2/src/common/directives/ng_class", ["angular2/src/facade var classes = className.split(/\s+/g); for (var i = 0, len = classes.length; i < len; i++) { - this._renderer.setElementClass(this._ngEl, classes[i], enabled); + this._renderer.setElementClass(this._ngEl.nativeElement, classes[i], enabled); } } else { - this._renderer.setElementClass(this._ngEl, className, enabled); + this._renderer.setElementClass(this._ngEl.nativeElement, className, enabled); } } }; @@ -16033,7 +14942,7 @@ System.register("angular2/src/common/directives/ng_class", ["angular2/src/facade return module.exports; }); -System.register("angular2/src/common/directives/ng_for", ["angular2/core", "angular2/src/facade/lang"], true, function(require, exports, module) { +System.register("angular2/src/common/directives/ng_for", ["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; @@ -16055,6 +14964,7 @@ System.register("angular2/src/common/directives/ng_for", ["angular2/core", "angu }; var core_1 = require("angular2/core"); var lang_1 = require("angular2/src/facade/lang"); + var exceptions_1 = require("angular2/src/facade/exceptions"); var NgFor = (function() { function NgFor(_viewContainer, _templateRef, _iterableDiffers, _cdr) { this._viewContainer = _viewContainer; @@ -16066,7 +14976,11 @@ System.register("angular2/src/common/directives/ng_for", ["angular2/core", "angu 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); + try { + this._differ = this._iterableDiffers.find(value).create(this._cdr, this._ngForTrackBy); + } catch (e) { + throw new exceptions_1.BaseException("Cannot find a differ supporting object '" + value + "' of type '" + lang_1.getTypeNameForDebugging(value) + "'. NgFor only supports binding to Iterables such as Arrays."); + } } }, enumerable: true, @@ -16081,6 +14995,13 @@ System.register("angular2/src/common/directives/ng_for", ["angular2/core", "angu enumerable: true, configurable: true }); + Object.defineProperty(NgFor.prototype, "ngForTrackBy", { + set: function(value) { + this._ngForTrackBy = value; + }, + enumerable: true, + configurable: true + }); NgFor.prototype.ngDoCheck = function() { if (lang_1.isPresent(this._differ)) { var changes = this._differ.diff(this._ngForOf); @@ -16089,6 +15010,7 @@ System.register("angular2/src/common/directives/ng_for", ["angular2/core", "angu } }; NgFor.prototype._applyChanges = function(changes) { + var _this = this; var recordViewTuples = []; changes.forEachRemovedItem(function(removedRecord) { return recordViewTuples.push(new RecordViewTuple(removedRecord, null)); @@ -16106,8 +15028,13 @@ System.register("angular2/src/common/directives/ng_for", ["angular2/core", "angu } for (var i = 0, ilen = this._viewContainer.length; i < ilen; i++) { - this._viewContainer.get(i).setLocal('last', i === ilen - 1); + var viewRef = this._viewContainer.get(i); + viewRef.setLocal('last', i === ilen - 1); } + changes.forEachIdentityChange(function(record) { + var viewRef = _this._viewContainer.get(record.currentIndex); + viewRef.setLocal('\$implicit', record.item); + }); }; NgFor.prototype._perViewChange = function(view, record) { view.setLocal('\$implicit', record.item); @@ -16147,7 +15074,7 @@ System.register("angular2/src/common/directives/ng_for", ["angular2/core", "angu }; NgFor = __decorate([core_1.Directive({ selector: '[ngFor][ngForOf]', - inputs: ['ngForOf', 'ngForTemplate'] + inputs: ['ngForTrackBy', 'ngForOf', 'ngForTemplate'] }), __metadata('design:paramtypes', [core_1.ViewContainerRef, core_1.TemplateRef, core_1.IterableDiffers, core_1.ChangeDetectorRef])], NgFor); return NgFor; })(); @@ -16274,7 +15201,7 @@ System.register("angular2/src/common/directives/ng_style", ["angular2/core", "an }); }; NgStyle.prototype._setStyle = function(name, val) { - this._renderer.setElementStyle(this._ngEl, name, val); + this._renderer.setElementStyle(this._ngEl.nativeElement, name, val); }; NgStyle = __decorate([core_1.Directive({ selector: '[ngStyle]', @@ -16329,6 +15256,7 @@ System.register("angular2/src/common/directives/ng_switch", ["angular2/core", "a }; return SwitchView; })(); + exports.SwitchView = SwitchView; var NgSwitch = (function() { function NgSwitch() { this._useDefault = false; @@ -16442,6 +15370,112 @@ System.register("angular2/src/common/directives/ng_switch", ["angular2/core", "a return module.exports; }); +System.register("angular2/src/common/directives/ng_plural", ["angular2/core", "angular2/src/facade/lang", "angular2/src/facade/collection", "angular2/src/common/directives/ng_switch"], 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 ng_switch_1 = require("angular2/src/common/directives/ng_switch"); + var _CATEGORY_DEFAULT = 'other'; + var NgLocalization = (function() { + function NgLocalization() {} + return NgLocalization; + })(); + exports.NgLocalization = NgLocalization; + var NgPluralCase = (function() { + function NgPluralCase(value, template, viewContainer) { + this.value = value; + this._view = new ng_switch_1.SwitchView(viewContainer, template); + } + NgPluralCase = __decorate([core_1.Directive({selector: '[ngPluralCase]'}), __param(0, core_1.Attribute('ngPluralCase')), __metadata('design:paramtypes', [String, core_1.TemplateRef, core_1.ViewContainerRef])], NgPluralCase); + return NgPluralCase; + })(); + exports.NgPluralCase = NgPluralCase; + var NgPlural = (function() { + function NgPlural(_localization) { + this._localization = _localization; + this._caseViews = new collection_1.Map(); + this.cases = null; + } + Object.defineProperty(NgPlural.prototype, "ngPlural", { + set: function(value) { + this._switchValue = value; + this._updateView(); + }, + enumerable: true, + configurable: true + }); + NgPlural.prototype.ngAfterContentInit = function() { + var _this = this; + this.cases.forEach(function(pluralCase) { + _this._caseViews.set(_this._formatValue(pluralCase), pluralCase._view); + }); + this._updateView(); + }; + NgPlural.prototype._updateView = function() { + this._clearViews(); + var view = this._caseViews.get(this._switchValue); + if (!lang_1.isPresent(view)) + view = this._getCategoryView(this._switchValue); + this._activateView(view); + }; + NgPlural.prototype._clearViews = function() { + if (lang_1.isPresent(this._activeView)) + this._activeView.destroy(); + }; + NgPlural.prototype._activateView = function(view) { + if (!lang_1.isPresent(view)) + return ; + this._activeView = view; + this._activeView.create(); + }; + NgPlural.prototype._getCategoryView = function(value) { + var category = this._localization.getPluralCategory(value); + var categoryView = this._caseViews.get(category); + return lang_1.isPresent(categoryView) ? categoryView : this._caseViews.get(_CATEGORY_DEFAULT); + }; + NgPlural.prototype._isValueView = function(pluralCase) { + return pluralCase.value[0] === "="; + }; + NgPlural.prototype._formatValue = function(pluralCase) { + return this._isValueView(pluralCase) ? this._stripValue(pluralCase.value) : pluralCase.value; + }; + NgPlural.prototype._stripValue = function(value) { + return lang_1.NumberWrapper.parseInt(value.substring(1), 10); + }; + __decorate([core_1.ContentChildren(NgPluralCase), __metadata('design:type', core_1.QueryList)], NgPlural.prototype, "cases", void 0); + __decorate([core_1.Input(), __metadata('design:type', Number), __metadata('design:paramtypes', [Number])], NgPlural.prototype, "ngPlural", null); + NgPlural = __decorate([core_1.Directive({selector: '[ngPlural]'}), __metadata('design:paramtypes', [NgLocalization])], NgPlural); + return NgPlural; + })(); + exports.NgPlural = NgPlural; + 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; @@ -16450,7 +15484,7 @@ System.register("angular2/src/common/directives/observable_list_diff", [], true, 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) { +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", "angular2/src/common/directives/ng_plural"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -16460,7 +15494,8 @@ System.register("angular2/src/common/directives/core_directives", ["angular2/src 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]); + var ng_plural_1 = require("angular2/src/common/directives/ng_plural"); + 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, ng_plural_1.NgPlural, ng_plural_1.NgPluralCase]); global.define = __define; return module.exports; }); @@ -16691,6 +15726,17 @@ System.register("angular2/src/common/forms/model", ["angular2/src/facade/lang", } return lang_1.isPresent(this.getError(errorCode, path)); }; + Object.defineProperty(AbstractControl.prototype, "root", { + get: function() { + var x = this; + while (lang_1.isPresent(x._parent)) { + x = x._parent; + } + return x; + }, + enumerable: true, + configurable: true + }); AbstractControl.prototype._updateControlsErrors = function() { this._status = this._calculateStatus(); if (lang_1.isPresent(this._parent)) { @@ -17089,7 +16135,7 @@ System.register("angular2/src/common/forms/validators", ["angular2/src/facade/la var Validators = (function() { function Validators() {} Validators.required = function(control) { - return lang_1.isBlank(control.value) || control.value == "" ? {"required": true} : null; + return lang_1.isBlank(control.value) || (lang_1.isString(control.value) && control.value == "") ? {"required": true} : null; }; Validators.minLength = function(minLength) { return function(control) { @@ -17113,6 +16159,18 @@ System.register("angular2/src/common/forms/validators", ["angular2/src/facade/la }} : null; }; }; + Validators.pattern = function(pattern) { + return function(control) { + if (lang_1.isPresent(Validators.required(control))) + return null; + var regex = new RegExp("^" + pattern + "$"); + var v = control.value; + return regex.test(v) ? null : {"pattern": { + "requiredPattern": "^" + pattern + "$", + "actualValue": v + }}; + }; + }; Validators.nullValidator = function(c) { return null; }; @@ -17133,7 +16191,7 @@ System.register("angular2/src/common/forms/validators", ["angular2/src/facade/la if (presentValidators.length == 0) return null; return function(control) { - var promises = _executeValidators(control, presentValidators).map(_convertToPromise); + var promises = _executeAsyncValidators(control, presentValidators).map(_convertToPromise); return promise_1.PromiseWrapper.all(promises).then(_mergeErrors); }; }; @@ -17148,6 +16206,11 @@ System.register("angular2/src/common/forms/validators", ["angular2/src/facade/la return v(control); }); } + function _executeAsyncValidators(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; @@ -17196,7 +16259,7 @@ System.register("angular2/src/common/forms/directives/default_value_accessor", [ } DefaultValueAccessor.prototype.writeValue = function(value) { var normalizedValue = lang_1.isBlank(value) ? '' : value; - this._renderer.setElementProperty(this._elementRef, 'value', normalizedValue); + this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', normalizedValue); }; DefaultValueAccessor.prototype.registerOnChange = function(fn) { this.onChange = fn; @@ -17256,7 +16319,7 @@ System.register("angular2/src/common/forms/directives/number_value_accessor", [" this.onTouched = function() {}; } NumberValueAccessor.prototype.writeValue = function(value) { - this._renderer.setElementProperty(this._elementRef, 'value', value); + this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', value); }; NumberValueAccessor.prototype.registerOnChange = function(fn) { this.onChange = function(value) { @@ -17319,7 +16382,7 @@ System.register("angular2/src/common/forms/directives/checkbox_value_accessor", this.onTouched = function() {}; } CheckboxControlValueAccessor.prototype.writeValue = function(value) { - this._renderer.setElementProperty(this._elementRef, 'checked', value); + this._renderer.setElementProperty(this._elementRef.nativeElement, 'checked', value); }; CheckboxControlValueAccessor.prototype.registerOnChange = function(fn) { this.onChange = fn; @@ -17327,22 +16390,165 @@ System.register("angular2/src/common/forms/directives/checkbox_value_accessor", 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]', + 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()' + }, + providers: [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/common/forms/directives/control_value_accessor", "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 control_value_accessor_1 = require("angular2/src/common/forms/directives/control_value_accessor"); + var lang_1 = require("angular2/src/facade/lang"); + var collection_1 = require("angular2/src/facade/collection"); + 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 + })); + function _buildValueString(id, value) { + if (lang_1.isBlank(id)) + return "" + value; + if (!lang_1.isPrimitive(value)) + value = "Object"; + return lang_1.StringWrapper.slice(id + ": " + value, 0, 50); + } + function _extractId(valueString) { + return valueString.split(":")[0]; + } + var SelectControlValueAccessor = (function() { + function SelectControlValueAccessor(_renderer, _elementRef) { + this._renderer = _renderer; + this._elementRef = _elementRef; + this._optionMap = new Map(); + this._idCounter = 0; + this.onChange = function(_) {}; + this.onTouched = function() {}; + } + SelectControlValueAccessor.prototype.writeValue = function(value) { + this.value = value; + var valueString = _buildValueString(this._getOptionId(value), value); + this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', valueString); + }; + SelectControlValueAccessor.prototype.registerOnChange = function(fn) { + var _this = this; + this.onChange = function(valueString) { + fn(_this._getOptionValue(valueString)); + }; + }; + SelectControlValueAccessor.prototype.registerOnTouched = function(fn) { + this.onTouched = fn; + }; + SelectControlValueAccessor.prototype._registerOption = function() { + return (this._idCounter++).toString(); + }; + SelectControlValueAccessor.prototype._getOptionId = function(value) { + for (var _i = 0, + _a = collection_1.MapWrapper.keys(this._optionMap); _i < _a.length; _i++) { + var id = _a[_i]; + if (lang_1.looseIdentical(this._optionMap.get(id), value)) + return id; + } + return null; + }; + SelectControlValueAccessor.prototype._getOptionValue = function(valueString) { + var value = this._optionMap.get(_extractId(valueString)); + return lang_1.isPresent(value) ? value : valueString; + }; + SelectControlValueAccessor = __decorate([core_1.Directive({ + selector: 'select[ngControl],select[ngFormControl],select[ngModel]', host: { - '(change)': 'onChange($event.target.checked)', + '(input)': 'onChange($event.target.value)', '(blur)': 'onTouched()' }, - bindings: [CHECKBOX_VALUE_ACCESSOR] - }), __metadata('design:paramtypes', [core_1.Renderer, core_1.ElementRef])], CheckboxControlValueAccessor); - return CheckboxControlValueAccessor; + providers: [SELECT_VALUE_ACCESSOR] + }), __metadata('design:paramtypes', [core_1.Renderer, core_1.ElementRef])], SelectControlValueAccessor); + return SelectControlValueAccessor; })(); - exports.CheckboxControlValueAccessor = CheckboxControlValueAccessor; + exports.SelectControlValueAccessor = SelectControlValueAccessor; + var NgSelectOption = (function() { + function NgSelectOption(_element, _renderer, _select) { + this._element = _element; + this._renderer = _renderer; + this._select = _select; + if (lang_1.isPresent(this._select)) + this.id = this._select._registerOption(); + } + Object.defineProperty(NgSelectOption.prototype, "ngValue", { + set: function(value) { + if (this._select == null) + return ; + this._select._optionMap.set(this.id, value); + this._setElementValue(_buildValueString(this.id, value)); + this._select.writeValue(this._select.value); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NgSelectOption.prototype, "value", { + set: function(value) { + if (this._select == null) + return ; + this._setElementValue(value); + this._select.writeValue(this._select.value); + }, + enumerable: true, + configurable: true + }); + NgSelectOption.prototype._setElementValue = function(value) { + this._renderer.setElementProperty(this._element.nativeElement, 'value', value); + }; + NgSelectOption.prototype.ngOnDestroy = function() { + if (lang_1.isPresent(this._select)) { + this._select._optionMap.delete(this.id); + this._select.writeValue(this._select.value); + } + }; + __decorate([core_1.Input('ngValue'), __metadata('design:type', Object), __metadata('design:paramtypes', [Object])], NgSelectOption.prototype, "ngValue", null); + __decorate([core_1.Input('value'), __metadata('design:type', Object), __metadata('design:paramtypes', [Object])], NgSelectOption.prototype, "value", null); + NgSelectOption = __decorate([core_1.Directive({selector: 'option'}), __param(2, core_1.Optional()), __param(2, core_1.Host()), __metadata('design:paramtypes', [core_1.ElementRef, core_1.Renderer, SelectControlValueAccessor])], NgSelectOption); + return NgSelectOption; + })(); + exports.NgSelectOption = NgSelectOption; 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) { +System.register("angular2/src/common/forms/directives/radio_control_value_accessor", ["angular2/core", "angular2/src/common/forms/directives/control_value_accessor", "angular2/src/common/forms/directives/ng_control", "angular2/src/facade/lang", "angular2/src/facade/collection"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -17362,63 +16568,100 @@ System.register("angular2/src/common/forms/directives/select_control_value_acces 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 ng_control_1 = require("angular2/src/common/forms/directives/ng_control"); 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, { + var collection_1 = require("angular2/src/facade/collection"); + var RADIO_VALUE_ACCESSOR = lang_1.CONST_EXPR(new core_1.Provider(control_value_accessor_1.NG_VALUE_ACCESSOR, { useExisting: core_1.forwardRef(function() { - return SelectControlValueAccessor; + return RadioControlValueAccessor; }), multi: true })); - var NgSelectOption = (function() { - function NgSelectOption() {} - NgSelectOption = __decorate([core_1.Directive({selector: 'option'}), __metadata('design:paramtypes', [])], NgSelectOption); - return NgSelectOption; + var RadioControlRegistry = (function() { + function RadioControlRegistry() { + this._accessors = []; + } + RadioControlRegistry.prototype.add = function(control, accessor) { + this._accessors.push([control, accessor]); + }; + RadioControlRegistry.prototype.remove = function(accessor) { + var indexToRemove = -1; + for (var i = 0; i < this._accessors.length; ++i) { + if (this._accessors[i][1] === accessor) { + indexToRemove = i; + } + } + collection_1.ListWrapper.removeAt(this._accessors, indexToRemove); + }; + RadioControlRegistry.prototype.select = function(accessor) { + this._accessors.forEach(function(c) { + if (c[0].control.root === accessor._control.control.root && c[1] !== accessor) { + c[1].fireUncheck(); + } + }); + }; + RadioControlRegistry = __decorate([core_1.Injectable(), __metadata('design:paramtypes', [])], RadioControlRegistry); + return RadioControlRegistry; })(); - exports.NgSelectOption = NgSelectOption; - var SelectControlValueAccessor = (function() { - function SelectControlValueAccessor(_renderer, _elementRef, query) { + exports.RadioControlRegistry = RadioControlRegistry; + var RadioButtonState = (function() { + function RadioButtonState(checked, value) { + this.checked = checked; + this.value = value; + } + return RadioButtonState; + })(); + exports.RadioButtonState = RadioButtonState; + var RadioControlValueAccessor = (function() { + function RadioControlValueAccessor(_renderer, _elementRef, _registry, _injector) { this._renderer = _renderer; this._elementRef = _elementRef; - this.onChange = function(_) {}; + this._registry = _registry; + this._injector = _injector; + this.onChange = function() {}; this.onTouched = function() {}; - this._updateValueWhenListOfOptionsChanges(query); } - SelectControlValueAccessor.prototype.writeValue = function(value) { - this.value = value; - this._renderer.setElementProperty(this._elementRef, 'value', value); + RadioControlValueAccessor.prototype.ngOnInit = function() { + this._control = this._injector.get(ng_control_1.NgControl); + this._registry.add(this._control, this); }; - SelectControlValueAccessor.prototype.registerOnChange = function(fn) { - this.onChange = fn; + RadioControlValueAccessor.prototype.ngOnDestroy = function() { + this._registry.remove(this); }; - SelectControlValueAccessor.prototype.registerOnTouched = function(fn) { - this.onTouched = fn; + RadioControlValueAccessor.prototype.writeValue = function(value) { + this._state = value; + if (lang_1.isPresent(value) && value.checked) { + this._renderer.setElementProperty(this._elementRef.nativeElement, 'checked', true); + } }; - SelectControlValueAccessor.prototype._updateValueWhenListOfOptionsChanges = function(query) { + RadioControlValueAccessor.prototype.registerOnChange = function(fn) { var _this = this; - async_1.ObservableWrapper.subscribe(query.changes, function(_) { - return _this.writeValue(_this.value); - }); + this._fn = fn; + this.onChange = function() { + fn(new RadioButtonState(true, _this._state.value)); + _this._registry.select(_this); + }; }; - SelectControlValueAccessor = __decorate([core_1.Directive({ - selector: 'select[ngControl],select[ngFormControl],select[ngModel]', + RadioControlValueAccessor.prototype.fireUncheck = function() { + this._fn(new RadioButtonState(false, this._state.value)); + }; + RadioControlValueAccessor.prototype.registerOnTouched = function(fn) { + this.onTouched = fn; + }; + __decorate([core_1.Input(), __metadata('design:type', String)], RadioControlValueAccessor.prototype, "name", void 0); + RadioControlValueAccessor = __decorate([core_1.Directive({ + selector: 'input[type=radio][ngControl],input[type=radio][ngFormControl],input[type=radio][ngModel]', host: { - '(change)': 'onChange($event.target.value)', - '(input)': 'onChange($event.target.value)', + '(change)': 'onChange()', '(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; + providers: [RADIO_VALUE_ACCESSOR] + }), __metadata('design:paramtypes', [core_1.Renderer, core_1.ElementRef, RadioControlRegistry, core_1.Injector])], RadioControlValueAccessor); + return RadioControlValueAccessor; })(); - exports.SelectControlValueAccessor = SelectControlValueAccessor; + exports.RadioControlValueAccessor = RadioControlValueAccessor; global.define = __define; return module.exports; }); @@ -17437,6 +16680,16 @@ System.register("angular2/src/common/forms/directives/normalize_validator", [], } } exports.normalizeValidator = normalizeValidator; + function normalizeAsyncValidator(validator) { + if (validator.validate !== undefined) { + return function(c) { + return Promise.resolve(validator.validate(c)); + }; + } else { + return validator; + } + } + exports.normalizeAsyncValidator = normalizeAsyncValidator; global.define = __define; return module.exports; }); @@ -18149,18 +17402,232 @@ System.register("angular2/src/common/forms/directives/ng_control_status", ["angu '[class.ng-valid]': 'ngClassValid', '[class.ng-invalid]': 'ngClassInvalid' } - }), __param(0, core_1.Self()), __metadata('design:paramtypes', [ng_control_1.NgControl])], NgControlStatus); - return NgControlStatus; + }), __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 = validators_1.Validators.required; + var REQUIRED_VALIDATOR = lang_1.CONST_EXPR(new core_1.Provider(validators_1.NG_VALIDATORS, { + useValue: 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; + var PATTERN_VALIDATOR = lang_1.CONST_EXPR(new core_1.Provider(validators_1.NG_VALIDATORS, { + useExisting: core_1.forwardRef(function() { + return PatternValidator; + }), + multi: true + })); + var PatternValidator = (function() { + function PatternValidator(pattern) { + this._validator = validators_1.Validators.pattern(pattern); + } + PatternValidator.prototype.validate = function(c) { + return this._validator(c); + }; + PatternValidator = __decorate([core_1.Directive({ + selector: '[pattern][ngControl],[pattern][ngFormControl],[pattern][ngModel]', + providers: [PATTERN_VALIDATOR] + }), __param(0, core_1.Attribute("pattern")), __metadata('design:paramtypes', [String])], PatternValidator); + return PatternValidator; + })(); + exports.PatternValidator = PatternValidator; + 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.NgControlStatus = NgControlStatus; + exports.FormBuilder = FormBuilder; 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) { +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, @@ -18177,185 +17644,339 @@ System.register("angular2/src/common/forms/directives/validators", ["angular2/co 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 dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); 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)); + 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; } - MinLengthValidator.prototype.validate = function(c) { - return this._validator(c); + }; + var KeyEventsPlugin = (function(_super) { + __extends(KeyEventsPlugin, _super); + function KeyEventsPlugin() { + _super.call(this); + } + KeyEventsPlugin.prototype.supports = function(eventName) { + return lang_1.isPresent(KeyEventsPlugin.parseEventName(eventName)); }; - 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)); + 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()); + return this.manager.getZone().runOutsideAngular(function() { + return dom_adapter_1.DOM.onAndCancel(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; } - MaxLengthValidator.prototype.validate = function(c) { - return this._validator(c); + 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); }; - 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; + 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.MaxLengthValidator = MaxLengthValidator; + exports.XHR = XHR; 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) { +System.register("angular2/src/platform/browser/testability", ["angular2/src/facade/collection", "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 __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); + 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(); }; - FormBuilder.prototype.control = function(value, validator, asyncValidator) { - if (validator === void 0) { - validator = null; - } - if (asyncValidator === void 0) { - asyncValidator = null; + 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); + }); + }; + lang_1.global.getAllAngularRootElements = function() { + return registry.getAllRootElements(); + }; + var whenAllStable = function(callback) { + var testabilities = lang_1.global.getAllAngularTestabilities(); + var count = testabilities.length; + var didWork = false; + var decrement = function(didWork_) { + didWork = didWork || didWork_; + count--; + if (count == 0) { + callback(didWork); + } + }; + testabilities.forEach(function(testability) { + testability.whenStable(decrement); + }); + }; + if (!lang_1.global.frameworkStabilizers) { + lang_1.global.frameworkStabilizers = collection_1.ListWrapper.createGrowableSize(0); } - return new modelModule.Control(value, validator, asyncValidator); + lang_1.global.frameworkStabilizers.push(whenAllStable); }; - FormBuilder.prototype.array = function(controlsConfig, validator, asyncValidator) { - var _this = this; - if (validator === void 0) { - validator = null; + BrowserGetTestability.prototype.findTestabilityInTree = function(registry, elem, findInAncestors) { + if (elem == null) { + return null; } - if (asyncValidator === void 0) { - asyncValidator = null; + var t = registry.getTestability(elem); + if (lang_1.isPresent(t)) { + return t; + } else if (!findInAncestors) { + return 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); + 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); }; - FormBuilder = __decorate([core_1.Injectable(), __metadata('design:paramtypes', [])], FormBuilder); - return FormBuilder; + return BrowserGetTestability; })(); - exports.FormBuilder = FormBuilder; - exports.FORM_PROVIDERS = lang_1.CONST_EXPR([FormBuilder]); - exports.FORM_BINDINGS = exports.FORM_PROVIDERS; + exports.BrowserGetTestability = BrowserGetTestability; 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) { +System.register("angular2/src/core/profile/wtf_init", [], 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]); + function wtfInit() {} + exports.wtfInit = wtfInit; 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) { +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 __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 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, @@ -18372,896 +17993,880 @@ System.register("angular2/src/platform/dom/events/key_events", ["angular2/src/pl 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 __param = (this && this.__param) || function(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; }; - var KeyEventsPlugin = (function(_super) { - __extends(KeyEventsPlugin, _super); - function KeyEventsPlugin() { - _super.call(this); + 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, "/") + "/"; + } } - 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; + UrlResolver.prototype.resolve = function(baseUrl, url) { + var resolvedUrl = url; + if (lang_1.isPresent(baseUrl) && baseUrl.length > 0) { + resolvedUrl = _resolveUrl(baseUrl, resolvedUrl); } - 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; + if (lang_1.isPresent(this._packagePrefix) && getUrlScheme(resolvedUrl) == "package") { + resolvedUrl = resolvedUrl.replace("package:", this._packagePrefix); } - var result = collection_1.StringMapWrapper.create(); - collection_1.StringMapWrapper.set(result, 'domEventName', domEventName); - collection_1.StringMapWrapper.set(result, 'fullKey', fullKey); - return result; + return resolvedUrl; }; - 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'; + 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 + '@'); } - modifierKeys.forEach(function(modifierName) { - if (modifierName != key) { - var modifierGetter = collection_1.StringMapWrapper.get(modifierKeyGetters, modifierName); - if (modifierGetter(event)) { - fullKey += modifierName + '.'; + 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++; } - } - }); - 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'; + break; default: - return keyName; + out.push(segment); } - }; - KeyEventsPlugin = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], KeyEventsPlugin); - return KeyEventsPlugin; - })(event_manager_1.EventManagerPlugin); - exports.KeyEventsPlugin = KeyEventsPlugin; + } + 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/platform/dom/events/hammer_common", ["angular2/src/platform/dom/events/event_manager", "angular2/src/facade/collection"], true, function(require, exports, module) { +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 __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); + 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 = []; } - HammerGesturesPluginCommon.prototype.supports = function(eventName) { - eventName = eventName.toLowerCase(); - return collection_1.StringMapWrapper.contains(_eventNames, eventName); + 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; }; - 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; + 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; }; - return XHR; + 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.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; + 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 = []; } - PublicTestability.prototype.isStable = function() { - return this._testability.isStable(); + SelectorMatcher.createNotMatcher = function(notSelectors) { + var notMatcher = new SelectorMatcher(); + notMatcher.addSelectables(notSelectors, null); + return notMatcher; }; - PublicTestability.prototype.whenStable = function(callback) { - this._testability.whenStable(callback); + 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); + } }; - PublicTestability.prototype.findBindings = function(using, provider, exactMatch) { - return this.findProviders(using, provider, exactMatch); + 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); + } + } + } }; - PublicTestability.prototype.findProviders = function(using, provider, exactMatch) { - return this._testability.findBindings(using, provider, exactMatch); + 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); }; - return PublicTestability; - })(); - var BrowserGetTestability = (function() { - function BrowserGetTestability() {} - BrowserGetTestability.init = function() { - core_1.setTestabilityGetter(new BrowserGetTestability()); + 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; }; - BrowserGetTestability.prototype.addToWindow = function(registry) { - lang_1.global.getAngularTestability = function(elem, findInAncestors) { - if (findInAncestors === void 0) { - findInAncestors = true; + 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; } - var testability = registry.findTestabilityInTree(elem, findInAncestors); - if (testability == null) { - throw new Error('Could not find testability for element.'); + } + 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 new PublicTestability(testability); - }; - lang_1.global.getAllAngularTestabilities = function() { - var testabilities = registry.getAllTestabilities(); - return testabilities.map(function(testability) { - return new PublicTestability(testability); - }); - }; + } + return result; }; - BrowserGetTestability.prototype.findTestabilityInTree = function(registry, elem, findInAncestors) { - if (elem == null) { - return null; + SelectorMatcher.prototype._matchTerminal = function(map, name, cssSelector, matchedCallback) { + if (lang_1.isBlank(map) || lang_1.isBlank(name)) { + return false; } - var t = registry.getTestability(elem); - if (lang_1.isPresent(t)) { - return t; - } else if (!findInAncestors) { - return null; + var selectables = map.get(name); + var starSelectables = map.get("*"); + if (lang_1.isPresent(starSelectables)) { + selectables = selectables.concat(starSelectables); } - if (dom_adapter_1.DOM.isShadowRoot(elem)) { - return this.findTestabilityInTree(registry, dom_adapter_1.DOM.getHost(elem), true); + if (lang_1.isBlank(selectables)) { + return false; } - return this.findTestabilityInTree(registry, dom_adapter_1.DOM.parentElement(elem), true); + var selectable; + var result = false; + for (var index = 0; index < selectables.length; index++) { + selectable = selectables[index]; + result = selectable.finalize(cssSelector, matchedCallback) || result; + } + return result; }; - 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(); + 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); }; - Title.prototype.setTitle = function(newTitle) { - dom_adapter_1.DOM.setTitle(newTitle); + 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 Title; + return SelectorContext; })(); - 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']; + exports.SelectorContext = SelectorContext; 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) { +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 __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(); + 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'; + exports.CONST_VAR = lang_1.IS_DART ? 'const' : 'var'; + function camelCaseToDashCase(input) { + return lang_1.StringWrapper.replaceAllMapped(input, CAMEL_CASE_REGEXP, function(m) { + return '-' + m[1].toLowerCase(); + }); } - 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, "/") + "/"; - } + 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; } - 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]) || ""; + return "'" + escapeString(input, SINGLE_QUOTE_ESCAPE_STRING_RE) + "'"; } - 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 + ':'); + exports.escapeSingleQuoteString = escapeSingleQuoteString; + function escapeDoubleQuoteString(input) { + if (lang_1.isBlank(input)) { + return null; } - 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); + 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 + "'] = "; } - if (lang_1.isPresent(opt_path)) { - out.push(opt_path); + } + exports.codeGenExportVariable = codeGenExportVariable; + function codeGenConstConstructorCall(name) { + if (lang_1.IS_DART) { + return "const " + name; + } else { + return "new " + name; } - if (lang_1.isPresent(opt_queryData)) { - out.push('?' + opt_queryData); + } + exports.codeGenConstConstructorCall = codeGenConstConstructorCall; + function codeGenValueFn(params, value, fnName) { + if (fnName === void 0) { + fnName = ''; + } + if (lang_1.IS_DART) { + return codeGenFnHeader(params, fnName) + " => " + value; + } else { + return codeGenFnHeader(params, fnName) + " { return " + value + "; }"; + } + } + exports.codeGenValueFn = codeGenValueFn; + function codeGenFnHeader(params, fnName) { + if (fnName === void 0) { + fnName = ''; + } + if (lang_1.IS_DART) { + return fnName + "(" + params.join(',') + ")"; + } else { + return "function " + fnName + "(" + params.join(',') + ")"; } - if (lang_1.isPresent(opt_fragment)) { - out.push('#' + opt_fragment); + } + exports.codeGenFnHeader = codeGenFnHeader; + function codeGenToString(expr) { + if (lang_1.IS_DART) { + return "'${" + expr + "}'"; + } else { + return expr; } - 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); + 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; + } } - 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); + exports.splitAtColon = splitAtColon; + var Statement = (function() { + function Statement(statement) { + this.statement = statement; + } + return Statement; + })(); + exports.Statement = Statement; + var Expression = (function() { + function Expression(expression, isArray) { + if (isArray === void 0) { + isArray = false; } + this.expression = expression; + this.isArray = isArray; } - if (leadingSlash == '') { - while (up-- > 0) { - out.unshift('..'); + return Expression; + })(); + exports.Expression = Expression; + function escapeValue(value) { + if (value instanceof Expression) { + return value.expression; + } else if (lang_1.isString(value)) { + return escapeSingleQuoteString(value); + } else if (lang_1.isBlank(value)) { + return 'null'; + } else { + return "" + value; + } + } + exports.escapeValue = escapeValue; + function codeGenArray(data) { + return "[" + data.map(escapeValue).join(',') + "]"; + } + exports.codeGenArray = codeGenArray; + function codeGenFlatArray(values) { + var result = '(['; + var isFirstArrayEntry = true; + var concatFn = lang_1.IS_DART ? '.addAll' : 'concat'; + for (var i = 0; i < values.length; i++) { + var value = values[i]; + if (value instanceof Expression && value.isArray) { + result += "])." + concatFn + "(" + value.expression + ")." + concatFn + "(["; + isFirstArrayEntry = true; + } else { + if (!isFirstArrayEntry) { + result += ','; + } + isFirstArrayEntry = false; + result += escapeValue(value); } - if (out.length === 0) - out.push('.'); } - return leadingSlash + out.join('/') + trailingSlash; + result += '])'; + return result; } - 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]); + exports.codeGenFlatArray = codeGenFlatArray; + function codeGenStringMap(keyValueArray) { + return "{" + keyValueArray.map(codeGenKeyValue).join(',') + "}"; } - 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]; + exports.codeGenStringMap = codeGenStringMap; + function codeGenKeyValue(keyValue) { + return escapeValue(keyValue[0]) + ":" + escapeValue(keyValue[1]); + } + function addAll(source, target) { + for (var i = 0; i < source.length; i++) { + target.push(source[i]); } - for (var i = _ComponentIndex.Scheme; i <= _ComponentIndex.Port; i++) { - if (lang_1.isBlank(parts[i])) { - parts[i] = baseParts[i]; + } + exports.addAll = addAll; + function flattenArray(source, target) { + if (lang_1.isPresent(source)) { + for (var i = 0; i < source.length; i++) { + var item = source[i]; + if (lang_1.isArray(item)) { + flattenArray(item, target); + } else { + target.push(item); + } } } - 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); + return target; } + exports.flattenArray = flattenArray; 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) { +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/compiler/template_ast", ["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 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 = []; + var TextAst = (function() { + function TextAst(value, ngContentIndex, sourceSpan) { + this.value = value; + this.ngContentIndex = ngContentIndex; + this.sourceSpan = sourceSpan; } - 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; + TextAst.prototype.visit = function(visitor, context) { + return visitor.visitText(this, context); }; - return CssSelector; + return TextAst; })(); - 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 = []; + exports.TextAst = TextAst; + var BoundTextAst = (function() { + function BoundTextAst(value, ngContentIndex, sourceSpan) { + this.value = value; + this.ngContentIndex = ngContentIndex; + this.sourceSpan = sourceSpan; } - SelectorMatcher.createNotMatcher = function(notSelectors) { - var notMatcher = new SelectorMatcher(); - notMatcher.addSelectables(notSelectors, null); - return notMatcher; + BoundTextAst.prototype.visit = function(visitor, context) { + return visitor.visitBoundText(this, context); }; - 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); - } + 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); }; - 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); + 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 { - 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); - } + 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); }; - 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); + 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); }; - 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; + ElementAst.prototype.isBound = function() { + return (this.inputs.length > 0 || this.outputs.length > 0 || this.exportAsVars.length > 0 || this.directives.length > 0); }; - 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; + ElementAst.prototype.getComponent = function() { + return this.directives.length > 0 && this.directives[0].directive.isComponent ? this.directives[0].directive : null; }; - 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; + 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); }; - 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 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 SelectorMatcher; + return BoundDirectivePropertyAst; })(); - exports.SelectorMatcher = SelectorMatcher; - var SelectorListContext = (function() { - function SelectorListContext(selectors) { - this.selectors = selectors; - this.alreadyMatched = false; + 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; } - return SelectorListContext; + DirectiveAst.prototype.visit = function(visitor, context) { + return visitor.visitDirective(this, context); + }; + return DirectiveAst; })(); - exports.SelectorListContext = SelectorListContext; - var SelectorContext = (function() { - function SelectorContext(selector, cbContext, listContext) { - this.selector = selector; - this.cbContext = cbContext; - this.listContext = listContext; - this.notSelectors = selector.notSelectors; + exports.DirectiveAst = DirectiveAst; + var NgContentAst = (function() { + function NgContentAst(index, ngContentIndex, sourceSpan) { + this.index = index; + this.ngContentIndex = ngContentIndex; + this.sourceSpan = sourceSpan; } - 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; + NgContentAst.prototype.visit = function(visitor, context) { + return visitor.visitNgContent(this, context); }; - return SelectorContext; + return NgContentAst; })(); - 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; + 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; } - 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]; + var result = []; + asts.forEach(function(ast) { + var astResult = ast.visit(visitor, context); + if (lang_1.isPresent(astResult)) { + result.push(astResult); } }); + return result; } - 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; + exports.templateVisitAll = templateVisitAll; global.define = __define; return module.exports; }); @@ -19281,6 +18886,11 @@ System.register("angular2/src/compiler/source_module", ["angular2/src/facade/lan this.moduleUrl = moduleUrl; this.sourceWithModuleRefs = sourceWithModuleRefs; } + SourceModule.getSourceWithoutImports = function(sourceWithModuleRefs) { + return lang_1.StringWrapper.replaceAllMapped(sourceWithModuleRefs, MODULE_REGEXP, function(match) { + return ''; + }); + }; SourceModule.prototype.getSourceWithImports = function() { var _this = this; var moduleAliases = {}; @@ -19332,198 +18942,162 @@ System.register("angular2/src/compiler/source_module", ["angular2/src/facade/lan return module.exports; }); -System.register("angular2/src/compiler/template_ast", ["angular2/src/facade/lang"], true, function(require, exports, module) { +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 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; + 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.nodeCount = 0; + this.boundElementCount = 0; + this.variableNames = []; + this.bindingRecords = []; + this.eventRecords = []; + this.directiveRecords = []; + this.viewIndex = allVisitors.length; + allVisitors.push(this); } - AttrAst.prototype.visit = function(visitor, context) { - return visitor.visitAttr(this, context); + ProtoViewVisitor.prototype.visitEmbeddedTemplate = function(ast, context) { + this.nodeCount++; + 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; }; - 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); + ProtoViewVisitor.prototype.visitElement = function(ast, context) { + this.nodeCount++; + 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; }; - 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); + ProtoViewVisitor.prototype.visitNgContent = function(ast, context) { + return null; }; - 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); + ProtoViewVisitor.prototype.visitVariable = function(ast, context) { + this.variableNames.push(ast.name); + return null; }; - 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); + 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; }; - ElementAst.prototype.isBound = function() { - return (this.inputs.length > 0 || this.outputs.length > 0 || this.exportAsVars.length > 0 || this.directives.length > 0); + 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; }; - ElementAst.prototype.getComponent = function() { - return this.directives.length > 0 && this.directives[0].directive.isComponent ? this.directives[0].directive : null; + ProtoViewVisitor.prototype.visitAttr = function(ast, context) { + return 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); + ProtoViewVisitor.prototype.visitBoundText = function(ast, context) { + var nodeIndex = this.nodeCount++; + this.bindingRecords.push(change_detection_1.BindingRecord.createForTextNode(ast.value, nodeIndex)); + return null; }; - 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); + ProtoViewVisitor.prototype.visitText = function(ast, context) { + this.nodeCount++; + return null; }; - 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); + ProtoViewVisitor.prototype.visitDirective = function(ast, directiveIndexAsNumber) { + var directiveIndex = new change_detection_1.DirectiveIndex(this.boundElementCount - 1, directiveIndexAsNumber); + var directiveMetadata = ast.directive; + var outputsArray = []; + collection_1.StringMapWrapper.forEach(ast.directive.outputs, function(eventName, dirProperty) { + return outputsArray.push([dirProperty, eventName]); + }); + 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, + callOnDestroy: directiveMetadata.lifecycleHooks.indexOf(interfaces_1.LifecycleHooks.OnDestroy) !== -1, + changeDetection: directiveMetadata.changeDetection, + outputs: outputsArray + }); + 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; }; - 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); + 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 NgContentAst; + return ProtoViewVisitor; })(); - 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); - } + 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); }); - return result; } - exports.templateVisitAll = templateVisitAll; + 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; }); @@ -19663,12 +19237,13 @@ System.register("angular2/src/compiler/shadow_css", ["angular2/src/facade/collec 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); + var p = parts[i].trim(); + var deepParts = lang_1.StringWrapper.split(p, _shadowDeepSelectors); + var shallowPart = deepParts[0]; + if (this._selectorNeedsScoping(shallowPart, scopeSelector)) { + deepParts[0] = strict && !lang_1.StringWrapper.contains(shallowPart, _polyfillHostNoCombinator) ? this._applyStrictSelectorScope(shallowPart, scopeSelector) : this._applySelectorScope(shallowPart, scopeSelector, hostSelector); } - r.push(p); + r.push(deepParts.join(' ')); } return r.join(', '); }; @@ -19737,7 +19312,8 @@ System.register("angular2/src/compiler/shadow_css", ["angular2/src/facade/collec 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 _shadowDOMSelectorsRe = [/::shadow/g, /::content/g, /\/shadow-deep\//g, /\/shadow\//g]; + var _shadowDeepSelectors = /(?:>>>)|(?:\/deep\/)/g; var _selectorReSuffix = '([>\\s~+\[.,{:][\\s\\S]*)?$'; var _polyfillHostRe = lang_1.RegExpWrapper.create(_polyfillHost, 'im'); var _colonHostRe = /:host/gim; @@ -19860,10 +19436,19 @@ System.register("angular2/src/compiler/style_url_resolver", ["angular2/src/facad 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) { +System.register("angular2/src/compiler/proto_view_compiler", ["angular2/src/facade/lang", "angular2/src/facade/collection", "angular2/src/compiler/template_ast", "angular2/src/compiler/source_module", "angular2/src/core/linker/view", "angular2/src/core/linker/view_type", "angular2/src/core/linker/element", "angular2/src/compiler/util", "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, @@ -19882,110 +19467,159 @@ System.register("angular2/src/compiler/command_compiler", ["angular2/src/facade/ }; 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 view_1 = require("angular2/src/core/linker/view"); + var view_type_1 = require("angular2/src/core/linker/view_type"); + var element_1 = require("angular2/src/core/linker/element"); 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); + exports.PROTO_VIEW_JIT_IMPORTS = lang_1.CONST_EXPR({ + 'AppProtoView': view_1.AppProtoView, + 'AppProtoElement': element_1.AppProtoElement, + 'ViewType': view_type_1.ViewType + }); + exports.APP_VIEW_MODULE_REF = source_module_1.moduleRef('package:angular2/src/core/linker/view' + util_1.MODULE_SUFFIX); + exports.VIEW_TYPE_MODULE_REF = source_module_1.moduleRef('package:angular2/src/core/linker/view_type' + util_1.MODULE_SUFFIX); + exports.APP_EL_MODULE_REF = source_module_1.moduleRef('package:angular2/src/core/linker/element' + util_1.MODULE_SUFFIX); + exports.METADATA_MODULE_REF = source_module_1.moduleRef('package:angular2/src/core/metadata/view' + 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; + var ProtoViewCompiler = (function() { + function ProtoViewCompiler() {} + ProtoViewCompiler.prototype.compileProtoViewRuntime = function(metadataCache, component, template, pipes) { + var protoViewFactory = new RuntimeProtoViewFactory(metadataCache, component, pipes); + var allProtoViews = []; + protoViewFactory.createCompileProtoView(template, [], [], allProtoViews); + return new CompileProtoViews([], allProtoViews); + }; + ProtoViewCompiler.prototype.compileProtoViewCodeGen = function(resolvedMetadataCacheExpr, component, template, pipes) { + var protoViewFactory = new CodeGenProtoViewFactory(resolvedMetadataCacheExpr, component, pipes); + var allProtoViews = []; + var allStatements = []; + protoViewFactory.createCompileProtoView(template, [], allStatements, allProtoViews); + return new CompileProtoViews(allStatements.map(function(stmt) { + return stmt.statement; + }), allProtoViews); + }; + ProtoViewCompiler = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], ProtoViewCompiler); + return ProtoViewCompiler; + })(); + exports.ProtoViewCompiler = ProtoViewCompiler; + var CompileProtoViews = (function() { + function CompileProtoViews(declarations, protoViews) { + this.declarations = declarations; + this.protoViews = protoViews; } - 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; + return CompileProtoViews; })(); - var CodegenCommandFactory = (function() { - function CodegenCommandFactory(component, componentTemplateFactory, changeDetectorFactoryExpressions) { - this.component = component; - this.componentTemplateFactory = componentTemplateFactory; - this.changeDetectorFactoryExpressions = changeDetectorFactoryExpressions; + exports.CompileProtoViews = CompileProtoViews; + var CompileProtoView = (function() { + function CompileProtoView(embeddedTemplateIndex, protoElements, protoView) { + this.embeddedTemplateIndex = embeddedTemplateIndex; + this.protoElements = protoElements; + this.protoView = protoView; } - 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; + return CompileProtoView; + })(); + exports.CompileProtoView = CompileProtoView; + var CompileProtoElement = (function() { + function CompileProtoElement(boundElementIndex, attrNameAndValues, variableNameAndValues, renderEvents, directives, embeddedTemplateIndex, appProtoEl) { + this.boundElementIndex = boundElementIndex; + this.attrNameAndValues = attrNameAndValues; + this.variableNameAndValues = variableNameAndValues; + this.renderEvents = renderEvents; + this.directives = directives; + this.embeddedTemplateIndex = embeddedTemplateIndex; + this.appProtoEl = appProtoEl; + } + return CompileProtoElement; })(); + exports.CompileProtoElement = CompileProtoElement; 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; + var ProtoViewFactory = (function() { + function ProtoViewFactory(component) { + this.component = component; } - CommandBuilderVisitor.prototype._readAttrNameAndValues = function(directives, attrAsts) { - var attrs = keyValueArrayToMap(visitAndReturnContext(this, attrAsts, [])); + ProtoViewFactory.prototype.createCompileProtoView = function(template, templateVariableBindings, targetStatements, targetProtoViews) { + var embeddedTemplateIndex = targetProtoViews.length; + targetProtoViews.push(null); + var builder = new ProtoViewBuilderVisitor(this, targetStatements, targetProtoViews); + template_ast_1.templateVisitAll(builder, template); + var viewType = getViewType(this.component, embeddedTemplateIndex); + var appProtoView = this.createAppProtoView(embeddedTemplateIndex, viewType, templateVariableBindings, targetStatements); + var cpv = new CompileProtoView(embeddedTemplateIndex, builder.protoElements, appProtoView); + targetProtoViews[embeddedTemplateIndex] = cpv; + return cpv; + }; + return ProtoViewFactory; + })(); + var CodeGenProtoViewFactory = (function(_super) { + __extends(CodeGenProtoViewFactory, _super); + function CodeGenProtoViewFactory(resolvedMetadataCacheExpr, component, pipes) { + _super.call(this, component); + this.resolvedMetadataCacheExpr = resolvedMetadataCacheExpr; + this.pipes = pipes; + this._nextVarId = 0; + } + CodeGenProtoViewFactory.prototype._nextProtoViewVar = function(embeddedTemplateIndex) { + return "appProtoView" + this._nextVarId++ + "_" + this.component.type.name + embeddedTemplateIndex; + }; + CodeGenProtoViewFactory.prototype.createAppProtoView = function(embeddedTemplateIndex, viewType, templateVariableBindings, targetStatements) { + var protoViewVarName = this._nextProtoViewVar(embeddedTemplateIndex); + var viewTypeExpr = codeGenViewType(viewType); + var pipesExpr = embeddedTemplateIndex === 0 ? codeGenTypesArray(this.pipes.map(function(pipeMeta) { + return pipeMeta.type; + })) : null; + var statement = "var " + protoViewVarName + " = " + exports.APP_VIEW_MODULE_REF + "AppProtoView.create(" + this.resolvedMetadataCacheExpr.expression + ", " + viewTypeExpr + ", " + pipesExpr + ", " + util_1.codeGenStringMap(templateVariableBindings) + ");"; + targetStatements.push(new util_1.Statement(statement)); + return new util_1.Expression(protoViewVarName); + }; + CodeGenProtoViewFactory.prototype.createAppProtoElement = function(boundElementIndex, attrNameAndValues, variableNameAndValues, directives, targetStatements) { + var varName = "appProtoEl" + this._nextVarId++ + "_" + this.component.type.name; + var value = exports.APP_EL_MODULE_REF + "AppProtoElement.create(\n " + this.resolvedMetadataCacheExpr.expression + ",\n " + boundElementIndex + ",\n " + util_1.codeGenStringMap(attrNameAndValues) + ",\n " + codeGenDirectivesArray(directives) + ",\n " + util_1.codeGenStringMap(variableNameAndValues) + "\n )"; + var statement = "var " + varName + " = " + value + ";"; + targetStatements.push(new util_1.Statement(statement)); + return new util_1.Expression(varName); + }; + return CodeGenProtoViewFactory; + })(ProtoViewFactory); + var RuntimeProtoViewFactory = (function(_super) { + __extends(RuntimeProtoViewFactory, _super); + function RuntimeProtoViewFactory(metadataCache, component, pipes) { + _super.call(this, component); + this.metadataCache = metadataCache; + this.pipes = pipes; + } + RuntimeProtoViewFactory.prototype.createAppProtoView = function(embeddedTemplateIndex, viewType, templateVariableBindings, targetStatements) { + var pipes = embeddedTemplateIndex === 0 ? this.pipes.map(function(pipeMeta) { + return pipeMeta.type.runtime; + }) : []; + var templateVars = keyValueArrayToStringMap(templateVariableBindings); + return view_1.AppProtoView.create(this.metadataCache, viewType, pipes, templateVars); + }; + RuntimeProtoViewFactory.prototype.createAppProtoElement = function(boundElementIndex, attrNameAndValues, variableNameAndValues, directives, targetStatements) { + var attrs = keyValueArrayToStringMap(attrNameAndValues); + return element_1.AppProtoElement.create(this.metadataCache, boundElementIndex, attrs, directives.map(function(dirMeta) { + return dirMeta.type.runtime; + }), keyValueArrayToStringMap(variableNameAndValues)); + }; + return RuntimeProtoViewFactory; + })(ProtoViewFactory); + var ProtoViewBuilderVisitor = (function() { + function ProtoViewBuilderVisitor(factory, allStatements, allProtoViews) { + this.factory = factory; + this.allStatements = allStatements; + this.allProtoViews = allProtoViews; + this.protoElements = []; + this.boundElementCount = 0; + } + ProtoViewBuilderVisitor.prototype._readAttrNameAndValues = function(directives, attrAsts) { + var attrs = visitAndReturnContext(this, attrAsts, {}); directives.forEach(function(directiveMeta) { collection_1.StringMapWrapper.forEach(directiveMeta.hostAttributes, function(value, name) { var prevValue = attrs[name]; @@ -19994,119 +19628,92 @@ System.register("angular2/src/compiler/command_compiler", ["angular2/src/facade/ }); return mapToKeyValueArray(attrs); }; - CommandBuilderVisitor.prototype.visitNgContent = function(ast, context) { - this.transitiveNgContentCount++; - this.result.push(this.commandFactory.createNgContent(ast.index, ast.ngContentIndex)); + ProtoViewBuilderVisitor.prototype.visitBoundText = function(ast, context) { 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; + ProtoViewBuilderVisitor.prototype.visitText = function(ast, context) { return null; }; - CommandBuilderVisitor.prototype.visitElement = function(ast, context) { + ProtoViewBuilderVisitor.prototype.visitNgContent = function(ast, context) { + return null; + }; + ProtoViewBuilderVisitor.prototype.visitElement = function(ast, context) { var _this = this; + var boundElementIndex = null; + if (ast.isBound()) { + boundElementIndex = this.boundElementCount++; + } 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); + variableNameAndValues.push([varAst.name, null]); }); } var directives = []; + var renderEvents = visitAndReturnContext(this, ast.outputs, new Map()); collection_1.ListWrapper.forEachWithIndex(ast.directives, function(directiveAst, index) { - directiveAst.visit(_this, new DirectiveContext(index, eventTargetAndNames, variableNameAndValues, directives)); + directiveAst.visit(_this, new DirectiveContext(index, boundElementIndex, renderEvents, variableNameAndValues, directives)); + }); + var renderEventArray = []; + renderEvents.forEach(function(eventAst, _) { + return renderEventArray.push(eventAst); }); - 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()); - } + this._addProtoElement(ast.isBound(), boundElementIndex, attrNameAndValues, variableNameAndValues, renderEventArray, directives, null); + template_ast_1.templateVisitAll(this, ast.children); return null; }; - CommandBuilderVisitor.prototype.visitVariable = function(ast, ctx) { + ProtoViewBuilderVisitor.prototype.visitEmbeddedTemplate = function(ast, context) { + var _this = this; + var boundElementIndex = this.boundElementCount++; + var directives = []; + collection_1.ListWrapper.forEachWithIndex(ast.directives, function(directiveAst, index) { + directiveAst.visit(_this, new DirectiveContext(index, boundElementIndex, new Map(), [], directives)); + }); + var attrNameAndValues = this._readAttrNameAndValues(directives, ast.attrs); + var templateVariableBindings = ast.vars.map(function(varAst) { + return [varAst.value.length > 0 ? varAst.value : IMPLICIT_TEMPLATE_VAR, varAst.name]; + }); + var nestedProtoView = this.factory.createCompileProtoView(ast.children, templateVariableBindings, this.allStatements, this.allProtoViews); + this._addProtoElement(true, boundElementIndex, attrNameAndValues, [], [], directives, nestedProtoView.embeddedTemplateIndex); return null; }; - CommandBuilderVisitor.prototype.visitAttr = function(ast, attrNameAndValues) { - attrNameAndValues.push(ast.name); - attrNameAndValues.push(ast.value); - return null; + ProtoViewBuilderVisitor.prototype._addProtoElement = function(isBound, boundElementIndex, attrNameAndValues, variableNameAndValues, renderEvents, directives, embeddedTemplateIndex) { + var appProtoEl = null; + if (isBound) { + appProtoEl = this.factory.createAppProtoElement(boundElementIndex, attrNameAndValues, variableNameAndValues, directives, this.allStatements); + } + var compileProtoEl = new CompileProtoElement(boundElementIndex, attrNameAndValues, variableNameAndValues, renderEvents, directives, embeddedTemplateIndex, appProtoEl); + this.protoElements.push(compileProtoEl); }; - CommandBuilderVisitor.prototype.visitBoundText = function(ast, context) { - this.result.push(this.commandFactory.createText(null, true, ast.ngContentIndex)); + ProtoViewBuilderVisitor.prototype.visitVariable = function(ast, ctx) { return null; }; - CommandBuilderVisitor.prototype.visitText = function(ast, context) { - this.result.push(this.commandFactory.createText(ast.value, false, ast.ngContentIndex)); + ProtoViewBuilderVisitor.prototype.visitAttr = function(ast, attrNameAndValues) { + attrNameAndValues[ast.name] = ast.value; return null; }; - CommandBuilderVisitor.prototype.visitDirective = function(ast, ctx) { + ProtoViewBuilderVisitor.prototype.visitDirective = function(ast, ctx) { ctx.targetDirectives.push(ast.directive); - template_ast_1.templateVisitAll(this, ast.hostEvents, ctx.eventTargetAndNames); + template_ast_1.templateVisitAll(this, ast.hostEvents, ctx.hostEventTargetAndNames); ast.exportAsVars.forEach(function(varAst) { - ctx.targetVariableNameAndValues.push(varAst.name); - ctx.targetVariableNameAndValues.push(ctx.index); + ctx.targetVariableNameAndValues.push([varAst.name, ctx.index]); }); return null; }; - CommandBuilderVisitor.prototype.visitEvent = function(ast, eventTargetAndNames) { - eventTargetAndNames.push(ast.target); - eventTargetAndNames.push(ast.name); + ProtoViewBuilderVisitor.prototype.visitEvent = function(ast, eventTargetAndNames) { + eventTargetAndNames.set(ast.fullName, ast); return null; }; - CommandBuilderVisitor.prototype.visitDirectiveProperty = function(ast, context) { + ProtoViewBuilderVisitor.prototype.visitDirectiveProperty = function(ast, context) { return null; }; - CommandBuilderVisitor.prototype.visitElementProperty = function(ast, context) { + ProtoViewBuilderVisitor.prototype.visitElementProperty = function(ast, context) { return null; }; - return CommandBuilderVisitor; + return ProtoViewBuilderVisitor; })(); - 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) { @@ -20117,8 +19724,7 @@ System.register("angular2/src/compiler/command_compiler", ["angular2/src/facade/ }); var keyValueArray = []; entryArray.forEach(function(entry) { - keyValueArray.push(entry[0]); - keyValueArray.push(entry[1]); + keyValueArray.push([entry[0], entry[1]]); }); return keyValueArray; } @@ -20130,49 +19736,52 @@ System.register("angular2/src/compiler/command_compiler", ["angular2/src/facade/ } } var DirectiveContext = (function() { - function DirectiveContext(index, eventTargetAndNames, targetVariableNameAndValues, targetDirectives) { + function DirectiveContext(index, boundElementIndex, hostEventTargetAndNames, targetVariableNameAndValues, targetDirectives) { this.index = index; - this.eventTargetAndNames = eventTargetAndNames; + this.boundElementIndex = boundElementIndex; + this.hostEventTargetAndNames = hostEventTargetAndNames; 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 keyValueArrayToStringMap(keyValueArray) { + var stringMap = {}; + for (var i = 0; i < keyValueArray.length; i++) { + var entry = keyValueArray[i]; + stringMap[entry[0]] = entry[1]; } - } - function codeGenArray(data) { - var base = "[" + data.map(escapeValue).join(',') + "]"; - return lang_1.IS_DART ? "const " + base : base; + return stringMap; } function codeGenDirectivesArray(directives) { var expressions = directives.map(function(directiveType) { - return ("" + source_module_1.moduleRef(directiveType.type.moduleUrl) + directiveType.type.name); + return typeRef(directiveType.type); }); - var base = "[" + expressions.join(',') + "]"; - return lang_1.IS_DART ? "const " + base : base; + return "[" + expressions.join(',') + "]"; } - function codeGenViewEncapsulation(value) { + function codeGenTypesArray(types) { + var expressions = types.map(typeRef); + return "[" + expressions.join(',') + "]"; + } + function codeGenViewType(value) { if (lang_1.IS_DART) { - return "" + exports.TEMPLATE_COMMANDS_MODULE_REF + value; + return "" + exports.VIEW_TYPE_MODULE_REF + value; } else { return "" + value; } } + function typeRef(type) { + return "" + source_module_1.moduleRef(type.moduleUrl) + type.name; + } + function getViewType(component, embeddedTemplateIndex) { + if (embeddedTemplateIndex > 0) { + return view_type_1.ViewType.EMBEDDED; + } else if (component.type.isHost) { + return view_type_1.ViewType.HOST; + } else { + return view_type_1.ViewType.COMPONENT; + } + } global.define = __define; return module.exports; }); @@ -20206,11 +19815,13 @@ System.register("angular2/src/compiler/html_ast", ["angular2/src/facade/lang"], })(); exports.HtmlAttrAst = HtmlAttrAst; var HtmlElementAst = (function() { - function HtmlElementAst(name, attrs, children, sourceSpan) { + function HtmlElementAst(name, attrs, children, sourceSpan, startSourceSpan, endSourceSpan) { this.name = name; this.attrs = attrs; this.children = children; this.sourceSpan = sourceSpan; + this.startSourceSpan = startSourceSpan; + this.endSourceSpan = endSourceSpan; } HtmlElementAst.prototype.visit = function(visitor, context) { return visitor.visitElement(this, context); @@ -20218,6 +19829,17 @@ System.register("angular2/src/compiler/html_ast", ["angular2/src/facade/lang"], return HtmlElementAst; })(); exports.HtmlElementAst = HtmlElementAst; + var HtmlCommentAst = (function() { + function HtmlCommentAst(value, sourceSpan) { + this.value = value; + this.sourceSpan = sourceSpan; + } + HtmlCommentAst.prototype.visit = function(visitor, context) { + return visitor.visitComment(this, context); + }; + return HtmlCommentAst; + })(); + exports.HtmlCommentAst = HtmlCommentAst; function htmlVisitAll(visitor, asts, context) { if (context === void 0) { context = null; @@ -20261,14 +19883,25 @@ System.register("angular2/src/compiler/parse_util", [], true, function(require, return ParseSourceFile; })(); exports.ParseSourceFile = ParseSourceFile; + 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; var ParseError = (function() { - function ParseError(location, msg) { - this.location = location; + function ParseError(span, msg) { + this.span = span; this.msg = msg; } ParseError.prototype.toString = function() { - var source = this.location.file.content; - var ctxStart = this.location.offset; + var source = this.span.start.file.content; + var ctxStart = this.span.start.offset; if (ctxStart > source.length - 1) { ctxStart = source.length - 1; } @@ -20295,23 +19928,12 @@ System.register("angular2/src/compiler/parse_util", [], true, function(require, } } } - var context = source.substring(ctxStart, this.location.offset) + '[ERROR ->]' + source.substring(this.location.offset, ctxEnd + 1); - return this.msg + " (\"" + context + "\"): " + this.location; + var context = source.substring(ctxStart, this.span.start.offset) + '[ERROR ->]' + source.substring(this.span.start.offset, ctxEnd + 1); + return this.msg + " (\"" + context + "\"): " + this.span.start; }; 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; }); @@ -20629,6 +20251,8 @@ System.register("angular2/src/compiler/html_tags", ["angular2/src/facade/lang"], })(); exports.HtmlTagDefinition = HtmlTagDefinition; var TAG_DEFINITIONS = { + 'base': new HtmlTagDefinition({isVoid: true}), + 'meta': new HtmlTagDefinition({isVoid: true}), 'area': new HtmlTagDefinition({isVoid: true}), 'embed': new HtmlTagDefinition({isVoid: true}), 'link': new HtmlTagDefinition({isVoid: true}), @@ -20734,6 +20358,10 @@ System.register("angular2/src/compiler/html_tags", ["angular2/src/facade/lang"], return splitNsName(elementName)[0]; } exports.getNsPrefix = getNsPrefix; + function mergeNsAndName(prefix, localName) { + return lang_1.isPresent(prefix) ? "@" + prefix + ":" + localName : localName; + } + exports.mergeNsAndName = mergeNsAndName; global.define = __define; return module.exports; }); @@ -20772,11 +20400,13 @@ System.register("angular2/src/compiler/template_preparser", ["angular2/src/facad var STYLE_ELEMENT = 'style'; var SCRIPT_ELEMENT = 'script'; var NG_NON_BINDABLE_ATTR = 'ngNonBindable'; + var NG_PROJECT_AS = 'ngProjectAs'; function preparseElement(ast) { var selectAttr = null; var hrefAttr = null; var relAttr = null; var nonBindable = false; + var projectAs = null; ast.attrs.forEach(function(attr) { var lcAttrName = attr.name.toLowerCase(); if (lcAttrName == NG_CONTENT_SELECT_ATTR) { @@ -20787,6 +20417,10 @@ System.register("angular2/src/compiler/template_preparser", ["angular2/src/facad relAttr = attr.value; } else if (attr.name == NG_NON_BINDABLE_ATTR) { nonBindable = true; + } else if (attr.name == NG_PROJECT_AS) { + if (attr.value.length > 0) { + projectAs = attr.value; + } } }); selectAttr = normalizeNgContentSelect(selectAttr); @@ -20801,7 +20435,7 @@ System.register("angular2/src/compiler/template_preparser", ["angular2/src/facad } else if (nodeName == LINK_ELEMENT && relAttr == LINK_STYLE_REL_VALUE) { type = PreparsedElementType.STYLESHEET; } - return new PreparsedElement(type, selectAttr, hrefAttr, nonBindable); + return new PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs); } exports.preparseElement = preparseElement; (function(PreparsedElementType) { @@ -20813,11 +20447,12 @@ System.register("angular2/src/compiler/template_preparser", ["angular2/src/facad })(exports.PreparsedElementType || (exports.PreparsedElementType = {})); var PreparsedElementType = exports.PreparsedElementType; var PreparsedElement = (function() { - function PreparsedElement(type, selectAttr, hrefAttr, nonBindable) { + function PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs) { this.type = type; this.selectAttr = selectAttr; this.hrefAttr = hrefAttr; this.nonBindable = nonBindable; + this.projectAs = projectAs; } return PreparsedElement; })(); @@ -20949,6 +20584,8 @@ System.register("angular2/src/compiler/template_normalizer", ["angular2/src/comp case template_preparser_1.PreparsedElementType.STYLESHEET: this.styleUrls.push(preparsedElement.hrefAttr); break; + default: + break; } if (preparsedElement.nonBindable) { this.ngNonBindableStackCount++; @@ -20959,6 +20596,9 @@ System.register("angular2/src/compiler/template_normalizer", ["angular2/src/comp } return null; }; + TemplatePreparseVisitor.prototype.visitComment = function(ast, context) { + return null; + }; TemplatePreparseVisitor.prototype.visitAttr = function(ast, context) { return null; }; @@ -20971,144 +20611,62 @@ System.register("angular2/src/compiler/template_normalizer", ["angular2/src/comp 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) { +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 __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(); + 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; } - 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); + } + exports.hasLifecycleHook = hasLifecycleHook; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/compiler/assertions", ["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"); + function assertArrayOfStrings(identifier, value) { + if (!lang_1.assertionsEnabled() || lang_1.isBlank(value)) { + return ; } - if (lang_1.isPresent(view.directives)) { - flattenArray(view.directives, directives); + if (!lang_1.isArray(value)) { + throw new exceptions_1.BaseException("Expected '" + identifier + "' to be an array of strings."); } - 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); + for (var i = 0; i < value.length; i += 1) { + if (!lang_1.isString(value[i])) { + throw new exceptions_1.BaseException("Expected '" + identifier + "' to be an array of strings."); } } } - 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); - } - } + exports.assertArrayOfStrings = assertArrayOfStrings; global.define = __define; return module.exports; }); @@ -21270,6 +20828,7 @@ System.register("angular2/src/common/pipes/async_pipe", ["angular2/src/facade/la })(); var _promiseStrategy = new PromiseStrategy(); var _observableStrategy = new ObservableStrategy(); + var __unused; var AsyncPipe = (function() { function AsyncPipe(_ref) { this._latestValue = null; @@ -21289,6 +20848,7 @@ System.register("angular2/src/common/pipes/async_pipe", ["angular2/src/facade/la if (lang_1.isPresent(obj)) { this._subscribe(obj); } + this._latestReturnedValue = this._latestValue; return this._latestValue; } if (obj !== this._obj) { @@ -21410,7 +20970,7 @@ System.register("angular2/src/common/pipes/date_pipe", ["angular2/src/facade/lan 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) { +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/ng_plural", "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; @@ -21431,6 +20991,10 @@ System.register("angular2/src/common/directives", ["angular2/src/common/directiv exports.NgSwitch = ng_switch_1.NgSwitch; exports.NgSwitchWhen = ng_switch_1.NgSwitchWhen; exports.NgSwitchDefault = ng_switch_1.NgSwitchDefault; + var ng_plural_1 = require("angular2/src/common/directives/ng_plural"); + exports.NgPlural = ng_plural_1.NgPlural; + exports.NgPluralCase = ng_plural_1.NgPluralCase; + exports.NgLocalization = ng_plural_1.NgLocalization; __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; @@ -21438,7 +21002,7 @@ System.register("angular2/src/common/directives", ["angular2/src/common/directiv 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) { +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/radio_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; @@ -21450,6 +21014,7 @@ System.register("angular2/src/common/forms/directives/shared", ["angular2/src/fa 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 radio_control_value_accessor_1 = require("angular2/src/common/forms/directives/radio_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); @@ -21494,7 +21059,7 @@ System.register("angular2/src/common/forms/directives/shared", ["angular2/src/fa } exports.composeValidators = composeValidators; function composeAsyncValidators(validators) { - return lang_1.isPresent(validators) ? validators_1.Validators.composeAsync(validators.map(normalize_validator_1.normalizeValidator)) : null; + return lang_1.isPresent(validators) ? validators_1.Validators.composeAsync(validators.map(normalize_validator_1.normalizeAsyncValidator)) : null; } exports.composeAsyncValidators = composeAsyncValidators; function isPropertyUpdated(changes, viewModel) { @@ -21513,9 +21078,9 @@ System.register("angular2/src/common/forms/directives/shared", ["angular2/src/fa var builtinAccessor; var customAccessor; valueAccessors.forEach(function(v) { - if (v instanceof default_value_accessor_1.DefaultValueAccessor) { + if (lang_1.hasConstructor(v, 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) { + } else if (lang_1.hasConstructor(v, checkbox_value_accessor_1.CheckboxControlValueAccessor) || lang_1.hasConstructor(v, number_value_accessor_1.NumberValueAccessor) || lang_1.hasConstructor(v, select_control_value_accessor_1.SelectControlValueAccessor) || lang_1.hasConstructor(v, radio_control_value_accessor_1.RadioControlValueAccessor)) { if (lang_1.isPresent(builtinAccessor)) _throwError(dir, "More than one built-in value accessor matches"); builtinAccessor = v; @@ -21539,7 +21104,7 @@ System.register("angular2/src/common/forms/directives/shared", ["angular2/src/fa 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) { +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/radio_control_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/radio_control_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; @@ -21553,6 +21118,7 @@ System.register("angular2/src/common/forms/directives", ["angular2/src/facade/la 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 radio_control_value_accessor_1 = require("angular2/src/common/forms/directives/radio_control_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"); @@ -21572,6 +21138,9 @@ System.register("angular2/src/common/forms/directives", ["angular2/src/facade/la 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 radio_control_value_accessor_2 = require("angular2/src/common/forms/directives/radio_control_value_accessor"); + exports.RadioControlValueAccessor = radio_control_value_accessor_2.RadioControlValueAccessor; + exports.RadioButtonState = radio_control_value_accessor_2.RadioButtonState; 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"); @@ -21583,9 +21152,10 @@ System.register("angular2/src/common/forms/directives", ["angular2/src/facade/la exports.RequiredValidator = validators_2.RequiredValidator; exports.MinLengthValidator = validators_2.MinLengthValidator; exports.MaxLengthValidator = validators_2.MaxLengthValidator; + exports.PatternValidator = validators_2.PatternValidator; 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]); + 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, radio_control_value_accessor_1.RadioControlValueAccessor, ng_control_status_1.NgControlStatus, validators_1.RequiredValidator, validators_1.MinLengthValidator, validators_1.MaxLengthValidator, validators_1.PatternValidator]); global.define = __define; return module.exports; }); @@ -21639,15 +21209,19 @@ System.register("angular2/src/platform/dom/events/hammer_gestures", ["angular2/s HammerGesturesPlugin.prototype.addEventListener = function(element, eventName, handler) { var zone = this.manager.getZone(); eventName = eventName.toLowerCase(); - zone.runOutsideAngular(function() { + return 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) { + var callback = function(eventObj) { zone.run(function() { handler(eventObj); }); - }); + }; + mc.on(eventName, callback); + return function() { + mc.off(eventName, callback); + }; }); }; HammerGesturesPlugin = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], HammerGesturesPlugin); @@ -21756,11 +21330,21 @@ System.register("angular2/src/platform/browser/tools/common_tools", ["angular2/s 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) { +System.register("angular2/src/compiler/directive_metadata", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "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 __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 change_detection_1 = require("angular2/src/core/change_detection/change_detection"); var view_1 = require("angular2/src/core/metadata/view"); @@ -21768,35 +21352,279 @@ System.register("angular2/src/compiler/directive_metadata", ["angular2/src/facad var util_1 = require("angular2/src/compiler/util"); var interfaces_1 = require("angular2/src/core/linker/interfaces"); var HOST_REG_EXP = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\)))$/g; + var CompileMetadataWithIdentifier = (function() { + function CompileMetadataWithIdentifier() {} + CompileMetadataWithIdentifier.fromJson = function(data) { + return _COMPILE_METADATA_FROM_JSON[data['class']](data); + }; + Object.defineProperty(CompileMetadataWithIdentifier.prototype, "identifier", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + return CompileMetadataWithIdentifier; + })(); + exports.CompileMetadataWithIdentifier = CompileMetadataWithIdentifier; + var CompileMetadataWithType = (function(_super) { + __extends(CompileMetadataWithType, _super); + function CompileMetadataWithType() { + _super.apply(this, arguments); + } + CompileMetadataWithType.fromJson = function(data) { + return _COMPILE_METADATA_FROM_JSON[data['class']](data); + }; + Object.defineProperty(CompileMetadataWithType.prototype, "type", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CompileMetadataWithType.prototype, "identifier", { + get: function() { + return exceptions_1.unimplemented(); + }, + enumerable: true, + configurable: true + }); + return CompileMetadataWithType; + })(CompileMetadataWithIdentifier); + exports.CompileMetadataWithType = CompileMetadataWithType; + var CompileIdentifierMetadata = (function() { + function CompileIdentifierMetadata(_a) { + var _b = _a === void 0 ? {} : _a, + runtime = _b.runtime, + name = _b.name, + moduleUrl = _b.moduleUrl, + prefix = _b.prefix, + constConstructor = _b.constConstructor; + this.runtime = runtime; + this.name = name; + this.prefix = prefix; + this.moduleUrl = moduleUrl; + this.constConstructor = constConstructor; + } + CompileIdentifierMetadata.fromJson = function(data) { + return new CompileIdentifierMetadata({ + name: data['name'], + prefix: data['prefix'], + moduleUrl: data['moduleUrl'], + constConstructor: data['constConstructor'] + }); + }; + CompileIdentifierMetadata.prototype.toJson = function() { + return { + 'class': 'Identifier', + 'name': this.name, + 'moduleUrl': this.moduleUrl, + 'prefix': this.prefix, + 'constConstructor': this.constConstructor + }; + }; + Object.defineProperty(CompileIdentifierMetadata.prototype, "identifier", { + get: function() { + return this; + }, + enumerable: true, + configurable: true + }); + return CompileIdentifierMetadata; + })(); + exports.CompileIdentifierMetadata = CompileIdentifierMetadata; + var CompileDiDependencyMetadata = (function() { + function CompileDiDependencyMetadata(_a) { + var _b = _a === void 0 ? {} : _a, + isAttribute = _b.isAttribute, + isSelf = _b.isSelf, + isHost = _b.isHost, + isSkipSelf = _b.isSkipSelf, + isOptional = _b.isOptional, + query = _b.query, + viewQuery = _b.viewQuery, + token = _b.token; + this.isAttribute = lang_1.normalizeBool(isAttribute); + this.isSelf = lang_1.normalizeBool(isSelf); + this.isHost = lang_1.normalizeBool(isHost); + this.isSkipSelf = lang_1.normalizeBool(isSkipSelf); + this.isOptional = lang_1.normalizeBool(isOptional); + this.query = query; + this.viewQuery = viewQuery; + this.token = token; + } + CompileDiDependencyMetadata.fromJson = function(data) { + return new CompileDiDependencyMetadata({ + token: objFromJson(data['token'], CompileIdentifierMetadata.fromJson), + query: objFromJson(data['query'], CompileQueryMetadata.fromJson), + viewQuery: objFromJson(data['viewQuery'], CompileQueryMetadata.fromJson), + isAttribute: data['isAttribute'], + isSelf: data['isSelf'], + isHost: data['isHost'], + isSkipSelf: data['isSkipSelf'], + isOptional: data['isOptional'] + }); + }; + CompileDiDependencyMetadata.prototype.toJson = function() { + return { + 'token': objToJson(this.token), + 'query': objToJson(this.query), + 'viewQuery': objToJson(this.viewQuery), + 'isAttribute': this.isAttribute, + 'isSelf': this.isSelf, + 'isHost': this.isHost, + 'isSkipSelf': this.isSkipSelf, + 'isOptional': this.isOptional + }; + }; + return CompileDiDependencyMetadata; + })(); + exports.CompileDiDependencyMetadata = CompileDiDependencyMetadata; + var CompileProviderMetadata = (function() { + function CompileProviderMetadata(_a) { + var token = _a.token, + 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.deps = deps; + this.multi = multi; + } + CompileProviderMetadata.fromJson = function(data) { + return new CompileProviderMetadata({ + token: objFromJson(data['token'], CompileIdentifierMetadata.fromJson), + useClass: objFromJson(data['useClass'], CompileTypeMetadata.fromJson) + }); + }; + CompileProviderMetadata.prototype.toJson = function() { + return { + 'token': objToJson(this.token), + 'useClass': objToJson(this.useClass) + }; + }; + return CompileProviderMetadata; + })(); + exports.CompileProviderMetadata = CompileProviderMetadata; + var CompileFactoryMetadata = (function() { + function CompileFactoryMetadata(_a) { + var runtime = _a.runtime, + name = _a.name, + moduleUrl = _a.moduleUrl, + constConstructor = _a.constConstructor, + diDeps = _a.diDeps; + this.runtime = runtime; + this.name = name; + this.moduleUrl = moduleUrl; + this.diDeps = diDeps; + this.constConstructor = constConstructor; + } + Object.defineProperty(CompileFactoryMetadata.prototype, "identifier", { + get: function() { + return this; + }, + enumerable: true, + configurable: true + }); + CompileFactoryMetadata.prototype.toJson = function() { + return null; + }; + return CompileFactoryMetadata; + })(); + exports.CompileFactoryMetadata = CompileFactoryMetadata; var CompileTypeMetadata = (function() { function CompileTypeMetadata(_a) { var _b = _a === void 0 ? {} : _a, runtime = _b.runtime, name = _b.name, moduleUrl = _b.moduleUrl, - isHost = _b.isHost; + prefix = _b.prefix, + isHost = _b.isHost, + constConstructor = _b.constConstructor, + diDeps = _b.diDeps; this.runtime = runtime; this.name = name; this.moduleUrl = moduleUrl; + this.prefix = prefix; this.isHost = lang_1.normalizeBool(isHost); + this.constConstructor = constConstructor; + this.diDeps = lang_1.normalizeBlank(diDeps); } CompileTypeMetadata.fromJson = function(data) { return new CompileTypeMetadata({ name: data['name'], moduleUrl: data['moduleUrl'], - isHost: data['isHost'] + prefix: data['prefix'], + isHost: data['isHost'], + constConstructor: data['constConstructor'], + diDeps: arrayFromJson(data['diDeps'], CompileDiDependencyMetadata.fromJson) }); }; + Object.defineProperty(CompileTypeMetadata.prototype, "identifier", { + get: function() { + return this; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CompileTypeMetadata.prototype, "type", { + get: function() { + return this; + }, + enumerable: true, + configurable: true + }); CompileTypeMetadata.prototype.toJson = function() { return { + 'class': 'Type', 'name': this.name, 'moduleUrl': this.moduleUrl, - 'isHost': this.isHost + 'prefix': this.prefix, + 'isHost': this.isHost, + 'constConstructor': this.constConstructor, + 'diDeps': arrayToJson(this.diDeps) }; }; return CompileTypeMetadata; })(); exports.CompileTypeMetadata = CompileTypeMetadata; + var CompileQueryMetadata = (function() { + function CompileQueryMetadata(_a) { + var _b = _a === void 0 ? {} : _a, + selectors = _b.selectors, + descendants = _b.descendants, + first = _b.first, + propertyName = _b.propertyName; + this.selectors = selectors; + this.descendants = descendants; + this.first = lang_1.normalizeBool(first); + this.propertyName = propertyName; + } + CompileQueryMetadata.fromJson = function(data) { + return new CompileQueryMetadata({ + selectors: arrayFromJson(data['selectors'], CompileIdentifierMetadata.fromJson), + descendants: data['descendants'], + first: data['first'], + propertyName: data['propertyName'] + }); + }; + CompileQueryMetadata.prototype.toJson = function() { + return { + 'selectors': arrayToJson(this.selectors), + 'descendants': this.descendants, + 'first': this.first, + 'propertyName': this.propertyName + }; + }; + return CompileQueryMetadata; + })(); + exports.CompileQueryMetadata = CompileQueryMetadata; var CompileTemplateMetadata = (function() { function CompileTemplateMetadata(_a) { var _b = _a === void 0 ? {} : _a, @@ -21851,6 +21679,10 @@ System.register("angular2/src/compiler/directive_metadata", ["angular2/src/facad hostProperties = _b.hostProperties, hostAttributes = _b.hostAttributes, lifecycleHooks = _b.lifecycleHooks, + providers = _b.providers, + viewProviders = _b.viewProviders, + queries = _b.queries, + viewQueries = _b.viewQueries, template = _b.template; this.type = type; this.isComponent = isComponent; @@ -21864,6 +21696,10 @@ System.register("angular2/src/compiler/directive_metadata", ["angular2/src/facad this.hostProperties = hostProperties; this.hostAttributes = hostAttributes; this.lifecycleHooks = lifecycleHooks; + this.providers = lang_1.normalizeBlank(providers); + this.viewProviders = lang_1.normalizeBlank(viewProviders); + this.queries = queries; + this.viewQueries = viewQueries; this.template = template; } CompileDirectiveMetadata.create = function(_a) { @@ -21878,6 +21714,10 @@ System.register("angular2/src/compiler/directive_metadata", ["angular2/src/facad outputs = _b.outputs, host = _b.host, lifecycleHooks = _b.lifecycleHooks, + providers = _b.providers, + viewProviders = _b.viewProviders, + queries = _b.queries, + viewQueries = _b.viewQueries, template = _b.template; var hostListeners = {}; var hostProperties = {}; @@ -21921,9 +21761,20 @@ System.register("angular2/src/compiler/directive_metadata", ["angular2/src/facad hostProperties: hostProperties, hostAttributes: hostAttributes, lifecycleHooks: lang_1.isPresent(lifecycleHooks) ? lifecycleHooks : [], + providers: providers, + viewProviders: viewProviders, + queries: queries, + viewQueries: viewQueries, template: template }); }; + Object.defineProperty(CompileDirectiveMetadata.prototype, "identifier", { + get: function() { + return this.type; + }, + enumerable: true, + configurable: true + }); CompileDirectiveMetadata.fromJson = function(data) { return new CompileDirectiveMetadata({ isComponent: data['isComponent'], @@ -21940,11 +21791,13 @@ System.register("angular2/src/compiler/directive_metadata", ["angular2/src/facad 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'] + template: lang_1.isPresent(data['template']) ? CompileTemplateMetadata.fromJson(data['template']) : data['template'], + providers: arrayFromJson(data['providers'], CompileProviderMetadata.fromJson) }); }; CompileDirectiveMetadata.prototype.toJson = function() { return { + 'class': 'Directive', 'isComponent': this.isComponent, 'dynamicLoadable': this.dynamicLoadable, 'selector': this.selector, @@ -21959,7 +21812,8 @@ System.register("angular2/src/compiler/directive_metadata", ["angular2/src/facad 'lifecycleHooks': this.lifecycleHooks.map(function(hook) { return lang_1.serializeEnum(hook); }), - 'template': lang_1.isPresent(this.template) ? this.template.toJson() : this.template + 'template': lang_1.isPresent(this.template) ? this.template.toJson() : this.template, + 'providers': arrayToJson(this.providers) }; }; return CompileDirectiveMetadata; @@ -21988,166 +21842,166 @@ System.register("angular2/src/compiler/directive_metadata", ["angular2/src/facad lifecycleHooks: [], isComponent: true, dynamicLoadable: false, - selector: '*' + selector: '*', + providers: [], + viewProviders: [], + queries: [], + viewQueries: [] }); } 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; + var CompilePipeMetadata = (function() { + function CompilePipeMetadata(_a) { + var _b = _a === void 0 ? {} : _a, + type = _b.type, + name = _b.name, + pure = _b.pure; + this.type = type; + this.name = name; + this.pure = lang_1.normalizeBool(pure); + } + Object.defineProperty(CompilePipeMetadata.prototype, "identifier", { + get: function() { + return this.type; + }, + enumerable: true, + configurable: true + }); + CompilePipeMetadata.fromJson = function(data) { + return new CompilePipeMetadata({ + type: lang_1.isPresent(data['type']) ? CompileTypeMetadata.fromJson(data['type']) : data['type'], + name: data['name'], + pure: data['pure'] + }); }; - 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; + CompilePipeMetadata.prototype.toJson = function() { + return { + 'class': 'Pipe', + 'type': lang_1.isPresent(this.type) ? this.type.toJson() : null, + 'name': this.name, + 'pure': this.pure + }; }; - return ProtoViewVisitor; + return CompilePipeMetadata; })(); - 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); + exports.CompilePipeMetadata = CompilePipeMetadata; + var _COMPILE_METADATA_FROM_JSON = { + 'Directive': CompileDirectiveMetadata.fromJson, + 'Pipe': CompilePipeMetadata.fromJson, + 'Type': CompileTypeMetadata.fromJson, + 'Identifier': CompileIdentifierMetadata.fromJson + }; + function arrayFromJson(obj, fn) { + return lang_1.isBlank(obj) ? null : obj.map(function(o) { + return objFromJson(o, fn); }); } - 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; + function arrayToJson(obj) { + return lang_1.isBlank(obj) ? null : obj.map(objToJson); } + function objFromJson(obj, fn) { + return (lang_1.isString(obj) || lang_1.isBlank(obj)) ? obj : fn(obj); + } + function objToJson(obj) { + return (lang_1.isString(obj) || lang_1.isBlank(obj)) ? obj : obj.toJson(); + } + 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/core/change_detection/abstract_change_detector", "angular2/src/core/change_detection/change_detection_util", "angular2/src/core/change_detection/constants", "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 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 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"; + exports.CHANGE_DETECTION_JIT_IMPORTS = lang_1.CONST_EXPR({ + 'AbstractChangeDetector': abstract_change_detector_1.AbstractChangeDetector, + 'ChangeDetectionUtil': change_detection_util_1.ChangeDetectionUtil, + 'ChangeDetectorState': constants_1.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) { + var proto = new change_detection_1.DynamicProtoChangeDetector(definition); + return function() { + return proto.instantiate(); + }; + }; + 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() { return new " + codegen.typeName + "(); }"); + 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/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) { +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"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -22177,7 +22031,9 @@ System.register("angular2/src/compiler/style_compiler", ["angular2/src/compiler/ 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 COMPONENT_VARIABLE = '%COMP%'; + var HOST_ATTR = "_nghost-" + COMPONENT_VARIABLE; + var CONTENT_ATTR = "_ngcontent-" + COMPONENT_VARIABLE; var StyleCompiler = (function() { function StyleCompiler(_xhr, _urlResolver) { this._xhr = _xhr; @@ -22194,64 +22050,482 @@ System.register("angular2/src/compiler/style_compiler", ["angular2/src/compiler/ 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.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, CONTENT_ATTR, 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/view_compiler", ["angular2/src/facade/lang", "angular2/src/facade/collection", "angular2/src/compiler/template_ast", "angular2/src/compiler/source_module", "angular2/src/core/linker/view", "angular2/src/core/linker/view_type", "angular2/src/core/linker/element", "angular2/src/core/metadata/view", "angular2/src/compiler/util", "angular2/src/core/di", "angular2/src/compiler/proto_view_compiler"], 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_ast_1 = require("angular2/src/compiler/template_ast"); + var source_module_1 = require("angular2/src/compiler/source_module"); + var view_1 = require("angular2/src/core/linker/view"); + var view_type_1 = require("angular2/src/core/linker/view_type"); + var element_1 = require("angular2/src/core/linker/element"); + var view_2 = require("angular2/src/core/metadata/view"); + var util_1 = require("angular2/src/compiler/util"); + var di_1 = require("angular2/src/core/di"); + var proto_view_compiler_1 = require("angular2/src/compiler/proto_view_compiler"); + exports.VIEW_JIT_IMPORTS = lang_1.CONST_EXPR({ + 'AppView': view_1.AppView, + 'AppElement': element_1.AppElement, + 'flattenNestedViewRenderNodes': view_1.flattenNestedViewRenderNodes, + 'checkSlotCount': view_1.checkSlotCount + }); + var ViewCompiler = (function() { + function ViewCompiler() {} + ViewCompiler.prototype.compileComponentRuntime = function(component, template, styles, protoViews, changeDetectorFactories, componentViewFactory) { + var viewFactory = new RuntimeViewFactory(component, styles, protoViews, changeDetectorFactories, componentViewFactory); + return viewFactory.createViewFactory(template, 0, []); + }; + ViewCompiler.prototype.compileComponentCodeGen = function(component, template, styles, protoViews, changeDetectorFactoryExpressions, componentViewFactory) { + var viewFactory = new CodeGenViewFactory(component, styles, protoViews, changeDetectorFactoryExpressions, componentViewFactory); + var targetStatements = []; + var viewFactoryExpression = viewFactory.createViewFactory(template, 0, targetStatements); + return new source_module_1.SourceExpression(targetStatements.map(function(stmt) { + return stmt.statement; + }), viewFactoryExpression.expression); + }; + ViewCompiler = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [])], ViewCompiler); + return ViewCompiler; + })(); + exports.ViewCompiler = ViewCompiler; + var CodeGenViewFactory = (function() { + function CodeGenViewFactory(component, styles, protoViews, changeDetectorExpressions, componentViewFactory) { + this.component = component; + this.styles = styles; + this.protoViews = protoViews; + this.changeDetectorExpressions = changeDetectorExpressions; + this.componentViewFactory = componentViewFactory; + this._nextVarId = 0; + } + CodeGenViewFactory.prototype._nextVar = function(prefix) { + return "" + prefix + this._nextVarId++ + "_" + this.component.type.name; + }; + CodeGenViewFactory.prototype._nextRenderVar = function() { + return this._nextVar('render'); + }; + CodeGenViewFactory.prototype._nextAppVar = function() { + return this._nextVar('app'); + }; + CodeGenViewFactory.prototype._nextDisposableVar = function() { + return "disposable" + this._nextVarId++ + "_" + this.component.type.name; + }; + CodeGenViewFactory.prototype.createText = function(renderer, parent, text, targetStatements) { + var varName = this._nextRenderVar(); + var statement = "var " + varName + " = " + renderer.expression + ".createText(" + (lang_1.isPresent(parent) ? parent.expression : null) + ", " + util_1.escapeSingleQuoteString(text) + ");"; + targetStatements.push(new util_1.Statement(statement)); + return new util_1.Expression(varName); + }; + CodeGenViewFactory.prototype.createElement = function(renderer, parentRenderNode, name, rootSelector, targetStatements) { + var varName = this._nextRenderVar(); + var valueExpr; + if (lang_1.isPresent(rootSelector)) { + valueExpr = rootSelector.expression + " == null ?\n " + renderer.expression + ".createElement(" + (lang_1.isPresent(parentRenderNode) ? parentRenderNode.expression : null) + ", " + util_1.escapeSingleQuoteString(name) + ") :\n " + renderer.expression + ".selectRootElement(" + rootSelector.expression + ");"; + } else { + valueExpr = renderer.expression + ".createElement(" + (lang_1.isPresent(parentRenderNode) ? parentRenderNode.expression : null) + ", " + util_1.escapeSingleQuoteString(name) + ")"; + } + var statement = "var " + varName + " = " + valueExpr + ";"; + targetStatements.push(new util_1.Statement(statement)); + return new util_1.Expression(varName); + }; + CodeGenViewFactory.prototype.createTemplateAnchor = function(renderer, parentRenderNode, targetStatements) { + var varName = this._nextRenderVar(); + var valueExpr = renderer.expression + ".createTemplateAnchor(" + (lang_1.isPresent(parentRenderNode) ? parentRenderNode.expression : null) + ");"; + targetStatements.push(new util_1.Statement("var " + varName + " = " + valueExpr)); + return new util_1.Expression(varName); + }; + CodeGenViewFactory.prototype.createGlobalEventListener = function(renderer, appView, boundElementIndex, eventAst, targetStatements) { + var disposableVar = this._nextDisposableVar(); + var eventHandlerExpr = codeGenEventHandler(appView, boundElementIndex, eventAst.fullName); + targetStatements.push(new util_1.Statement("var " + disposableVar + " = " + renderer.expression + ".listenGlobal(" + util_1.escapeValue(eventAst.target) + ", " + util_1.escapeValue(eventAst.name) + ", " + eventHandlerExpr + ");")); + return new util_1.Expression(disposableVar); + }; + CodeGenViewFactory.prototype.createElementEventListener = function(renderer, appView, boundElementIndex, renderNode, eventAst, targetStatements) { + var disposableVar = this._nextDisposableVar(); + var eventHandlerExpr = codeGenEventHandler(appView, boundElementIndex, eventAst.fullName); + targetStatements.push(new util_1.Statement("var " + disposableVar + " = " + renderer.expression + ".listen(" + renderNode.expression + ", " + util_1.escapeValue(eventAst.name) + ", " + eventHandlerExpr + ");")); + return new util_1.Expression(disposableVar); + }; + CodeGenViewFactory.prototype.setElementAttribute = function(renderer, renderNode, attrName, attrValue, targetStatements) { + targetStatements.push(new util_1.Statement(renderer.expression + ".setElementAttribute(" + renderNode.expression + ", " + util_1.escapeSingleQuoteString(attrName) + ", " + util_1.escapeSingleQuoteString(attrValue) + ");")); + }; + CodeGenViewFactory.prototype.createAppElement = function(appProtoEl, appView, renderNode, parentAppEl, embeddedViewFactory, targetStatements) { + var appVar = this._nextAppVar(); + var varValue = "new " + proto_view_compiler_1.APP_EL_MODULE_REF + "AppElement(" + appProtoEl.expression + ", " + appView.expression + ",\n " + (lang_1.isPresent(parentAppEl) ? parentAppEl.expression : null) + ", " + renderNode.expression + ", " + (lang_1.isPresent(embeddedViewFactory) ? embeddedViewFactory.expression : null) + ")"; + targetStatements.push(new util_1.Statement("var " + appVar + " = " + varValue + ";")); + return new util_1.Expression(appVar); + }; + CodeGenViewFactory.prototype.createAndSetComponentView = function(renderer, viewManager, view, appEl, component, contentNodesByNgContentIndex, targetStatements) { + var codeGenContentNodes; + if (this.component.type.isHost) { + codeGenContentNodes = view.expression + ".projectableNodes"; + } else { + codeGenContentNodes = "[" + contentNodesByNgContentIndex.map(function(nodes) { + return util_1.codeGenFlatArray(nodes); + }).join(',') + "]"; + } + targetStatements.push(new util_1.Statement(this.componentViewFactory(component) + "(" + renderer.expression + ", " + viewManager.expression + ", " + appEl.expression + ", " + codeGenContentNodes + ", null, null, null);")); + }; + CodeGenViewFactory.prototype.getProjectedNodes = function(projectableNodes, ngContentIndex) { + return new util_1.Expression(projectableNodes.expression + "[" + ngContentIndex + "]", true); + }; + CodeGenViewFactory.prototype.appendProjectedNodes = function(renderer, parent, nodes, targetStatements) { + targetStatements.push(new util_1.Statement(renderer.expression + ".projectNodes(" + parent.expression + ", " + proto_view_compiler_1.APP_VIEW_MODULE_REF + "flattenNestedViewRenderNodes(" + nodes.expression + "));")); + }; + CodeGenViewFactory.prototype.createViewFactory = function(asts, embeddedTemplateIndex, targetStatements) { + var compileProtoView = this.protoViews[embeddedTemplateIndex]; + var isHostView = this.component.type.isHost; + var isComponentView = embeddedTemplateIndex === 0 && !isHostView; + var visitor = new ViewBuilderVisitor(new util_1.Expression('renderer'), new util_1.Expression('viewManager'), new util_1.Expression('projectableNodes'), isHostView ? new util_1.Expression('rootSelector') : null, new util_1.Expression('view'), compileProtoView, targetStatements, this); + template_ast_1.templateVisitAll(visitor, asts, new ParentElement(isComponentView ? new util_1.Expression('parentRenderNode') : null, null, null)); + var appProtoView = compileProtoView.protoView.expression; + var viewFactoryName = codeGenViewFactoryName(this.component, embeddedTemplateIndex); + var changeDetectorFactory = this.changeDetectorExpressions.expressions[embeddedTemplateIndex]; + var factoryArgs = ['parentRenderer', 'viewManager', 'containerEl', 'projectableNodes', 'rootSelector', 'dynamicallyCreatedProviders', 'rootInjector']; + var initRendererStmts = []; + var rendererExpr = "parentRenderer"; + if (embeddedTemplateIndex === 0) { + var renderCompTypeVar = this._nextVar('renderType'); + targetStatements.push(new util_1.Statement("var " + renderCompTypeVar + " = null;")); + var stylesVar = this._nextVar('styles'); + targetStatements.push(new util_1.Statement(util_1.CONST_VAR + " " + stylesVar + " = " + this.styles.expression + ";")); + var encapsulation = this.component.template.encapsulation; + initRendererStmts.push("if (" + renderCompTypeVar + " == null) {\n " + renderCompTypeVar + " = viewManager.createRenderComponentType(" + codeGenViewEncapsulation(encapsulation) + ", " + stylesVar + ");\n }"); + rendererExpr = "parentRenderer.renderComponent(" + renderCompTypeVar + ")"; + } + var statement = "\n" + util_1.codeGenFnHeader(factoryArgs, viewFactoryName) + "{\n " + initRendererStmts.join('\n') + "\n var renderer = " + rendererExpr + ";\n var view = new " + proto_view_compiler_1.APP_VIEW_MODULE_REF + "AppView(\n " + appProtoView + ", renderer, viewManager,\n projectableNodes,\n containerEl,\n dynamicallyCreatedProviders, rootInjector,\n " + changeDetectorFactory + "()\n );\n " + proto_view_compiler_1.APP_VIEW_MODULE_REF + "checkSlotCount(" + util_1.escapeValue(this.component.type.name) + ", " + this.component.template.ngContentSelectors.length + ", projectableNodes);\n " + (isComponentView ? 'var parentRenderNode = renderer.createViewRoot(view.containerAppElement.nativeElement);' : '') + "\n " + visitor.renderStmts.map(function(stmt) { + return stmt.statement; + }).join('\n') + "\n " + visitor.appStmts.map(function(stmt) { + return stmt.statement; + }).join('\n') + "\n\n view.init(" + util_1.codeGenFlatArray(visitor.rootNodesOrAppElements) + ", " + util_1.codeGenArray(visitor.renderNodes) + ", " + util_1.codeGenArray(visitor.appDisposables) + ",\n " + util_1.codeGenArray(visitor.appElements) + ");\n return view;\n}"; + targetStatements.push(new util_1.Statement(statement)); + return new util_1.Expression(viewFactoryName); + }; + return CodeGenViewFactory; + })(); + var RuntimeViewFactory = (function() { + function RuntimeViewFactory(component, styles, protoViews, changeDetectorFactories, componentViewFactory) { + this.component = component; + this.styles = styles; + this.protoViews = protoViews; + this.changeDetectorFactories = changeDetectorFactories; + this.componentViewFactory = componentViewFactory; + } + RuntimeViewFactory.prototype.createText = function(renderer, parent, text, targetStatements) { + return renderer.createText(parent, text); + }; + RuntimeViewFactory.prototype.createElement = function(renderer, parent, name, rootSelector, targetStatements) { + var el; + if (lang_1.isPresent(rootSelector)) { + el = renderer.selectRootElement(rootSelector); + } else { + el = renderer.createElement(parent, name); + } + return el; + }; + RuntimeViewFactory.prototype.createTemplateAnchor = function(renderer, parent, targetStatements) { + return renderer.createTemplateAnchor(parent); + }; + RuntimeViewFactory.prototype.createGlobalEventListener = function(renderer, appView, boundElementIndex, eventAst, targetStatements) { + return renderer.listenGlobal(eventAst.target, eventAst.name, function(event) { + return appView.triggerEventHandlers(eventAst.fullName, event, boundElementIndex); + }); + }; + RuntimeViewFactory.prototype.createElementEventListener = function(renderer, appView, boundElementIndex, renderNode, eventAst, targetStatements) { + return renderer.listen(renderNode, eventAst.name, function(event) { + return appView.triggerEventHandlers(eventAst.fullName, event, boundElementIndex); + }); + }; + RuntimeViewFactory.prototype.setElementAttribute = function(renderer, renderNode, attrName, attrValue, targetStatements) { + renderer.setElementAttribute(renderNode, attrName, attrValue); + }; + RuntimeViewFactory.prototype.createAppElement = function(appProtoEl, appView, renderNode, parentAppEl, embeddedViewFactory, targetStatements) { + return new element_1.AppElement(appProtoEl, appView, parentAppEl, renderNode, embeddedViewFactory); + }; + RuntimeViewFactory.prototype.createAndSetComponentView = function(renderer, viewManager, appView, appEl, component, contentNodesByNgContentIndex, targetStatements) { + var flattenedContentNodes; + if (this.component.type.isHost) { + flattenedContentNodes = appView.projectableNodes; + } else { + flattenedContentNodes = collection_1.ListWrapper.createFixedSize(contentNodesByNgContentIndex.length); + for (var i = 0; i < contentNodesByNgContentIndex.length; i++) { + flattenedContentNodes[i] = util_1.flattenArray(contentNodesByNgContentIndex[i], []); + } + } + this.componentViewFactory(component)(renderer, viewManager, appEl, flattenedContentNodes); + }; + RuntimeViewFactory.prototype.getProjectedNodes = function(projectableNodes, ngContentIndex) { + return projectableNodes[ngContentIndex]; + }; + RuntimeViewFactory.prototype.appendProjectedNodes = function(renderer, parent, nodes, targetStatements) { + renderer.projectNodes(parent, view_1.flattenNestedViewRenderNodes(nodes)); + }; + RuntimeViewFactory.prototype.createViewFactory = function(asts, embeddedTemplateIndex, targetStatements) { + var _this = this; + var compileProtoView = this.protoViews[embeddedTemplateIndex]; + var isComponentView = compileProtoView.protoView.type === view_type_1.ViewType.COMPONENT; + var renderComponentType = null; + return function(parentRenderer, viewManager, containerEl, projectableNodes, rootSelector, dynamicallyCreatedProviders, rootInjector) { + if (rootSelector === void 0) { + rootSelector = null; + } + if (dynamicallyCreatedProviders === void 0) { + dynamicallyCreatedProviders = null; + } + if (rootInjector === void 0) { + rootInjector = null; + } + view_1.checkSlotCount(_this.component.type.name, _this.component.template.ngContentSelectors.length, projectableNodes); + var renderer; + if (embeddedTemplateIndex === 0) { + if (lang_1.isBlank(renderComponentType)) { + renderComponentType = viewManager.createRenderComponentType(_this.component.template.encapsulation, _this.styles); + } + renderer = parentRenderer.renderComponent(renderComponentType); + } else { + renderer = parentRenderer; + } + var changeDetector = _this.changeDetectorFactories[embeddedTemplateIndex](); + var view = new view_1.AppView(compileProtoView.protoView, renderer, viewManager, projectableNodes, containerEl, dynamicallyCreatedProviders, rootInjector, changeDetector); + var visitor = new ViewBuilderVisitor(renderer, viewManager, projectableNodes, rootSelector, view, compileProtoView, [], _this); + var parentRenderNode = isComponentView ? renderer.createViewRoot(containerEl.nativeElement) : null; + template_ast_1.templateVisitAll(visitor, asts, new ParentElement(parentRenderNode, null, null)); + view.init(util_1.flattenArray(visitor.rootNodesOrAppElements, []), visitor.renderNodes, visitor.appDisposables, visitor.appElements); + return view; + }; + }; + return RuntimeViewFactory; + })(); + var ParentElement = (function() { + function ParentElement(renderNode, appEl, component) { + this.renderNode = renderNode; + this.appEl = appEl; + this.component = component; + if (lang_1.isPresent(component)) { + this.contentNodesByNgContentIndex = collection_1.ListWrapper.createFixedSize(component.template.ngContentSelectors.length); + for (var i = 0; i < this.contentNodesByNgContentIndex.length; i++) { + this.contentNodesByNgContentIndex[i] = []; + } + } else { + this.contentNodesByNgContentIndex = null; + } + } + ParentElement.prototype.addContentNode = function(ngContentIndex, nodeExpr) { + this.contentNodesByNgContentIndex[ngContentIndex].push(nodeExpr); + }; + return ParentElement; + })(); + var ViewBuilderVisitor = (function() { + function ViewBuilderVisitor(renderer, viewManager, projectableNodes, rootSelector, view, protoView, targetStatements, factory) { + this.renderer = renderer; + this.viewManager = viewManager; + this.projectableNodes = projectableNodes; + this.rootSelector = rootSelector; + this.view = view; + this.protoView = protoView; + this.targetStatements = targetStatements; + this.factory = factory; + this.renderStmts = []; + this.renderNodes = []; + this.appStmts = []; + this.appElements = []; + this.appDisposables = []; + this.rootNodesOrAppElements = []; + this.elementCount = 0; + } + ViewBuilderVisitor.prototype._addRenderNode = function(renderNode, appEl, ngContentIndex, parent) { + this.renderNodes.push(renderNode); + if (lang_1.isPresent(parent.component)) { + if (lang_1.isPresent(ngContentIndex)) { + parent.addContentNode(ngContentIndex, lang_1.isPresent(appEl) ? appEl : renderNode); + } + } else if (lang_1.isBlank(parent.renderNode)) { + this.rootNodesOrAppElements.push(lang_1.isPresent(appEl) ? appEl : renderNode); + } + }; + ViewBuilderVisitor.prototype._getParentRenderNode = function(ngContentIndex, parent) { + return lang_1.isPresent(parent.component) && parent.component.template.encapsulation !== view_2.ViewEncapsulation.Native ? null : parent.renderNode; + }; + ViewBuilderVisitor.prototype.visitBoundText = function(ast, parent) { + return this._visitText('', ast.ngContentIndex, parent); }; - StyleCompiler.prototype.clearCache = function() { - this._styleCache.clear(); + ViewBuilderVisitor.prototype.visitText = function(ast, parent) { + return this._visitText(ast.value, ast.ngContentIndex, parent); }; - 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); + ViewBuilderVisitor.prototype._visitText = function(value, ngContentIndex, parent) { + var renderNode = this.factory.createText(this.renderer, this._getParentRenderNode(ngContentIndex, parent), value, this.renderStmts); + this._addRenderNode(renderNode, null, ngContentIndex, parent); + return null; + }; + ViewBuilderVisitor.prototype.visitNgContent = function(ast, parent) { + var nodesExpression = this.factory.getProjectedNodes(this.projectableNodes, ast.index); + if (lang_1.isPresent(parent.component)) { + if (lang_1.isPresent(ast.ngContentIndex)) { + parent.addContentNode(ast.ngContentIndex, nodesExpression); } - 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; - }); + } else { + if (lang_1.isPresent(parent.renderNode)) { + this.factory.appendProjectedNodes(this.renderer, parent.renderNode, nodesExpression, this.renderStmts); + } else { + this.rootNodesOrAppElements.push(nodesExpression); + } + } + return null; }; - StyleCompiler.prototype._styleCodeGen = function(plainStyles, absUrls, shim) { + ViewBuilderVisitor.prototype.visitElement = function(ast, parent) { var _this = this; - var arrayPrefix = lang_1.IS_DART ? "const" : ''; - var styleExpressions = plainStyles.map(function(plainStyle) { - return util_1.escapeSingleQuoteString(_this._shimIfNeeded(plainStyle, shim)); + var renderNode = this.factory.createElement(this.renderer, this._getParentRenderNode(ast.ngContentIndex, parent), ast.name, this.rootSelector, this.renderStmts); + var component = ast.getComponent(); + var elementIndex = this.elementCount++; + var protoEl = this.protoView.protoElements[elementIndex]; + protoEl.renderEvents.forEach(function(eventAst) { + var disposable; + if (lang_1.isPresent(eventAst.target)) { + disposable = _this.factory.createGlobalEventListener(_this.renderer, _this.view, protoEl.boundElementIndex, eventAst, _this.renderStmts); + } else { + disposable = _this.factory.createElementEventListener(_this.renderer, _this.view, protoEl.boundElementIndex, renderNode, eventAst, _this.renderStmts); + } + _this.appDisposables.push(disposable); }); - for (var i = 0; i < absUrls.length; i++) { - var moduleUrl = this._createModuleUrl(absUrls[i], shim); - styleExpressions.push(source_module_1.moduleRef(moduleUrl) + "STYLES"); + for (var i = 0; i < protoEl.attrNameAndValues.length; i++) { + var attrName = protoEl.attrNameAndValues[i][0]; + var attrValue = protoEl.attrNameAndValues[i][1]; + this.factory.setElementAttribute(this.renderer, renderNode, attrName, attrValue, this.renderStmts); + } + var appEl = null; + if (lang_1.isPresent(protoEl.appProtoEl)) { + appEl = this.factory.createAppElement(protoEl.appProtoEl, this.view, renderNode, parent.appEl, null, this.appStmts); + this.appElements.push(appEl); + } + this._addRenderNode(renderNode, appEl, ast.ngContentIndex, parent); + var newParent = new ParentElement(renderNode, lang_1.isPresent(appEl) ? appEl : parent.appEl, component); + template_ast_1.templateVisitAll(this, ast.children, newParent); + if (lang_1.isPresent(appEl) && lang_1.isPresent(component)) { + this.factory.createAndSetComponentView(this.renderer, this.viewManager, this.view, appEl, component, newParent.contentNodesByNgContentIndex, this.appStmts); } - var expressionSource = arrayPrefix + " [" + styleExpressions.join(',') + "]"; - return new source_module_1.SourceExpression([], expressionSource); + return null; }; - 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); + ViewBuilderVisitor.prototype.visitEmbeddedTemplate = function(ast, parent) { + var renderNode = this.factory.createTemplateAnchor(this.renderer, this._getParentRenderNode(ast.ngContentIndex, parent), this.renderStmts); + var elementIndex = this.elementCount++; + var protoEl = this.protoView.protoElements[elementIndex]; + var embeddedViewFactory = this.factory.createViewFactory(ast.children, protoEl.embeddedTemplateIndex, this.targetStatements); + var appEl = this.factory.createAppElement(protoEl.appProtoEl, this.view, renderNode, parent.appEl, embeddedViewFactory, this.appStmts); + this._addRenderNode(renderNode, appEl, ast.ngContentIndex, parent); + this.appElements.push(appEl); + return null; }; - StyleCompiler.prototype._shimIfNeeded = function(style, shim) { - return shim ? this._shadowCss.shimCssText(style, view_factory_1.CONTENT_ATTR, view_factory_1.HOST_ATTR) : style; + ViewBuilderVisitor.prototype.visitVariable = function(ast, ctx) { + return null; }; - StyleCompiler.prototype._createModuleUrl = function(stylesheetUrl, shim) { - return shim ? stylesheetUrl + ".shim" + util_1.MODULE_SUFFIX : "" + stylesheetUrl + util_1.MODULE_SUFFIX; + ViewBuilderVisitor.prototype.visitAttr = function(ast, ctx) { + return null; }; - StyleCompiler = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [xhr_1.XHR, url_resolver_1.UrlResolver])], StyleCompiler); - return StyleCompiler; + ViewBuilderVisitor.prototype.visitDirective = function(ast, ctx) { + return null; + }; + ViewBuilderVisitor.prototype.visitEvent = function(ast, ctx) { + return null; + }; + ViewBuilderVisitor.prototype.visitDirectiveProperty = function(ast, context) { + return null; + }; + ViewBuilderVisitor.prototype.visitElementProperty = function(ast, context) { + return null; + }; + return ViewBuilderVisitor; })(); - exports.StyleCompiler = StyleCompiler; + function codeGenEventHandler(view, boundElementIndex, eventName) { + return util_1.codeGenValueFn(['event'], view.expression + ".triggerEventHandlers(" + util_1.escapeValue(eventName) + ", event, " + boundElementIndex + ")"); + } + function codeGenViewFactoryName(component, embeddedTemplateIndex) { + return "viewFactory_" + component.type.name + embeddedTemplateIndex; + } + function codeGenViewEncapsulation(value) { + if (lang_1.IS_DART) { + return "" + proto_view_compiler_1.METADATA_MODULE_REF + value; + } else { + return "" + value; + } + } global.define = __define; return module.exports; }); @@ -22302,8 +22576,8 @@ System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", exports.HtmlToken = HtmlToken; var HtmlTokenError = (function(_super) { __extends(HtmlTokenError, _super); - function HtmlTokenError(errorMsg, tokenType, location) { - _super.call(this, location, errorMsg); + function HtmlTokenError(errorMsg, tokenType, span) { + _super.call(this, span, errorMsg); this.tokenType = tokenType; } return HtmlTokenError; @@ -22343,10 +22617,12 @@ System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", var $EQ = 61; var $GT = 62; var $QUESTION = 63; - var $A = 65; - var $Z = 90; var $LBRACKET = 91; var $RBRACKET = 93; + var $A = 65; + var $F = 70; + var $X = 88; + var $Z = 90; var $a = 97; var $f = 102; var $z = 122; @@ -22376,7 +22652,6 @@ System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", this.tokens = []; this.errors = []; this.input = file.content; - this.inputLowercase = file.content.toLowerCase(); this.length = file.content.length; this._advance(); } @@ -22387,16 +22662,16 @@ System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", while (this.peek !== $EOF) { var start = this._getLocation(); try { - if (this._attemptChar($LT)) { - if (this._attemptChar($BANG)) { - if (this._attemptChar($LBRACKET)) { + if (this._attemptCharCode($LT)) { + if (this._attemptCharCode($BANG)) { + if (this._attemptCharCode($LBRACKET)) { this._consumeCdata(start); - } else if (this._attemptChar($MINUS)) { + } else if (this._attemptCharCode($MINUS)) { this._consumeComment(start); } else { this._consumeDocType(start); } - } else if (this._attemptChar($SLASH)) { + } else if (this._attemptCharCode($SLASH)) { this._consumeTagClose(start); } else { this._consumeTagOpen(start); @@ -22419,6 +22694,15 @@ System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", _HtmlTokenizer.prototype._getLocation = function() { return new parse_util_1.ParseLocation(this.file, this.index, this.line, this.column); }; + _HtmlTokenizer.prototype._getSpan = function(start, end) { + if (lang_1.isBlank(start)) { + start = this._getLocation(); + } + if (lang_1.isBlank(end)) { + end = this._getLocation(); + } + return new parse_util_1.ParseSourceSpan(start, end); + }; _HtmlTokenizer.prototype._beginToken = function(type, start) { if (start === void 0) { start = null; @@ -22442,15 +22726,15 @@ System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", this.currentTokenType = null; return token; }; - _HtmlTokenizer.prototype._createError = function(msg, position) { - var error = new HtmlTokenError(msg, this.currentTokenType, position); + _HtmlTokenizer.prototype._createError = function(msg, span) { + var error = new HtmlTokenError(msg, this.currentTokenType, span); 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()); + throw this._createError(unexpectedCharacterErrorMsg($EOF), this._getSpan()); } if (this.peek === $LF) { this.line++; @@ -22459,45 +22743,60 @@ System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", this.column++; } this.index++; - this.peek = this.index >= this.length ? $EOF : lang_1.StringWrapper.charCodeAt(this.inputLowercase, this.index); + this.peek = this.index >= this.length ? $EOF : lang_1.StringWrapper.charCodeAt(this.input, this.index); }; - _HtmlTokenizer.prototype._attemptChar = function(charCode) { + _HtmlTokenizer.prototype._attemptCharCode = function(charCode) { if (this.peek === charCode) { this._advance(); return true; } return false; }; - _HtmlTokenizer.prototype._requireChar = function(charCode) { + _HtmlTokenizer.prototype._attemptCharCodeCaseInsensitive = function(charCode) { + if (compareCharCodeCaseInsensitive(this.peek, charCode)) { + this._advance(); + return true; + } + return false; + }; + _HtmlTokenizer.prototype._requireCharCode = function(charCode) { var location = this._getLocation(); - if (!this._attemptChar(charCode)) { - throw this._createError(unexpectedCharacterErrorMsg(this.peek), location); + if (!this._attemptCharCode(charCode)) { + throw this._createError(unexpectedCharacterErrorMsg(this.peek), this._getSpan(location, location)); + } + }; + _HtmlTokenizer.prototype._attemptStr = function(chars) { + for (var i = 0; i < chars.length; i++) { + if (!this._attemptCharCode(lang_1.StringWrapper.charCodeAt(chars, i))) { + return false; + } } + return true; }; - _HtmlTokenizer.prototype._attemptChars = function(chars) { + _HtmlTokenizer.prototype._attemptStrCaseInsensitive = function(chars) { for (var i = 0; i < chars.length; i++) { - if (!this._attemptChar(lang_1.StringWrapper.charCodeAt(chars, i))) { + if (!this._attemptCharCodeCaseInsensitive(lang_1.StringWrapper.charCodeAt(chars, i))) { return false; } } return true; }; - _HtmlTokenizer.prototype._requireChars = function(chars) { + _HtmlTokenizer.prototype._requireStr = function(chars) { var location = this._getLocation(); - if (!this._attemptChars(chars)) { - throw this._createError(unexpectedCharacterErrorMsg(this.peek), location); + if (!this._attemptStr(chars)) { + throw this._createError(unexpectedCharacterErrorMsg(this.peek), this._getSpan(location)); } }; - _HtmlTokenizer.prototype._attemptUntilFn = function(predicate) { + _HtmlTokenizer.prototype._attemptCharCodeUntilFn = function(predicate) { while (!predicate(this.peek)) { this._advance(); } }; - _HtmlTokenizer.prototype._requireUntilFn = function(predicate, len) { + _HtmlTokenizer.prototype._requireCharCodeUntilFn = function(predicate, len) { var start = this._getLocation(); - this._attemptUntilFn(predicate); + this._attemptCharCodeUntilFn(predicate); if (this.index - start.offset < len) { - throw this._createError(unexpectedCharacterErrorMsg(this.peek), start); + throw this._createError(unexpectedCharacterErrorMsg(this.peek), this._getSpan(start, start)); } }; _HtmlTokenizer.prototype._attemptUntilChar = function(char) { @@ -22517,12 +22816,12 @@ System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", _HtmlTokenizer.prototype._decodeEntity = function() { var start = this._getLocation(); this._advance(); - if (this._attemptChar($HASH)) { - var isHex = this._attemptChar($x); + if (this._attemptCharCode($HASH)) { + var isHex = this._attemptCharCode($x) || this._attemptCharCode($X); var numberStart = this._getLocation().offset; - this._attemptUntilFn(isDigitEntityEnd); + this._attemptCharCodeUntilFn(isDigitEntityEnd); if (this.peek != $SEMICOLON) { - throw this._createError(unexpectedCharacterErrorMsg(this.peek), this._getLocation()); + throw this._createError(unexpectedCharacterErrorMsg(this.peek), this._getSpan()); } this._advance(); var strNum = this.input.substring(numberStart, this.index - 1); @@ -22531,11 +22830,11 @@ System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", 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); + throw this._createError(unknownEntityErrorMsg(entity), this._getSpan(start)); } } else { var startPosition = this._savePosition(); - this._attemptUntilFn(isNamedEntityEnd); + this._attemptCharCodeUntilFn(isNamedEntityEnd); if (this.peek != $SEMICOLON) { this._restorePosition(startPosition); return '&'; @@ -22544,7 +22843,7 @@ System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", 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); + throw this._createError(unknownEntityErrorMsg(name_1), this._getSpan(start)); } return char; } @@ -22556,7 +22855,7 @@ System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", var parts = []; while (true) { tagCloseStart = this._getLocation(); - if (this._attemptChar(firstCharOfEnd) && attemptEndRest()) { + if (this._attemptCharCode(firstCharOfEnd) && attemptEndRest()) { break; } if (this.index > tagCloseStart.offset) { @@ -22571,10 +22870,10 @@ System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", _HtmlTokenizer.prototype._consumeComment = function(start) { var _this = this; this._beginToken(HtmlTokenType.COMMENT_START, start); - this._requireChar($MINUS); + this._requireCharCode($MINUS); this._endToken([]); var textToken = this._consumeRawText(false, $MINUS, function() { - return _this._attemptChars('->'); + return _this._attemptStr('->'); }); this._beginToken(HtmlTokenType.COMMENT_END, textToken.sourceSpan.end); this._endToken([]); @@ -22582,10 +22881,10 @@ System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", _HtmlTokenizer.prototype._consumeCdata = function(start) { var _this = this; this._beginToken(HtmlTokenType.CDATA_START, start); - this._requireChars('cdata['); + this._requireStr('CDATA['); this._endToken([]); var textToken = this._consumeRawText(false, $RBRACKET, function() { - return _this._attemptChars(']>'); + return _this._attemptStr(']>'); }); this._beginToken(HtmlTokenType.CDATA_END, textToken.sourceSpan.end); this._endToken([]); @@ -22610,7 +22909,7 @@ System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", } else { nameStart = nameOrPrefixStart; } - this._requireUntilFn(isNameEnd, this.index === nameStart ? 1 : 0); + this._requireCharCodeUntilFn(isNameEnd, this.index === nameStart ? 1 : 0); var name = this.input.substring(nameStart, this.index); return [prefix, name]; }; @@ -22619,20 +22918,20 @@ System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", var lowercaseTagName; try { if (!isAsciiLetter(this.peek)) { - throw this._createError(unexpectedCharacterErrorMsg(this.peek), this._getLocation()); + throw this._createError(unexpectedCharacterErrorMsg(this.peek), this._getSpan()); } var nameStart = this.index; this._consumeTagOpenStart(start); - lowercaseTagName = this.inputLowercase.substring(nameStart, this.index); - this._attemptUntilFn(isNotWhitespace); + lowercaseTagName = this.input.substring(nameStart, this.index).toLowerCase(); + this._attemptCharCodeUntilFn(isNotWhitespace); while (this.peek !== $SLASH && this.peek !== $GT) { this._consumeAttributeName(); - this._attemptUntilFn(isNotWhitespace); - if (this._attemptChar($EQ)) { - this._attemptUntilFn(isNotWhitespace); + this._attemptCharCodeUntilFn(isNotWhitespace); + if (this._attemptCharCode($EQ)) { + this._attemptCharCodeUntilFn(isNotWhitespace); this._consumeAttributeValue(); } - this._attemptUntilFn(isNotWhitespace); + this._attemptCharCodeUntilFn(isNotWhitespace); } this._consumeTagOpenEnd(); } catch (e) { @@ -22654,13 +22953,13 @@ System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", _HtmlTokenizer.prototype._consumeRawTextWithTagClose = function(lowercaseTagName, decodeEntities) { var _this = this; var textToken = this._consumeRawText(decodeEntities, $LT, function() { - if (!_this._attemptChar($SLASH)) + if (!_this._attemptCharCode($SLASH)) return false; - _this._attemptUntilFn(isNotWhitespace); - if (!_this._attemptChars(lowercaseTagName)) + _this._attemptCharCodeUntilFn(isNotWhitespace); + if (!_this._attemptStrCaseInsensitive(lowercaseTagName)) return false; - _this._attemptUntilFn(isNotWhitespace); - if (!_this._attemptChar($GT)) + _this._attemptCharCodeUntilFn(isNotWhitespace); + if (!_this._attemptCharCode($GT)) return false; return true; }); @@ -22691,24 +22990,24 @@ System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", this._advance(); } else { var valueStart = this.index; - this._requireUntilFn(isNameEnd, 1); + this._requireCharCodeUntilFn(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; + var tokenType = this._attemptCharCode($SLASH) ? HtmlTokenType.TAG_OPEN_END_VOID : HtmlTokenType.TAG_OPEN_END; this._beginToken(tokenType); - this._requireChar($GT); + this._requireCharCode($GT); this._endToken([]); }; _HtmlTokenizer.prototype._consumeTagClose = function(start) { this._beginToken(HtmlTokenType.TAG_CLOSE, start); - this._attemptUntilFn(isNotWhitespace); + this._attemptCharCodeUntilFn(isNotWhitespace); var prefixAndName; prefixAndName = this._consumePrefixAndName(); - this._attemptUntilFn(isNotWhitespace); - this._requireChar($GT); + this._attemptCharCodeUntilFn(isNotWhitespace); + this._requireCharCode($GT); this._endToken(prefixAndName); }; _HtmlTokenizer.prototype._consumeText = function() { @@ -22757,10 +23056,16 @@ System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", return code === $LT || code === $EOF; } function isAsciiLetter(code) { - return code >= $a && code <= $z; + return code >= $a && code <= $z || code >= $A && code <= $Z; } function isAsciiHexDigit(code) { - return code >= $a && code <= $f || code >= $0 && code <= $9; + return code >= $a && code <= $f || code >= $A && code <= $F || code >= $0 && code <= $9; + } + function compareCharCodeCaseInsensitive(code1, code2) { + return toUpperCaseCharCode(code1) == toUpperCaseCharCode(code2); + } + function toUpperCaseCharCode(code) { + return code >= $a && code <= $z ? code - $a + $A : code; } function mergeTextTokens(srcTokens) { var dstTokens = []; @@ -22781,36 +23086,239 @@ System.register("angular2/src/compiler/html_lexer", ["angular2/src/facade/lang", 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) { +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/pipe_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/assertions", "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 pipe_resolver_1 = require("angular2/src/core/linker/pipe_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 assertions_1 = require("angular2/src/compiler/assertions"); + var url_resolver_1 = require("angular2/src/compiler/url_resolver"); + var RuntimeMetadataResolver = (function() { + function RuntimeMetadataResolver(_directiveResolver, _pipeResolver, _viewResolver, _platformDirectives, _platformPipes) { + this._directiveResolver = _directiveResolver; + this._pipeResolver = _pipeResolver; + this._viewResolver = _viewResolver; + this._platformDirectives = _platformDirectives; + this._platformPipes = _platformPipes; + this._directiveCache = new Map(); + this._pipeCache = new Map(); + this._anonymousTypes = new Map(); + this._anonymousTypeIndex = 0; + } + RuntimeMetadataResolver.prototype.sanitizeName = function(obj) { + var result = lang_1.stringify(obj); + if (result.indexOf('(') < 0) { + return result; + } + var found = this._anonymousTypes.get(obj); + if (!found) { + this._anonymousTypes.set(obj, this._anonymousTypeIndex++); + found = this._anonymousTypes.get(obj); + } + return "anonymous_type_" + found + "_"; + }; + RuntimeMetadataResolver.prototype.getDirectiveMetadata = function(directiveType) { + var meta = this._directiveCache.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) { + assertions_1.assertArrayOfStrings('styles', dirMeta.styles); + var cmpMeta = dirMeta; + moduleUrl = calcModuleUrl(directiveType, cmpMeta); + var viewMeta = this._viewResolver.resolve(directiveType); + assertions_1.assertArrayOfStrings('styles', viewMeta.styles); + 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: this.sanitizeName(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._directiveCache.set(directiveType, meta); + } + return meta; + }; + RuntimeMetadataResolver.prototype.getPipeMetadata = function(pipeType) { + var meta = this._pipeCache.get(pipeType); + if (lang_1.isBlank(meta)) { + var pipeMeta = this._pipeResolver.resolve(pipeType); + var moduleUrl = reflection_1.reflector.importUri(pipeType); + meta = new cpl.CompilePipeMetadata({ + type: new cpl.CompileTypeMetadata({ + name: this.sanitizeName(pipeType), + moduleUrl: moduleUrl, + runtime: pipeType + }), + name: pipeMeta.name, + pure: pipeMeta.pure + }); + this._pipeCache.set(pipeType, 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 (!isValidType(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.getDirectiveMetadata(type); + }); + }; + RuntimeMetadataResolver.prototype.getViewPipesMetadata = function(component) { + var _this = this; + var view = this._viewResolver.resolve(component); + var pipes = flattenPipes(view, this._platformPipes); + for (var i = 0; i < pipes.length; i++) { + if (!isValidType(pipes[i])) { + throw new exceptions_1.BaseException("Unexpected piped value '" + lang_1.stringify(pipes[i]) + "' on the View of component '" + lang_1.stringify(component) + "'"); + } + } + return pipes.map(function(type) { + return _this.getPipeMetadata(type); + }); + }; + RuntimeMetadataResolver = __decorate([di_2.Injectable(), __param(3, di_2.Optional()), __param(3, di_2.Inject(platform_directives_and_pipes_1.PLATFORM_DIRECTIVES)), __param(4, di_2.Optional()), __param(4, di_2.Inject(platform_directives_and_pipes_1.PLATFORM_PIPES)), __metadata('design:paramtypes', [directive_resolver_1.DirectiveResolver, pipe_resolver_1.PipeResolver, view_resolver_1.ViewResolver, Array, 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 flattenPipes(view, platformPipes) { + var pipes = []; + if (lang_1.isPresent(platformPipes)) { + flattenArray(platformPipes, pipes); + } + if (lang_1.isPresent(view.pipes)) { + flattenArray(view.pipes, pipes); + } + return pipes; + } + 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 isValidType(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/common/pipes", ["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", "angular2/src/common/pipes/replace_pipe", "angular2/src/common/pipes/i18n_plural_pipe", "angular2/src/common/pipes/i18n_select_pipe", "angular2/src/common/pipes/common_pipes"], 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"); + exports.AsyncPipe = async_pipe_1.AsyncPipe; + var date_pipe_1 = require("angular2/src/common/pipes/date_pipe"); + exports.DatePipe = date_pipe_1.DatePipe; var json_pipe_1 = require("angular2/src/common/pipes/json_pipe"); + exports.JsonPipe = json_pipe_1.JsonPipe; var slice_pipe_1 = require("angular2/src/common/pipes/slice_pipe"); - var date_pipe_1 = require("angular2/src/common/pipes/date_pipe"); + exports.SlicePipe = slice_pipe_1.SlicePipe; + var lowercase_pipe_1 = require("angular2/src/common/pipes/lowercase_pipe"); + exports.LowerCasePipe = lowercase_pipe_1.LowerCasePipe; 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]); + exports.NumberPipe = number_pipe_1.NumberPipe; + exports.DecimalPipe = number_pipe_1.DecimalPipe; + exports.PercentPipe = number_pipe_1.PercentPipe; + exports.CurrencyPipe = number_pipe_1.CurrencyPipe; + var uppercase_pipe_1 = require("angular2/src/common/pipes/uppercase_pipe"); + exports.UpperCasePipe = uppercase_pipe_1.UpperCasePipe; + var replace_pipe_1 = require("angular2/src/common/pipes/replace_pipe"); + exports.ReplacePipe = replace_pipe_1.ReplacePipe; + var i18n_plural_pipe_1 = require("angular2/src/common/pipes/i18n_plural_pipe"); + exports.I18nPluralPipe = i18n_plural_pipe_1.I18nPluralPipe; + var i18n_select_pipe_1 = require("angular2/src/common/pipes/i18n_select_pipe"); + exports.I18nSelectPipe = i18n_select_pipe_1.I18nSelectPipe; + var common_pipes_1 = require("angular2/src/common/pipes/common_pipes"); + exports.COMMON_PIPES = common_pipes_1.COMMON_PIPES; global.define = __define; return module.exports; }); @@ -23040,94 +23548,6 @@ System.register("angular2/src/platform/browser/tools/tools", ["angular2/src/faca 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; @@ -23166,12 +23586,12 @@ System.register("angular2/src/compiler/html_parser", ["angular2/src/facade/lang" 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); + function HtmlTreeError(elementName, span, msg) { + _super.call(this, span, msg); this.elementName = elementName; } - HtmlTreeError.create = function(elementName, location, msg) { - return new HtmlTreeError(elementName, location, msg); + HtmlTreeError.create = function(elementName, span, msg) { + return new HtmlTreeError(elementName, span, msg); }; return HtmlTreeError; })(parse_util_1.ParseError); @@ -23243,9 +23663,11 @@ System.register("angular2/src/compiler/html_parser", ["angular2/src/facade/lang" 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); + TreeBuilder.prototype._consumeComment = function(token) { + var text = this._advanceIf(html_lexer_1.HtmlTokenType.RAW_TEXT); this._advanceIf(html_lexer_1.HtmlTokenType.COMMENT_END); + var value = lang_1.isPresent(text) ? text.parts[0].trim() : null; + this._addToParent(new html_ast_1.HtmlCommentAst(value, token.sourceSpan)); }; TreeBuilder.prototype._consumeText = function(token) { var text = token.parts[0]; @@ -23280,17 +23702,19 @@ System.register("angular2/src/compiler/html_parser", ["angular2/src/facade/lang" 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] + "\"")); + this.errors.push(HtmlTreeError.create(fullName, startTagToken.sourceSpan, "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)); + var span = new parse_util_1.ParseSourceSpan(startTagToken.sourceSpan.start, end); + var el = new html_ast_1.HtmlElementAst(fullName, attrs, [], span, span, null); this._pushElement(el); if (selfClosing) { this._popElement(fullName); + el.endSourceSpan = span; } }; TreeBuilder.prototype._pushElement = function(el) { @@ -23303,7 +23727,7 @@ System.register("angular2/src/compiler/html_parser", ["angular2/src/facade/lang" 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); + var newParent = new html_ast_1.HtmlElementAst(tagDef.parentToAdd, [], [el], el.sourceSpan, el.startSourceSpan, el.endSourceSpan); this._addToParent(newParent); this.elementStack.push(newParent); this.elementStack.push(el); @@ -23314,10 +23738,11 @@ System.register("angular2/src/compiler/html_parser", ["angular2/src/facade/lang" }; TreeBuilder.prototype._consumeEndTag = function(endTagToken) { var fullName = getElementFullName(endTagToken.parts[0], endTagToken.parts[1], this._getParentElement()); + this._getParentElement().endSourceSpan = endTagToken.sourceSpan; 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] + "\"")); + this.errors.push(HtmlTreeError.create(fullName, endTagToken.sourceSpan, "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] + "\"")); + this.errors.push(HtmlTreeError.create(fullName, endTagToken.sourceSpan, "Unexpected closing tag \"" + endTagToken.parts[1] + "\"")); } }; TreeBuilder.prototype._popElement = function(fullName) { @@ -23334,7 +23759,7 @@ System.register("angular2/src/compiler/html_parser", ["angular2/src/facade/lang" return false; }; TreeBuilder.prototype._consumeAttr = function(attrName) { - var fullName = mergeNsAndName(attrName.parts[0], attrName.parts[1]); + var fullName = html_tags_1.mergeNsAndName(attrName.parts[0], attrName.parts[1]); var end = attrName.sourceSpan.end; var value = ''; if (this.peek.type === html_lexer_1.HtmlTokenType.ATTR_VALUE) { @@ -23357,9 +23782,6 @@ System.register("angular2/src/compiler/html_parser", ["angular2/src/facade/lang" }; 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; @@ -23367,13 +23789,13 @@ System.register("angular2/src/compiler/html_parser", ["angular2/src/facade/lang" prefix = html_tags_1.getNsPrefix(parentElement.name); } } - return mergeNsAndName(prefix, localName); + return html_tags_1.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) { +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", "angular2/src/common/forms/form_builder", "angular2/src/common/forms/directives/radio_control_value_accessor", "angular2/src/facade/lang"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -23413,6 +23835,7 @@ System.register("angular2/src/common/forms", ["angular2/src/common/forms/model", exports.SelectControlValueAccessor = select_control_value_accessor_1.SelectControlValueAccessor; var directives_1 = require("angular2/src/common/forms/directives"); exports.FORM_DIRECTIVES = directives_1.FORM_DIRECTIVES; + exports.RadioButtonState = directives_1.RadioButtonState; 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; @@ -23421,10 +23844,14 @@ System.register("angular2/src/common/forms", ["angular2/src/common/forms/model", exports.RequiredValidator = validators_2.RequiredValidator; exports.MinLengthValidator = validators_2.MinLengthValidator; exports.MaxLengthValidator = validators_2.MaxLengthValidator; + exports.PatternValidator = validators_2.PatternValidator; 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; + var form_builder_2 = require("angular2/src/common/forms/form_builder"); + var radio_control_value_accessor_1 = require("angular2/src/common/forms/directives/radio_control_value_accessor"); + var lang_1 = require("angular2/src/facade/lang"); + exports.FORM_PROVIDERS = lang_1.CONST_EXPR([form_builder_2.FormBuilder, radio_control_value_accessor_1.RadioControlRegistry]); + exports.FORM_BINDINGS = exports.FORM_PROVIDERS; global.define = __define; return module.exports; }); @@ -23774,9 +24201,15 @@ System.register("angular2/src/platform/browser/browser_adapter", ["angular2/src/ BrowserDomAdapter.prototype.hasAttribute = function(element, attribute) { return element.hasAttribute(attribute); }; + BrowserDomAdapter.prototype.hasAttributeNS = function(element, ns, attribute) { + return element.hasAttributeNS(ns, attribute); + }; BrowserDomAdapter.prototype.getAttribute = function(element, attribute) { return element.getAttribute(attribute); }; + BrowserDomAdapter.prototype.getAttributeNS = function(element, ns, name) { + return element.getAttributeNS(ns, name); + }; BrowserDomAdapter.prototype.setAttribute = function(element, name, value) { element.setAttribute(name, value); }; @@ -23786,6 +24219,9 @@ System.register("angular2/src/platform/browser/browser_adapter", ["angular2/src/ BrowserDomAdapter.prototype.removeAttribute = function(element, attribute) { element.removeAttribute(attribute); }; + BrowserDomAdapter.prototype.removeAttributeNS = function(element, ns, name) { + element.removeAttributeNS(ns, name); + }; BrowserDomAdapter.prototype.templateAwareRoot = function(el) { return this.isTemplateElement(el) ? this.content(el) : el; }; @@ -23956,7 +24392,7 @@ System.register("angular2/src/platform/browser/browser_adapter", ["angular2/src/ 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) { +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/core/change_detection/parser/ast", "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; @@ -23999,6 +24435,7 @@ System.register("angular2/src/compiler/template_parser", ["angular2/src/facade/c 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 ast_1 = require("angular2/src/core/change_detection/parser/ast"); 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"); @@ -24019,8 +24456,8 @@ System.register("angular2/src/compiler/template_parser", ["angular2/src/facade/c 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); + function TemplateParseError(message, span) { + _super.call(this, span, message); } return TemplateParseError; })(parse_util_1.ParseError); @@ -24032,8 +24469,8 @@ System.register("angular2/src/compiler/template_parser", ["angular2/src/facade/c this._htmlParser = _htmlParser; this.transforms = transforms; } - TemplateParser.prototype.parse = function(template, directives, templateUrl) { - var parseVisitor = new TemplateParseVisitor(directives, this._exprParser, this._schemaRegistry); + TemplateParser.prototype.parse = function(template, directives, pipes, templateUrl) { + var parseVisitor = new TemplateParseVisitor(directives, pipes, 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); @@ -24053,7 +24490,7 @@ System.register("angular2/src/compiler/template_parser", ["angular2/src/facade/c })(); exports.TemplateParser = TemplateParser; var TemplateParseVisitor = (function() { - function TemplateParseVisitor(directives, _exprParser, _schemaRegistry) { + function TemplateParseVisitor(directives, pipes, _exprParser, _schemaRegistry) { var _this = this; this._exprParser = _exprParser; this._schemaRegistry = _schemaRegistry; @@ -24066,14 +24503,20 @@ System.register("angular2/src/compiler/template_parser", ["angular2/src/facade/c _this.selectorMatcher.addSelectables(selector, directive); _this.directivesIndex.set(directive, index); }); + this.pipesByName = new Map(); + pipes.forEach(function(pipe) { + return _this.pipesByName.set(pipe.name, pipe); + }); } TemplateParseVisitor.prototype._reportError = function(message, sourceSpan) { - this.errors.push(new TemplateParseError(message, sourceSpan.start)); + this.errors.push(new TemplateParseError(message, sourceSpan)); }; TemplateParseVisitor.prototype._parseInterpolation = function(value, sourceSpan) { var sourceInfo = sourceSpan.start.toString(); try { - return this._exprParser.parseInterpolation(value, sourceInfo); + var ast = this._exprParser.parseInterpolation(value, sourceInfo); + this._checkPipes(ast, sourceSpan); + return ast; } catch (e) { this._reportError("" + e, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); @@ -24082,7 +24525,9 @@ System.register("angular2/src/compiler/template_parser", ["angular2/src/facade/c TemplateParseVisitor.prototype._parseAction = function(value, sourceSpan) { var sourceInfo = sourceSpan.start.toString(); try { - return this._exprParser.parseAction(value, sourceInfo); + var ast = this._exprParser.parseAction(value, sourceInfo); + this._checkPipes(ast, sourceSpan); + return ast; } catch (e) { this._reportError("" + e, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); @@ -24091,21 +24536,42 @@ System.register("angular2/src/compiler/template_parser", ["angular2/src/facade/c TemplateParseVisitor.prototype._parseBinding = function(value, sourceSpan) { var sourceInfo = sourceSpan.start.toString(); try { - return this._exprParser.parseBinding(value, sourceInfo); + var ast = this._exprParser.parseBinding(value, sourceInfo); + this._checkPipes(ast, sourceSpan); + return ast; } catch (e) { this._reportError("" + e, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); } }; TemplateParseVisitor.prototype._parseTemplateBindings = function(value, sourceSpan) { + var _this = this; var sourceInfo = sourceSpan.start.toString(); try { - return this._exprParser.parseTemplateBindings(value, sourceInfo); + var bindings = this._exprParser.parseTemplateBindings(value, sourceInfo); + bindings.forEach(function(binding) { + if (lang_1.isPresent(binding.expression)) { + _this._checkPipes(binding.expression, sourceSpan); + } + }); + return bindings; } catch (e) { this._reportError("" + e, sourceSpan); return []; } }; + TemplateParseVisitor.prototype._checkPipes = function(ast, sourceSpan) { + var _this = this; + if (lang_1.isPresent(ast)) { + var collector = new PipeCollector(); + ast.visit(collector); + collector.pipes.forEach(function(pipeName) { + if (!_this.pipesByName.has(pipeName)) { + _this._reportError("The pipe '" + pipeName + "' could not be found", sourceSpan); + } + }); + } + }; TemplateParseVisitor.prototype.visitText = function(ast, component) { var ngContentIndex = component.findNgContentIndex(TEXT_CSS_SELECTOR); var expr = this._parseInterpolation(ast.value, ast.sourceSpan); @@ -24118,6 +24584,9 @@ System.register("angular2/src/compiler/template_parser", ["angular2/src/facade/c TemplateParseVisitor.prototype.visitAttr = function(ast, contex) { return new template_ast_1.AttrAst(ast.name, ast.value, ast.sourceSpan); }; + TemplateParseVisitor.prototype.visitComment = function(ast, context) { + return null; + }; TemplateParseVisitor.prototype.visitElement = function(element, component) { var _this = this; var nodeName = element.name; @@ -24138,11 +24607,11 @@ System.register("angular2/src/compiler/template_parser", ["angular2/src/facade/c 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)); + matchableAttrs.push([attr.name, attr.value]); } if (hasTemplateBinding) { hasInlineTemplates = true; @@ -24154,30 +24623,32 @@ System.register("angular2/src/compiler/template_parser", ["angular2/src/facade/c 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 projectionSelector = lang_1.isPresent(preparsedElement.projectAs) ? selector_1.CssSelector.parse(preparsedElement.projectAs)[0] : elementCssSelector; + var ngContentIndex = component.findNgContentIndex(projectionSelector); 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); + parsedElement = new template_ast_1.NgContentAst(this.ngContentCount++, hasInlineTemplates ? null : ngContentIndex, 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); + parsedElement = new template_ast_1.EmbeddedTemplateAst(attrs, events, vars, directives, children, hasInlineTemplates ? null : ngContentIndex, 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); + var ngContentIndex_1 = hasInlineTemplates ? null : component.findNgContentIndex(projectionSelector); + parsedElement = new template_ast_1.ElementAst(nodeName, attrs, elementProps, events, elementExportAsVars, directives, children, hasInlineTemplates ? null : ngContentIndex_1, 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); + parsedElement = new template_ast_1.EmbeddedTemplateAst([], [], templateVars, templateDirectives, [parsedElement], ngContentIndex, element.sourceSpan); } return parsedElement; }; @@ -24271,7 +24742,9 @@ System.register("angular2/src/compiler/template_parser", ["angular2/src/facade/c 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)); + var ast = this._parseAction(expression, sourceSpan); + targetMatchableAttrs.push([name, ast.source]); + targetEvents.push(new template_ast_1.BoundEventAst(eventName, target, ast, sourceSpan)); }; TemplateParseVisitor.prototype._parseLiteralAttr = function(name, value, sourceSpan, targetProps) { targetProps.push(new BoundElementOrDirectiveProperty(name, this._exprParser.wrapLiteralPrimitive(value, ''), true, sourceSpan)); @@ -24385,6 +24858,12 @@ System.register("angular2/src/compiler/template_parser", ["angular2/src/facade/c } else { if (parts[0] == ATTRIBUTE_PREFIX) { boundPropertyName = parts[1]; + var nsSeparatorIdx = boundPropertyName.indexOf(':'); + if (nsSeparatorIdx > -1) { + var ns = boundPropertyName.substring(0, nsSeparatorIdx); + var name_1 = boundPropertyName.substring(nsSeparatorIdx + 1); + boundPropertyName = html_tags_1.mergeNsAndName(ns, name_1); + } bindingType = template_ast_1.PropertyBindingType.Attribute; } else if (parts[0] == CLASS_PREFIX) { boundPropertyName = parts[1]; @@ -24457,6 +24936,9 @@ System.register("angular2/src/compiler/template_parser", ["angular2/src/facade/c 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.visitComment = function(ast, context) { + return null; + }; NonBindableVisitor.prototype.visitAttr = function(ast, context) { return new template_ast_1.AttrAst(ast.name, ast.value, ast.sourceSpan); }; @@ -24534,6 +25016,21 @@ System.register("angular2/src/compiler/template_parser", ["angular2/src/facade/c } var EMPTY_COMPONENT = new Component(new selector_1.SelectorMatcher(), null); var NON_BINDABLE_VISITOR = new NonBindableVisitor(); + var PipeCollector = (function(_super) { + __extends(PipeCollector, _super); + function PipeCollector() { + _super.apply(this, arguments); + this.pipes = new Set(); + } + PipeCollector.prototype.visitPipe = function(ast) { + this.pipes.add(ast.name); + ast.exp.visit(this); + this.visitAll(ast.args); + return null; + }; + return PipeCollector; + })(ast_1.RecursiveAstVisitor); + exports.PipeCollector = PipeCollector; global.define = __define; return module.exports; }); @@ -24555,7 +25052,7 @@ System.register("angular2/common", ["angular2/src/common/pipes", "angular2/src/c 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) { +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/compiler/directive_metadata", "angular2/src/compiler/template_ast", "angular2/src/core/di", "angular2/src/compiler/source_module", "angular2/src/compiler/change_detector_compiler", "angular2/src/compiler/style_compiler", "angular2/src/compiler/view_compiler", "angular2/src/compiler/proto_view_compiler", "angular2/src/compiler/template_parser", "angular2/src/compiler/template_normalizer", "angular2/src/compiler/runtime_metadata", "angular2/src/core/linker/view", "angular2/src/core/change_detection/change_detection", "angular2/src/core/linker/resolved_metadata_cache", "angular2/src/compiler/util"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -24579,30 +25076,36 @@ System.register("angular2/src/compiler/template_compiler", ["angular2/src/facade 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 template_ast_1 = require("angular2/src/compiler/template_ast"); 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 view_compiler_1 = require("angular2/src/compiler/view_compiler"); + var proto_view_compiler_1 = require("angular2/src/compiler/proto_view_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 view_1 = require("angular2/src/core/linker/view"); + var change_detection_1 = require("angular2/src/core/change_detection/change_detection"); + var resolved_metadata_cache_1 = require("angular2/src/core/linker/resolved_metadata_cache"); var util_1 = require("angular2/src/compiler/util"); + exports.METADATA_CACHE_MODULE_REF = source_module_1.moduleRef('package:angular2/src/core/linker/resolved_metadata_cache' + util_1.MODULE_SUFFIX); var TemplateCompiler = (function() { - function TemplateCompiler(_runtimeMetadataResolver, _templateNormalizer, _templateParser, _styleCompiler, _commandCompiler, _cdCompiler) { + function TemplateCompiler(_runtimeMetadataResolver, _templateNormalizer, _templateParser, _styleCompiler, _cdCompiler, _protoViewCompiler, _viewCompiler, _resolvedMetadataCache, _genConfig) { this._runtimeMetadataResolver = _runtimeMetadataResolver; this._templateNormalizer = _templateNormalizer; this._templateParser = _templateParser; this._styleCompiler = _styleCompiler; - this._commandCompiler = _commandCompiler; this._cdCompiler = _cdCompiler; + this._protoViewCompiler = _protoViewCompiler; + this._viewCompiler = _viewCompiler; + this._resolvedMetadataCache = _resolvedMetadataCache; + this._genConfig = _genConfig; this._hostCacheKeys = new Map(); this._compiledTemplateCache = new Map(); this._compiledTemplateDone = new Map(); - this._nextTemplateId = 0; } TemplateCompiler.prototype.normalizeDirectiveMetadata = function(directive) { if (!directive.isComponent) { @@ -24622,175 +25125,192 @@ System.register("angular2/src/compiler/template_compiler", ["angular2/src/facade hostProperties: directive.hostProperties, hostAttributes: directive.hostAttributes, lifecycleHooks: directive.lifecycleHooks, + providers: directive.providers, template: normalizedTemplate }); }); }; TemplateCompiler.prototype.compileHostComponentRuntime = function(type) { + var compMeta = this._runtimeMetadataResolver.getDirectiveMetadata(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()); + this._compileComponentRuntime(hostCacheKey, hostMeta, [compMeta], [], []); } return this._compiledTemplateDone.get(hostCacheKey).then(function(compiledTemplate) { - return new template_commands_1.CompiledHostTemplate(compiledTemplate); + return new view_1.HostViewFactory(compMeta.selector, compiledTemplate.viewFactory); }); }; TemplateCompiler.prototype.clearCache = function() { - this._hostCacheKeys.clear(); this._styleCompiler.clearCache(); this._compiledTemplateCache.clear(); this._compiledTemplateDone.clear(); + this._hostCacheKeys.clear(); + }; + TemplateCompiler.prototype.compileTemplatesCodeGen = function(components) { + var _this = this; + if (components.length === 0) { + throw new exceptions_1.BaseException('No components given'); + } + var declarations = []; + components.forEach(function(componentWithDirs) { + var compMeta = componentWithDirs.component; + assertComponent(compMeta); + _this._compileComponentCodeGen(compMeta, componentWithDirs.directives, componentWithDirs.pipes, declarations); + if (compMeta.dynamicLoadable) { + var hostMeta = directive_metadata_1.createHostComponentMeta(compMeta.type, compMeta.selector); + var viewFactoryExpression = _this._compileComponentCodeGen(hostMeta, [compMeta], [], declarations); + var constructionKeyword = lang_1.IS_DART ? 'const' : 'new'; + var compiledTemplateExpr = constructionKeyword + " " + proto_view_compiler_1.APP_VIEW_MODULE_REF + "HostViewFactory('" + compMeta.selector + "'," + viewFactoryExpression + ")"; + var varName = codeGenHostViewFactoryName(compMeta.type); + declarations.push("" + util_1.codeGenExportVariable(varName) + compiledTemplateExpr + ";"); + } + }); + 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._compileComponentRuntime = function(cacheKey, compMeta, viewDirectives, compilingComponentCacheKeys) { + TemplateCompiler.prototype._compileComponentRuntime = function(cacheKey, compMeta, viewDirectives, pipes, compilingComponentsPath) { var _this = this; var uniqViewDirectives = removeDuplicates(viewDirectives); + var uniqViewPipes = removeDuplicates(pipes); 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); + compiledTemplate = new CompiledTemplate(); 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 styles = stylesAndNormalizedViewDirMetas[0]; + var parsedTemplate = _this._templateParser.parse(compMeta.template.template, normalizedViewDirMetas, uniqViewPipes, compMeta.type.name); + var childPromises = []; + var usedDirectives = DirectiveCollector.findUsedDirectives(parsedTemplate); + usedDirectives.components.forEach(function(component) { + return _this._compileNestedComponentRuntime(component, compilingComponentsPath, childPromises); }); - 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(_) { + var filteredPipes = filterPipes(parsedTemplate, uniqViewPipes); + compiledTemplate.init(_this._createViewFactoryRuntime(compMeta, parsedTemplate, usedDirectives.directives, styles, filteredPipes)); + return compiledTemplate; }); - 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._compileNestedComponentRuntime = function(childComponentDir, parentCompilingComponentsPath, childPromises) { + var compilingComponentsPath = collection_1.ListWrapper.clone(parentCompilingComponentsPath); + var childCacheKey = childComponentDir.type.runtime; + var childViewDirectives = this._runtimeMetadataResolver.getViewDirectivesMetadata(childComponentDir.type.runtime); + var childViewPipes = this._runtimeMetadataResolver.getViewPipesMetadata(childComponentDir.type.runtime); + var childIsRecursive = collection_1.ListWrapper.contains(compilingComponentsPath, childCacheKey); + compilingComponentsPath.push(childCacheKey); + this._compileComponentRuntime(childCacheKey, childComponentDir, childViewDirectives, childViewPipes, compilingComponentsPath); + if (!childIsRecursive) { + childPromises.push(this._compiledTemplateDone.get(childCacheKey)); + } }; - TemplateCompiler.prototype.compileTemplatesCodeGen = function(components) { + TemplateCompiler.prototype._createViewFactoryRuntime = function(compMeta, parsedTemplate, directives, styles, pipes) { var _this = this; - if (components.length === 0) { - throw new exceptions_1.BaseException('No components given'); + if (lang_1.IS_DART || !this._genConfig.useJit) { + var changeDetectorFactories = this._cdCompiler.compileComponentRuntime(compMeta.type, compMeta.changeDetection, parsedTemplate); + var protoViews = this._protoViewCompiler.compileProtoViewRuntime(this._resolvedMetadataCache, compMeta, parsedTemplate, pipes); + return this._viewCompiler.compileComponentRuntime(compMeta, parsedTemplate, styles, protoViews.protoViews, changeDetectorFactories, function(compMeta) { + return _this._getNestedComponentViewFactory(compMeta); + }); + } else { + var declarations = []; + var viewFactoryExpr = this._createViewFactoryCodeGen('resolvedMetadataCache', compMeta, new source_module_1.SourceExpression([], 'styles'), parsedTemplate, pipes, declarations); + var vars = { + 'exports': {}, + 'styles': styles, + 'resolvedMetadataCache': this._resolvedMetadataCache + }; + directives.forEach(function(dirMeta) { + vars[dirMeta.type.name] = dirMeta.type.runtime; + if (dirMeta.isComponent && dirMeta.type.runtime !== compMeta.type.runtime) { + vars[("viewFactory_" + dirMeta.type.name + "0")] = _this._getNestedComponentViewFactory(dirMeta); + } + }); + pipes.forEach(function(pipeMeta) { + return vars[pipeMeta.type.name] = pipeMeta.type.runtime; + }); + var declarationsWithoutImports = source_module_1.SourceModule.getSourceWithoutImports(declarations.join('\n')); + return lang_1.evalExpression("viewFactory_" + compMeta.type.name, viewFactoryExpr, declarationsWithoutImports, mergeStringMaps([vars, change_detector_compiler_1.CHANGE_DETECTION_JIT_IMPORTS, proto_view_compiler_1.PROTO_VIEW_JIT_IMPORTS, view_compiler_1.VIEW_JIT_IMPORTS])); } - 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._getNestedComponentViewFactory = function(compMeta) { + return this._compiledTemplateCache.get(compMeta.type.runtime).viewFactory; }; - TemplateCompiler.prototype._processTemplateCodeGen = function(compMeta, directives, targetDeclarations, targetTemplateArguments) { + TemplateCompiler.prototype._compileComponentCodeGen = function(compMeta, directives, pipes, targetDeclarations) { var uniqueDirectives = removeDuplicates(directives); + var uniqPipes = removeDuplicates(pipes); 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]); + var parsedTemplate = this._templateParser.parse(compMeta.template.template, uniqueDirectives, uniqPipes, compMeta.type.name); + var filteredPipes = filterPipes(parsedTemplate, uniqPipes); + return this._createViewFactoryCodeGen(exports.METADATA_CACHE_MODULE_REF + "CODEGEN_RESOLVED_METADATA_CACHE", compMeta, styleExpr, parsedTemplate, filteredPipes, targetDeclarations); }; - 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); + TemplateCompiler.prototype._createViewFactoryCodeGen = function(resolvedMetadataCacheExpr, compMeta, styleExpr, parsedTemplate, pipes, targetDeclarations) { + var changeDetectorsExprs = this._cdCompiler.compileComponentCodeGen(compMeta.type, compMeta.changeDetection, parsedTemplate); + var protoViewExprs = this._protoViewCompiler.compileProtoViewCodeGen(new util_1.Expression(resolvedMetadataCacheExpr), compMeta, parsedTemplate, pipes); + var viewFactoryExpr = this._viewCompiler.compileComponentCodeGen(compMeta, parsedTemplate, styleExpr, protoViewExprs.protoViews, changeDetectorsExprs, codeGenComponentViewFactoryName); + util_1.addAll(changeDetectorsExprs.declarations, targetDeclarations); + util_1.addAll(protoViewExprs.declarations, targetDeclarations); + util_1.addAll(viewFactoryExpr.declarations, targetDeclarations); + return viewFactoryExpr.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, change_detector_compiler_1.ChangeDetectionCompiler, proto_view_compiler_1.ProtoViewCompiler, view_compiler_1.ViewCompiler, resolved_metadata_cache_1.ResolvedMetadataCache, change_detection_1.ChangeDetectorGenConfig])], TemplateCompiler); return TemplateCompiler; })(); exports.TemplateCompiler = TemplateCompiler; var NormalizedComponentWithViewDirectives = (function() { - function NormalizedComponentWithViewDirectives(component, directives) { + function NormalizedComponentWithViewDirectives(component, directives, pipes) { this.component = component; this.directives = directives; + this.pipes = pipes; } return NormalizedComponentWithViewDirectives; })(); exports.NormalizedComponentWithViewDirectives = NormalizedComponentWithViewDirectives; + var CompiledTemplate = (function() { + function CompiledTemplate() { + this.viewFactory = null; + } + CompiledTemplate.prototype.init = function(viewFactory) { + this.viewFactory = viewFactory; + }; + return CompiledTemplate; + })(); 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 codeGenHostViewFactoryName(type) { + return "hostViewFactory_" + type.name; } - function codeGenComponentTemplateFactory(nestedCompType) { - return "" + source_module_1.moduleRef(templateModuleUrl(nestedCompType.type.moduleUrl)) + templateGetterName(nestedCompType.type); + function codeGenComponentViewFactoryName(nestedCompType) { + return source_module_1.moduleRef(templateModuleUrl(nestedCompType.type.moduleUrl)) + "viewFactory_" + nestedCompType.type.name + "0"; + } + function mergeStringMaps(maps) { + var result = {}; + maps.forEach(function(map) { + collection_1.StringMapWrapper.forEach(map, function(value, key) { + result[key] = value; + }); + }); + return result; } function removeDuplicates(items) { var res = []; @@ -24804,11 +25324,124 @@ System.register("angular2/src/compiler/template_compiler", ["angular2/src/facade }); return res; } + var DirectiveCollector = (function() { + function DirectiveCollector() { + this.directives = []; + this.components = []; + } + DirectiveCollector.findUsedDirectives = function(parsedTemplate) { + var collector = new DirectiveCollector(); + template_ast_1.templateVisitAll(collector, parsedTemplate); + return collector; + }; + DirectiveCollector.prototype.visitBoundText = function(ast, context) { + return null; + }; + DirectiveCollector.prototype.visitText = function(ast, context) { + return null; + }; + DirectiveCollector.prototype.visitNgContent = function(ast, context) { + return null; + }; + DirectiveCollector.prototype.visitElement = function(ast, context) { + template_ast_1.templateVisitAll(this, ast.directives); + template_ast_1.templateVisitAll(this, ast.children); + return null; + }; + DirectiveCollector.prototype.visitEmbeddedTemplate = function(ast, context) { + template_ast_1.templateVisitAll(this, ast.directives); + template_ast_1.templateVisitAll(this, ast.children); + return null; + }; + DirectiveCollector.prototype.visitVariable = function(ast, ctx) { + return null; + }; + DirectiveCollector.prototype.visitAttr = function(ast, attrNameAndValues) { + return null; + }; + DirectiveCollector.prototype.visitDirective = function(ast, ctx) { + if (ast.directive.isComponent) { + this.components.push(ast.directive); + } + this.directives.push(ast.directive); + return null; + }; + DirectiveCollector.prototype.visitEvent = function(ast, eventTargetAndNames) { + return null; + }; + DirectiveCollector.prototype.visitDirectiveProperty = function(ast, context) { + return null; + }; + DirectiveCollector.prototype.visitElementProperty = function(ast, context) { + return null; + }; + return DirectiveCollector; + })(); + function filterPipes(template, allPipes) { + var visitor = new PipeVisitor(); + template_ast_1.templateVisitAll(visitor, template); + return allPipes.filter(function(pipeMeta) { + return collection_1.SetWrapper.has(visitor.collector.pipes, pipeMeta.name); + }); + } + var PipeVisitor = (function() { + function PipeVisitor() { + this.collector = new template_parser_1.PipeCollector(); + } + PipeVisitor.prototype.visitBoundText = function(ast, context) { + ast.value.visit(this.collector); + return null; + }; + PipeVisitor.prototype.visitText = function(ast, context) { + return null; + }; + PipeVisitor.prototype.visitNgContent = function(ast, context) { + return null; + }; + PipeVisitor.prototype.visitElement = function(ast, context) { + template_ast_1.templateVisitAll(this, ast.inputs); + template_ast_1.templateVisitAll(this, ast.outputs); + template_ast_1.templateVisitAll(this, ast.directives); + template_ast_1.templateVisitAll(this, ast.children); + return null; + }; + PipeVisitor.prototype.visitEmbeddedTemplate = function(ast, context) { + template_ast_1.templateVisitAll(this, ast.outputs); + template_ast_1.templateVisitAll(this, ast.directives); + template_ast_1.templateVisitAll(this, ast.children); + return null; + }; + PipeVisitor.prototype.visitVariable = function(ast, ctx) { + return null; + }; + PipeVisitor.prototype.visitAttr = function(ast, attrNameAndValues) { + return null; + }; + PipeVisitor.prototype.visitDirective = function(ast, ctx) { + template_ast_1.templateVisitAll(this, ast.inputs); + template_ast_1.templateVisitAll(this, ast.hostEvents); + template_ast_1.templateVisitAll(this, ast.hostProperties); + return null; + }; + PipeVisitor.prototype.visitEvent = function(ast, eventTargetAndNames) { + ast.handler.visit(this.collector); + return null; + }; + PipeVisitor.prototype.visitDirectiveProperty = function(ast, context) { + ast.value.visit(this.collector); + return null; + }; + PipeVisitor.prototype.visitElementProperty = function(ast, context) { + ast.value.visit(this.collector); + return null; + }; + return PipeVisitor; + })(); 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) { +System.register("angular2/src/compiler/runtime_compiler", ["angular2/src/core/linker/compiler", "angular2/src/core/linker/view_ref", "angular2/src/compiler/template_compiler", "angular2/src/core/di"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -24838,7 +25471,7 @@ System.register("angular2/src/compiler/runtime_compiler", ["angular2/src/core/li 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 view_ref_1 = require("angular2/src/core/linker/view_ref"); var template_compiler_1 = require("angular2/src/compiler/template_compiler"); var di_1 = require("angular2/src/core/di"); var RuntimeCompiler = (function(_super) { @@ -24851,21 +25484,20 @@ System.register("angular2/src/compiler/runtime_compiler", ["angular2/src/core/li exports.RuntimeCompiler = RuntimeCompiler; var RuntimeCompiler_ = (function(_super) { __extends(RuntimeCompiler_, _super); - function RuntimeCompiler_(_protoViewFactory, _templateCompiler) { - _super.call(this, _protoViewFactory); + function RuntimeCompiler_(_templateCompiler) { + _super.call(this); 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); + return this._templateCompiler.compileHostComponentRuntime(componentType).then(function(hostViewFactory) { + return new view_ref_1.HostViewFactoryRef_(hostViewFactory); }); }; 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_); + RuntimeCompiler_ = __decorate([di_1.Injectable(), __metadata('design:paramtypes', [template_compiler_1.TemplateCompiler])], RuntimeCompiler_); return RuntimeCompiler_; })(compiler_1.Compiler_); exports.RuntimeCompiler_ = RuntimeCompiler_; @@ -24873,7 +25505,7 @@ System.register("angular2/src/compiler/runtime_compiler", ["angular2/src/core/li 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) { +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/view_compiler", "angular2/src/compiler/proto_view_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; @@ -24906,7 +25538,8 @@ System.register("angular2/src/compiler/compiler", ["angular2/src/compiler/runtim 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 view_compiler_1 = require("angular2/src/compiler/view_compiler"); + var proto_view_compiler_1 = require("angular2/src/compiler/proto_view_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"); @@ -24918,7 +25551,7 @@ System.register("angular2/src/compiler/compiler", ["angular2/src/compiler/runtim 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, { + 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, proto_view_compiler_1.ProtoViewCompiler, view_compiler_1.ViewCompiler, 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]); @@ -24942,7 +25575,7 @@ System.register("angular2/compiler", ["angular2/src/compiler/url_resolver", "ang 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) { +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/platform/common_dom", "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; @@ -24965,16 +25598,16 @@ System.register("angular2/src/platform/browser_common", ["angular2/src/facade/la 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 common_dom_1 = require("angular2/platform/common_dom"); 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 common_dom_2 = require("angular2/platform/common_dom"); + exports.ELEMENT_PROBE_PROVIDERS = common_dom_2.ELEMENT_PROBE_PROVIDERS; + exports.ELEMENT_PROBE_PROVIDERS_PROD_MODE = common_dom_2.ELEMENT_PROBE_PROVIDERS_PROD_MODE; + exports.inspectNativeElement = common_dom_2.inspectNativeElement; + exports.By = common_dom_2.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"); @@ -25011,7 +25644,7 @@ System.register("angular2/src/platform/browser_common", ["angular2/src/facade/la }), 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]); + }), new di_1.Provider(dom_renderer_1.DomRootRenderer, {useClass: dom_renderer_1.DomRootRenderer_}), new di_1.Provider(core_1.RootRenderer, {useExisting: dom_renderer_1.DomRootRenderer}), 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, common_dom_1.ELEMENT_PROBE_PROVIDERS]); function initDomAdapter() { browser_adapter_1.BrowserDomAdapter.makeCurrent(); wtf_init_1.wtfInit(); @@ -25030,8 +25663,8 @@ System.register("angular2/platform/browser", ["angular2/src/core/angular_entrypo 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.ELEMENT_PROBE_PROVIDERS_PROD_MODE = browser_common_1.ELEMENT_PROBE_PROVIDERS_PROD_MODE; exports.inspectNativeElement = browser_common_1.inspectNativeElement; exports.BrowserDomAdapter = browser_common_1.BrowserDomAdapter; exports.By = browser_common_1.By; 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 index 36a98998e..b6408b2d1 100644 --- a/testapp/ng2/lib/angular2.0.0-beta.0/bundles/router.js +++ b/testapp/ng2/lib/angular2.0.0-beta.0/bundles/router.js @@ -1,5 +1,5 @@ "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) { +System.register("angular2/src/router/directives/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; @@ -222,15 +222,15 @@ System.register("angular2/src/router/router_link_transform", ["angular2/compiler 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) { +System.register("angular2/router/router_link_dsl", ["angular2/compiler", "angular2/core", "angular2/src/router/directives/router_link_transform", "angular2/src/facade/lang", "angular2/src/router/directives/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 router_link_transform_1 = require("angular2/src/router/directives/router_link_transform"); var lang_1 = require("angular2/src/facade/lang"); - var router_link_transform_2 = require("angular2/src/router/router_link_transform"); + var router_link_transform_2 = require("angular2/src/router/directives/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, @@ -240,10 +240,19 @@ System.register("angular2/router/router_link_dsl", ["angular2/compiler", "angula return module.exports; }); -System.register("angular2/src/router/route_config_impl", ["angular2/src/facade/lang"], true, function(require, exports, module) { +System.register("angular2/src/router/route_config/route_config_impl", ["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 __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, @@ -261,6 +270,7 @@ System.register("angular2/src/router/route_config_impl", ["angular2/src/facade/l return Reflect.metadata(k, v); }; var lang_1 = require("angular2/src/facade/lang"); + var __make_dart_analyzer_happy = null; var RouteConfig = (function() { function RouteConfig(configs) { this.configs = configs; @@ -269,83 +279,128 @@ System.register("angular2/src/router/route_config_impl", ["angular2/src/facade/l return RouteConfig; })(); exports.RouteConfig = RouteConfig; - var Route = (function() { + var AbstractRoute = (function() { + function AbstractRoute(_a) { + var name = _a.name, + useAsDefault = _a.useAsDefault, + path = _a.path, + regex = _a.regex, + serializer = _a.serializer, + data = _a.data; + this.name = name; + this.useAsDefault = useAsDefault; + this.path = path; + this.regex = regex; + this.serializer = serializer; + this.data = data; + } + AbstractRoute = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object])], AbstractRoute); + return AbstractRoute; + })(); + exports.AbstractRoute = AbstractRoute; + var Route = (function(_super) { + __extends(Route, _super); function Route(_a) { - var path = _a.path, - component = _a.component, - name = _a.name, + var name = _a.name, + useAsDefault = _a.useAsDefault, + path = _a.path, + regex = _a.regex, + serializer = _a.serializer, data = _a.data, - useAsDefault = _a.useAsDefault; + component = _a.component; + _super.call(this, { + name: name, + useAsDefault: useAsDefault, + path: path, + regex: regex, + serializer: serializer, + data: data + }); 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; - })(); + })(AbstractRoute); exports.Route = Route; - var AuxRoute = (function() { + var AuxRoute = (function(_super) { + __extends(AuxRoute, _super); 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; + var name = _a.name, + useAsDefault = _a.useAsDefault, + path = _a.path, + regex = _a.regex, + serializer = _a.serializer, + data = _a.data, + component = _a.component; + _super.call(this, { + name: name, + useAsDefault: useAsDefault, + path: path, + regex: regex, + serializer: serializer, + data: data + }); this.component = component; - this.name = name; } AuxRoute = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object])], AuxRoute); return AuxRoute; - })(); + })(AbstractRoute); exports.AuxRoute = AuxRoute; - var AsyncRoute = (function() { + var AsyncRoute = (function(_super) { + __extends(AsyncRoute, _super); function AsyncRoute(_a) { - var path = _a.path, - loader = _a.loader, - name = _a.name, + var name = _a.name, + useAsDefault = _a.useAsDefault, + path = _a.path, + regex = _a.regex, + serializer = _a.serializer, data = _a.data, - useAsDefault = _a.useAsDefault; + loader = _a.loader; + _super.call(this, { + name: name, + useAsDefault: useAsDefault, + path: path, + regex: regex, + serializer: serializer, + data: data + }); 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; - })(); + })(AbstractRoute); exports.AsyncRoute = AsyncRoute; - var Redirect = (function() { + var Redirect = (function(_super) { + __extends(Redirect, _super); function Redirect(_a) { - var path = _a.path, + var name = _a.name, + useAsDefault = _a.useAsDefault, + path = _a.path, + regex = _a.regex, + serializer = _a.serializer, + data = _a.data, redirectTo = _a.redirectTo; - this.name = null; - this.loader = null; - this.data = null; - this.aux = null; - this.useAsDefault = false; - this.path = path; + _super.call(this, { + name: name, + useAsDefault: useAsDefault, + path: path, + regex: regex, + serializer: serializer, + data: data + }); this.redirectTo = redirectTo; } Redirect = __decorate([lang_1.CONST(), __metadata('design:paramtypes', [Object])], Redirect); return Redirect; - })(); + })(AbstractRoute); 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) { +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; @@ -360,244 +415,25 @@ System.register("angular2/src/router/instruction", ["angular2/src/facade/collect }; 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; + var exceptions_1 = require("angular2/src/facade/exceptions"); + function convertUrlParamsToArray(urlParams) { + var paramsArray = []; + if (lang_1.isBlank(urlParams)) { + return []; } - 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 + collection_1.StringMapWrapper.forEach(urlParams, function(value, key) { + paramsArray.push((value === true) ? key : key + '=' + value); }); - 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; + return paramsArray; + } + exports.convertUrlParamsToArray = convertUrlParamsToArray; + function serializeParams(urlParams, joiner) { + if (joiner === void 0) { + joiner = '&'; } - 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"); + return convertUrlParamsToArray(urlParams).join(joiner); + } + exports.serializeParams = serializeParams; var Url = (function() { function Url(path, child, auxiliary, params) { if (child === void 0) { @@ -607,7 +443,7 @@ System.register("angular2/src/router/url_parser", ["angular2/src/facade/collecti auxiliary = lang_1.CONST_EXPR([]); } if (params === void 0) { - params = null; + params = lang_1.CONST_EXPR({}); } this.path = path; this.child = child; @@ -626,10 +462,11 @@ System.register("angular2/src/router/url_parser", ["angular2/src/facade/collecti }).join('//') + ')') : ''; }; Url.prototype._matrixParamsToString = function() { - if (lang_1.isBlank(this.params)) { - return ''; + var paramString = serializeParams(this.params, ';'); + if (paramString.length > 0) { + return ';' + paramString; } - return ';' + serializeParams(this.params).join(';'); + return ''; }; Url.prototype._childString = function() { return lang_1.isPresent(this.child) ? ('/' + this.child.toString()) : ''; @@ -661,7 +498,7 @@ System.register("angular2/src/router/url_parser", ["angular2/src/facade/collecti if (lang_1.isBlank(this.params)) { return ''; } - return '?' + serializeParams(this.params).join('&'); + return '?' + serializeParams(this.params); }; return RootUrl; })(Url); @@ -679,6 +516,11 @@ System.register("angular2/src/router/url_parser", ["angular2/src/facade/collecti var match = lang_1.RegExpWrapper.firstMatch(SEGMENT_RE, str); return lang_1.isPresent(match) ? match[0] : ''; } + var QUERY_PARAM_VALUE_RE = lang_1.RegExpWrapper.create('^[^\\(\\)\\?;&#]+'); + function matchUrlQueryParamValue(str) { + var match = lang_1.RegExpWrapper.firstMatch(QUERY_PARAM_VALUE_RE, str); + return lang_1.isPresent(match) ? match[0] : ''; + } var UrlParser = (function() { function UrlParser() {} UrlParser.prototype.peekStartsWith = function(str) { @@ -748,73 +590,315 @@ System.register("angular2/src/router/url_parser", ["angular2/src/facade/collecti UrlParser.prototype.parseQueryParams = function() { var params = {}; this.capture('?'); - this.parseParam(params); + this.parseQueryParam(params); while (this._remaining.length > 0 && this.peekStartsWith('&')) { this.capture('&'); + this.parseQueryParam(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.parseMatrixParams = function() { - var params = {}; - while (this._remaining.length > 0 && this.peekStartsWith(';')) { - this.capture(';'); - this.parseParam(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.parseQueryParam = 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 = matchUrlQueryParamValue(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(); + 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(component, child, auxInstruction) { + this.component = component; + this.child = child; + this.auxInstruction = auxInstruction; + } + Object.defineProperty(Instruction.prototype, "urlPath", { + get: function() { + return lang_1.isPresent(this.component) ? this.component.urlPath : ''; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Instruction.prototype, "urlParams", { + get: function() { + return lang_1.isPresent(this.component) ? this.component.urlParams : []; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Instruction.prototype, "specificity", { + get: function() { + var total = ''; + 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() : '') + this.toUrlQuery(); + }; + 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 params; + return primary; }; - 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); - } + Instruction.prototype._stringifyMatrixParams = function() { + return this.urlParams.length > 0 ? (';' + this.urlParams.join(';')) : ''; + }; + Instruction.prototype._stringifyPathMatrixAux = function() { + if (lang_1.isBlank(this.component)) { + return ''; } - params[key] = value; + return this.urlPath + this._stringifyMatrixParams() + this._stringifyAux(); }; - UrlParser.prototype.parseAuxiliaryRoutes = function() { + Instruction.prototype._stringifyAux = function() { var routes = []; - this.capture('('); - while (!this.peekStartsWith(')') && this._remaining.length > 0) { - routes.push(this.parseSegment()); - if (this.peekStartsWith('//')) { - this.capture('//'); - } + collection_1.StringMapWrapper.forEach(this.auxInstruction, function(auxInstruction, _) { + routes.push(auxInstruction._stringifyPathMatrixAux()); + }); + if (routes.length > 0) { + return '(' + routes.join('//') + ')'; } - this.capture(')'); - return routes; + return ''; }; - return UrlParser; + return Instruction; })(); - 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); + exports.Instruction = Instruction; + var ResolvedInstruction = (function(_super) { + __extends(ResolvedInstruction, _super); + function ResolvedInstruction(component, child, auxInstruction) { + _super.call(this, component, child, 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, component, child, {}); + } + DefaultInstruction.prototype.toLinkUrl = function() { + return ''; + }; + DefaultInstruction.prototype._toLinkUrl = function() { + return ''; + }; + return DefaultInstruction; + })(ResolvedInstruction); + 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, null, null, {}); + 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(instruction) { + _this.child = lang_1.isPresent(instruction) ? instruction.child : null; + return _this.component = lang_1.isPresent(instruction) ? instruction.component : null; }); + }; + return UnresolvedInstruction; + })(Instruction); + exports.UnresolvedInstruction = UnresolvedInstruction; + var RedirectInstruction = (function(_super) { + __extends(RedirectInstruction, _super); + function RedirectInstruction(component, child, auxInstruction, _specificity) { + _super.call(this, component, child, auxInstruction); + this._specificity = _specificity; } - return params; - } - exports.serializeParams = serializeParams; + Object.defineProperty(RedirectInstruction.prototype, "specificity", { + get: function() { + return this._specificity; + }, + enumerable: true, + configurable: true + }); + 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/async_route_handler", ["angular2/src/facade/lang", "angular2/src/router/instruction"], true, function(require, exports, module) { +System.register("angular2/src/router/rules/route_handlers/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; @@ -846,7 +930,7 @@ System.register("angular2/src/router/async_route_handler", ["angular2/src/facade 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) { +System.register("angular2/src/router/rules/route_handlers/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; @@ -870,13 +954,127 @@ System.register("angular2/src/router/sync_route_handler", ["angular2/src/facade/ 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) { +System.register("angular2/src/router/utils", ["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 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; + })(); + exports.TouchMap = TouchMap; + function normalizeString(obj) { + if (lang_1.isBlank(obj)) { + return null; + } else { + return obj.toString(); + } + } + exports.normalizeString = normalizeString; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/rules/route_paths/route_path", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var MatchedUrl = (function() { + function MatchedUrl(urlPath, urlParams, allParams, auxiliary, rest) { + this.urlPath = urlPath; + this.urlParams = urlParams; + this.allParams = allParams; + this.auxiliary = auxiliary; + this.rest = rest; + } + return MatchedUrl; + })(); + exports.MatchedUrl = MatchedUrl; + var GeneratedUrl = (function() { + function GeneratedUrl(urlPath, urlParams) { + this.urlPath = urlPath; + this.urlParams = urlParams; + } + return GeneratedUrl; + })(); + exports.GeneratedUrl = GeneratedUrl; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/rules/route_paths/regex_route_path", ["angular2/src/facade/lang", "angular2/src/router/rules/route_paths/route_path"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var lang_1 = require("angular2/src/facade/lang"); + var route_path_1 = require("angular2/src/router/rules/route_paths/route_path"); + var RegexRoutePath = (function() { + function RegexRoutePath(_reString, _serializer) { + this._reString = _reString; + this._serializer = _serializer; + this.terminal = true; + this.specificity = '2'; + this.hash = this._reString; + this._regex = lang_1.RegExpWrapper.create(this._reString); + } + RegexRoutePath.prototype.matchUrl = function(url) { + var urlPath = url.toString(); + var params = {}; + var matcher = lang_1.RegExpWrapper.matcher(this._regex, urlPath); + var match = lang_1.RegExpMatcherWrapper.next(matcher); + if (lang_1.isBlank(match)) { + return null; + } + for (var i = 0; i < match.length; i += 1) { + params[i.toString()] = match[i]; + } + return new route_path_1.MatchedUrl(urlPath, [], params, [], null); + }; + RegexRoutePath.prototype.generateUrl = function(params) { + return this._serializer(params); + }; + RegexRoutePath.prototype.toString = function() { + return this._reString; + }; + return RegexRoutePath; + })(); + exports.RegexRoutePath = RegexRoutePath; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/route_config/route_config_decorator", ["angular2/src/router/route_config/route_config_impl", "angular2/src/core/util/decorators", "angular2/src/router/route_config/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 route_config_impl_1 = require("angular2/src/router/route_config/route_config_impl"); var decorators_1 = require("angular2/src/core/util/decorators"); - var route_config_impl_2 = require("angular2/src/router/route_config_impl"); + var route_config_impl_2 = require("angular2/src/router/route_config/route_config_impl"); exports.Route = route_config_impl_2.Route; exports.Redirect = route_config_impl_2.Redirect; exports.AuxRoute = route_config_impl_2.AuxRoute; @@ -886,7 +1084,7 @@ System.register("angular2/src/router/route_config_decorator", ["angular2/src/rou return module.exports; }); -System.register("angular2/src/router/location_strategy", ["angular2/src/facade/lang", "angular2/core"], true, function(require, exports, module) { +System.register("angular2/src/router/location/location_strategy", ["angular2/src/facade/lang", "angular2/core"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -929,7 +1127,7 @@ System.register("angular2/src/router/location_strategy", ["angular2/src/facade/l return module.exports; }); -System.register("angular2/src/router/lifecycle_annotations_impl", ["angular2/src/facade/lang"], true, function(require, exports, module) { +System.register("angular2/src/router/lifecycle/lifecycle_annotations_impl", ["angular2/src/facade/lang"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -975,13 +1173,13 @@ System.register("angular2/src/router/lifecycle_annotations_impl", ["angular2/src 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) { +System.register("angular2/src/router/lifecycle/lifecycle_annotations", ["angular2/src/core/util/decorators", "angular2/src/router/lifecycle/lifecycle_annotations_impl", "angular2/src/router/lifecycle/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"); + var lifecycle_annotations_impl_1 = require("angular2/src/router/lifecycle/lifecycle_annotations_impl"); + var lifecycle_annotations_impl_2 = require("angular2/src/router/lifecycle/lifecycle_annotations_impl"); exports.routerCanReuse = lifecycle_annotations_impl_2.routerCanReuse; exports.routerCanDeactivate = lifecycle_annotations_impl_2.routerCanDeactivate; exports.routerOnActivate = lifecycle_annotations_impl_2.routerOnActivate; @@ -992,7 +1190,7 @@ System.register("angular2/src/router/lifecycle_annotations", ["angular2/src/core 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) { +System.register("angular2/src/router/directives/router_link", ["angular2/core", "angular2/src/facade/lang", "angular2/src/router/router", "angular2/src/router/location/location"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -1015,12 +1213,21 @@ System.register("angular2/src/router/router_link", ["angular2/core", "angular2/s 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 location_1 = require("angular2/src/router/location/location"); var RouterLink = (function() { function RouterLink(_router, _location) { + var _this = this; this._router = _router; this._location = _location; + this._router.subscribe(function(_) { + return _this._updateLink(); + }); } + RouterLink.prototype._updateLink = function() { + this._navigationInstruction = this._router.generate(this._routeParams); + var navigationHref = this._navigationInstruction.toLinkUrl(); + this.visibleHref = this._location.prepareExternalUrl(navigationHref); + }; Object.defineProperty(RouterLink.prototype, "isRouteActive", { get: function() { return this._router.isRouteActive(this._navigationInstruction); @@ -1031,9 +1238,7 @@ System.register("angular2/src/router/router_link", ["angular2/core", "angular2/s 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); + this._updateLink(); }, enumerable: true, configurable: true @@ -1056,12 +1261,46 @@ System.register("angular2/src/router/router_link", ["angular2/core", "angular2/s }), __metadata('design:paramtypes', [router_1.Router, location_1.Location])], RouterLink); return RouterLink; })(); - exports.RouterLink = RouterLink; + exports.RouterLink = RouterLink; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/location/platform_location", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var PlatformLocation = (function() { + function PlatformLocation() {} + Object.defineProperty(PlatformLocation.prototype, "pathname", { + get: function() { + return null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PlatformLocation.prototype, "search", { + get: function() { + return null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PlatformLocation.prototype, "hash", { + get: function() { + return null; + }, + enumerable: true, + configurable: true + }); + return PlatformLocation; + })(); + exports.PlatformLocation = PlatformLocation; 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) { +System.register("angular2/src/router/location/hash_location_strategy", ["angular2/core", "angular2/src/router/location/location_strategy", "angular2/src/facade/lang", "angular2/src/router/location/platform_location"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -1096,9 +1335,9 @@ System.register("angular2/src/router/hash_location_strategy", ["angular2/core", }; }; var core_1 = require("angular2/core"); - var location_strategy_1 = require("angular2/src/router/location_strategy"); + var location_strategy_1 = require("angular2/src/router/location/location_strategy"); var lang_1 = require("angular2/src/facade/lang"); - var platform_location_1 = require("angular2/src/router/platform_location"); + var platform_location_1 = require("angular2/src/router/location/platform_location"); var HashLocationStrategy = (function(_super) { __extends(HashLocationStrategy, _super); function HashLocationStrategy(_platformLocation, _baseHref) { @@ -1118,7 +1357,9 @@ System.register("angular2/src/router/hash_location_strategy", ["angular2/core", }; HashLocationStrategy.prototype.path = function() { var path = this._platformLocation.hash; - return (path.length > 0 ? path.substring(1) : path) + location_strategy_1.normalizeQueryParams(this._platformLocation.search); + if (!lang_1.isPresent(path)) + path = '#'; + return (path.length > 0 ? path.substring(1) : path); }; HashLocationStrategy.prototype.prepareExternalUrl = function(internal) { var url = location_strategy_1.joinWithSlash(this._baseHref, internal); @@ -1152,7 +1393,7 @@ System.register("angular2/src/router/hash_location_strategy", ["angular2/core", 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) { +System.register("angular2/src/router/location/path_location_strategy", ["angular2/core", "angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/router/location/location_strategy", "angular2/src/router/location/platform_location"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -1189,8 +1430,8 @@ System.register("angular2/src/router/path_location_strategy", ["angular2/core", 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 location_strategy_1 = require("angular2/src/router/location/location_strategy"); + var platform_location_1 = require("angular2/src/router/location/platform_location"); var PathLocationStrategy = (function(_super) { __extends(PathLocationStrategy, _super); function PathLocationStrategy(_platformLocation, href) { @@ -1247,374 +1488,423 @@ System.register("angular2/src/router/route_definition", [], true, function(requi 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) { +System.register("angular2/src/router/router_providers_common", ["angular2/src/router/location/location_strategy", "angular2/src/router/location/path_location_strategy", "angular2/src/router/router", "angular2/src/router/route_registry", "angular2/src/router/location/location", "angular2/src/facade/lang", "angular2/core", "angular2/src/facade/exceptions"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var location_strategy_1 = require("angular2/src/router/location/location_strategy"); + var path_location_strategy_1 = require("angular2/src/router/location/path_location_strategy"); + var router_1 = require("angular2/src/router/router"); + var route_registry_1 = require("angular2/src/router/route_registry"); + var location_1 = require("angular2/src/router/location/location"); + var lang_1 = require("angular2/src/facade/lang"); + var core_1 = require("angular2/core"); + var exceptions_1 = require("angular2/src/facade/exceptions"); + exports.ROUTER_PROVIDERS_COMMON = lang_1.CONST_EXPR([route_registry_1.RouteRegistry, lang_1.CONST_EXPR(new core_1.Provider(location_strategy_1.LocationStrategy, {useClass: path_location_strategy_1.PathLocationStrategy})), location_1.Location, lang_1.CONST_EXPR(new core_1.Provider(router_1.Router, { + useFactory: routerFactory, + deps: lang_1.CONST_EXPR([route_registry_1.RouteRegistry, location_1.Location, route_registry_1.ROUTER_PRIMARY_COMPONENT, core_1.ApplicationRef]) + })), lang_1.CONST_EXPR(new core_1.Provider(route_registry_1.ROUTER_PRIMARY_COMPONENT, { + useFactory: routerPrimaryComponentFactory, + deps: lang_1.CONST_EXPR([core_1.ApplicationRef]) + }))]); + function routerFactory(registry, location, primaryComponent, appRef) { + var rootRouter = new router_1.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; +}); + +System.register("angular2/src/router/rules/rules", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/promise", "angular2/src/facade/collection", "angular2/src/router/url_parser", "angular2/src/router/instruction"], 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 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; - }); - } + var instruction_1 = require("angular2/src/router/instruction"); + 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; } - TouchMap.prototype.get = function(key) { - collection_1.StringMapWrapper.delete(this.keys, key); - return this.map[key]; + 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 RedirectRule = (function() { + function RedirectRule(_pathRecognizer, redirectTo) { + this._pathRecognizer = _pathRecognizer; + this.redirectTo = redirectTo; + this.hash = this._pathRecognizer.hash; + } + Object.defineProperty(RedirectRule.prototype, "path", { + get: function() { + return this._pathRecognizer.toString(); + }, + set: function(val) { + throw new exceptions_1.BaseException('you cannot set the path of a RedirectRule directly'); + }, + enumerable: true, + configurable: true + }); + RedirectRule.prototype.recognize = function(beginningSegment) { + var match = null; + if (lang_1.isPresent(this._pathRecognizer.matchUrl(beginningSegment))) { + match = new RedirectMatch(this.redirectTo, this._pathRecognizer.specificity); + } + return promise_1.PromiseWrapper.resolve(match); }; - TouchMap.prototype.getUnused = function() { + RedirectRule.prototype.generate = function(params) { + throw new exceptions_1.BaseException("Tried to generate a redirect."); + }; + return RedirectRule; + })(); + exports.RedirectRule = RedirectRule; + var RouteRule = (function() { + function RouteRule(_routePath, handler) { + this._routePath = _routePath; + this.handler = handler; + this._cache = new collection_1.Map(); + this.specificity = this._routePath.specificity; + this.hash = this._routePath.hash; + this.terminal = this._routePath.terminal; + } + Object.defineProperty(RouteRule.prototype, "path", { + get: function() { + return this._routePath.toString(); + }, + set: function(val) { + throw new exceptions_1.BaseException('you cannot set the path of a RouteRule directly'); + }, + enumerable: true, + configurable: true + }); + RouteRule.prototype.recognize = function(beginningSegment) { 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); + var res = this._routePath.matchUrl(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.rest, res.auxiliary); }); - return unused; }; - return TouchMap; + RouteRule.prototype.generate = function(params) { + var generated = this._routePath.generateUrl(params); + var urlPath = generated.urlPath; + var urlParams = generated.urlParams; + return this._getInstruction(urlPath, url_parser_1.convertUrlParamsToArray(urlParams), params); + }; + RouteRule.prototype.generateComponentPathValues = function(params) { + return this._routePath.generateUrl(params); + }; + RouteRule.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 RouteRule; })(); - function normalizeString(obj) { - if (lang_1.isBlank(obj)) { - return null; - } else { - return obj.toString(); - } - } - var ContinuationSegment = (function() { - function ContinuationSegment() { + exports.RouteRule = RouteRule; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/rules/route_paths/param_route_path", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/router/utils", "angular2/src/router/url_parser", "angular2/src/router/rules/route_paths/route_path"], 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 utils_1 = require("angular2/src/router/utils"); + var url_parser_1 = require("angular2/src/router/url_parser"); + var route_path_1 = require("angular2/src/router/rules/route_paths/route_path"); + var ContinuationPathSegment = (function() { + function ContinuationPathSegment() { this.name = ''; + this.specificity = ''; + this.hash = '...'; } - ContinuationSegment.prototype.generate = function(params) { + ContinuationPathSegment.prototype.generate = function(params) { return ''; }; - ContinuationSegment.prototype.match = function(path) { + ContinuationPathSegment.prototype.match = function(path) { return true; }; - return ContinuationSegment; + return ContinuationPathSegment; })(); - var StaticSegment = (function() { - function StaticSegment(path) { + var StaticPathSegment = (function() { + function StaticPathSegment(path) { this.path = path; this.name = ''; + this.specificity = '2'; + this.hash = path; } - StaticSegment.prototype.match = function(path) { + StaticPathSegment.prototype.match = function(path) { return path == this.path; }; - StaticSegment.prototype.generate = function(params) { + StaticPathSegment.prototype.generate = function(params) { return this.path; }; - return StaticSegment; + return StaticPathSegment; })(); - var DynamicSegment = (function() { - function DynamicSegment(name) { + var DynamicPathSegment = (function() { + function DynamicPathSegment(name) { this.name = name; + this.specificity = '1'; + this.hash = ':'; } - DynamicSegment.prototype.match = function(path) { + DynamicPathSegment.prototype.match = function(path) { return path.length > 0; }; - DynamicSegment.prototype.generate = function(params) { + DynamicPathSegment.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 encodeDynamicSegment(utils_1.normalizeString(params.get(this.name))); }; - return DynamicSegment; + DynamicPathSegment.paramMatcher = /^:([^\/]+)$/g; + return DynamicPathSegment; })(); - var StarSegment = (function() { - function StarSegment(name) { + var StarPathSegment = (function() { + function StarPathSegment(name) { this.name = name; + this.specificity = '0'; + this.hash = '*'; } - StarSegment.prototype.match = function(path) { + StarPathSegment.prototype.match = function(path) { return true; }; - StarSegment.prototype.generate = function(params) { - return normalizeString(params.get(this.name)); + StarPathSegment.prototype.generate = function(params) { + return utils_1.normalizeString(params.get(this.name)); }; - return StarSegment; + StarPathSegment.wildcardMatcher = /^\*([^\/]+)$/g; + return StarPathSegment; })(); - 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; + var ParamRoutePath = (function() { + function ParamRoutePath(routePath) { + this.routePath = routePath; this.terminal = true; - assertPath(path); - var parsed = parsePathString(path); - this._segments = parsed['segments']; - this.specificity = parsed['specificity']; - this.hash = pathDslHash(this._segments); + this._assertValidPath(routePath); + this._parsePathString(routePath); + this.specificity = this._calculateSpecificity(); + this.hash = this._calculateHash(); var lastSegment = this._segments[this._segments.length - 1]; - this.terminal = !(lastSegment instanceof ContinuationSegment); + this.terminal = !(lastSegment instanceof ContinuationPathSegment); } - PathRecognizer.prototype.recognize = function(beginningSegment) { - var nextSegment = beginningSegment; - var currentSegment; + ParamRoutePath.prototype.matchUrl = function(url) { + var nextUrlSegment = url; + var currentUrlSegment; 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) { + var pathSegment = this._segments[i]; + currentUrlSegment = nextUrlSegment; + if (pathSegment instanceof ContinuationPathSegment) { break; } - if (lang_1.isPresent(currentSegment)) { - captured.push(currentSegment.path); - if (segment instanceof StarSegment) { - positionalParams[segment.name] = currentSegment.toString(); - nextSegment = null; + if (lang_1.isPresent(currentUrlSegment)) { + if (pathSegment instanceof StarPathSegment) { + positionalParams[pathSegment.name] = currentUrlSegment.toString(); + captured.push(currentUrlSegment.toString()); + nextUrlSegment = null; break; } - if (segment instanceof DynamicSegment) { - positionalParams[segment.name] = currentSegment.path; - } else if (!segment.match(currentSegment.path)) { + captured.push(currentUrlSegment.path); + if (pathSegment instanceof DynamicPathSegment) { + positionalParams[pathSegment.name] = decodeDynamicSegment(currentUrlSegment.path); + } else if (!pathSegment.match(currentUrlSegment.path)) { return null; } - nextSegment = currentSegment.child; - } else if (!segment.match('')) { + nextUrlSegment = currentUrlSegment.child; + } else if (!pathSegment.match('')) { return null; } } - if (this.terminal && lang_1.isPresent(nextSegment)) { + if (this.terminal && lang_1.isPresent(nextUrlSegment)) { 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 auxiliary = []; + var urlParams = []; + var allParams = positionalParams; + if (lang_1.isPresent(currentUrlSegment)) { + var paramsSegment = url instanceof url_parser_1.RootUrl ? url : currentUrlSegment; + if (lang_1.isPresent(paramsSegment.params)) { + allParams = collection_1.StringMapWrapper.merge(paramsSegment.params, positionalParams); + urlParams = url_parser_1.convertUrlParamsToArray(paramsSegment.params); + } else { + allParams = positionalParams; + } + auxiliary = currentUrlSegment.auxiliary; + } + return new route_path_1.MatchedUrl(urlPath, urlParams, allParams, auxiliary, nextUrlSegment); + }; + ParamRoutePath.prototype.generateUrl = function(params) { + var paramTokens = new utils_1.TouchMap(params); var path = []; for (var i = 0; i < this._segments.length; i++) { var segment = this._segments[i]; - if (!(segment instanceof ContinuationSegment)) { + if (!(segment instanceof ContinuationPathSegment)) { 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"); + var urlParams = nonPositionalParams; + return new route_path_1.GeneratedUrl(urlPath, urlParams); + }; + ParamRoutePath.prototype.toString = function() { + return this.routePath; + }; + ParamRoutePath.prototype._parsePathString = function(routePath) { + if (routePath.startsWith("/")) { + routePath = routePath.substring(1); + } + var segmentStrings = routePath.split('/'); + this._segments = []; + var limit = segmentStrings.length - 1; + for (var i = 0; i <= limit; i++) { + var segment = segmentStrings[i], + match; + if (lang_1.isPresent(match = lang_1.RegExpWrapper.firstMatch(DynamicPathSegment.paramMatcher, segment))) { + this._segments.push(new DynamicPathSegment(match[1])); + } else if (lang_1.isPresent(match = lang_1.RegExpWrapper.firstMatch(StarPathSegment.wildcardMatcher, segment))) { + this._segments.push(new StarPathSegment(match[1])); + } else if (segment == '...') { + if (i < limit) { + throw new exceptions_1.BaseException("Unexpected \"...\" before the end of the path for \"" + routePath + "\"."); + } + this._segments.push(new ContinuationPathSegment()); + } else { + this._segments.push(new StaticPathSegment(segment)); } - 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); + ParamRoutePath.prototype._calculateSpecificity = function() { + var i, + length = this._segments.length, + specificity; + if (length == 0) { + specificity += '2'; + } else { + specificity = ''; + for (i = 0; i < length; i++) { + specificity += this._segments[i].specificity; } - }); - 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); + return specificity; }; - 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; + ParamRoutePath.prototype._calculateHash = function() { + var i, + length = this._segments.length; + var hashParts = []; + for (i = 0; i < length; i++) { + hashParts.push(this._segments[i].hash); } - return pathRecognizer.generate(params); + return hashParts.join('/'); }; - ComponentRecognizer.prototype.generateAuxiliary = function(name, params) { - var pathRecognizer = this.auxNames.get(name); - if (lang_1.isBlank(pathRecognizer)) { - return null; + ParamRoutePath.prototype._assertValidPath = function(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(ParamRoutePath.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."); } - return pathRecognizer.generate(params); }; - return ComponentRecognizer; + ParamRoutePath.RESERVED_CHARS = lang_1.RegExpWrapper.create('//|\\(|\\)|;|\\?|='); + return ParamRoutePath; })(); - exports.ComponentRecognizer = ComponentRecognizer; + exports.ParamRoutePath = ParamRoutePath; + var REGEXP_PERCENT = /%/g; + var REGEXP_SLASH = /\//g; + var REGEXP_OPEN_PARENT = /\(/g; + var REGEXP_CLOSE_PARENT = /\)/g; + var REGEXP_SEMICOLON = /;/g; + function encodeDynamicSegment(value) { + if (lang_1.isBlank(value)) { + return null; + } + value = lang_1.StringWrapper.replaceAll(value, REGEXP_PERCENT, '%25'); + value = lang_1.StringWrapper.replaceAll(value, REGEXP_SLASH, '%2F'); + value = lang_1.StringWrapper.replaceAll(value, REGEXP_OPEN_PARENT, '%28'); + value = lang_1.StringWrapper.replaceAll(value, REGEXP_CLOSE_PARENT, '%29'); + value = lang_1.StringWrapper.replaceAll(value, REGEXP_SEMICOLON, '%3B'); + return value; + } + var REGEXP_ENC_SEMICOLON = /%3B/ig; + var REGEXP_ENC_CLOSE_PARENT = /%29/ig; + var REGEXP_ENC_OPEN_PARENT = /%28/ig; + var REGEXP_ENC_SLASH = /%2F/ig; + var REGEXP_ENC_PERCENT = /%25/ig; + function decodeDynamicSegment(value) { + if (lang_1.isBlank(value)) { + return null; + } + value = lang_1.StringWrapper.replaceAll(value, REGEXP_ENC_SEMICOLON, ';'); + value = lang_1.StringWrapper.replaceAll(value, REGEXP_ENC_CLOSE_PARENT, ')'); + value = lang_1.StringWrapper.replaceAll(value, REGEXP_ENC_OPEN_PARENT, '('); + value = lang_1.StringWrapper.replaceAll(value, REGEXP_ENC_SLASH, '/'); + value = lang_1.StringWrapper.replaceAll(value, REGEXP_ENC_PERCENT, '%'); + return value; + } 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) { +System.register("angular2/src/router/route_config/route_config_normalizer", ["angular2/src/router/route_config/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 route_config_decorator_1 = require("angular2/src/router/route_config/route_config_decorator"); var lang_1 = require("angular2/src/facade/lang"); var exceptions_1 = require("angular2/src/facade/exceptions"); function normalizeRouteConfig(config, registry) { @@ -1646,6 +1936,7 @@ System.register("angular2/src/router/route_config_nomalizer", ["angular2/src/rou path: config.path, loader: wrappedLoader, name: config.name, + data: config.data, useAsDefault: config.useAsDefault }); } @@ -1672,6 +1963,7 @@ System.register("angular2/src/router/route_config_nomalizer", ["angular2/src/rou path: config.path, loader: componentDefinitionObject.loader, name: config.name, + data: config.data, useAsDefault: config.useAsDefault }); } else { @@ -1707,7 +1999,7 @@ System.register("angular2/src/router/route_config_nomalizer", ["angular2/src/rou 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) { +System.register("angular2/src/router/location/location", ["angular2/src/router/location/location_strategy", "angular2/src/facade/async", "angular2/core"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -1727,7 +2019,7 @@ System.register("angular2/src/router/location", ["angular2/src/router/location_s if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; - var location_strategy_1 = require("angular2/src/router/location_strategy"); + var location_strategy_1 = require("angular2/src/router/location/location_strategy"); var async_1 = require("angular2/src/facade/async"); var core_1 = require("angular2/core"); var Location = (function() { @@ -1810,12 +2102,12 @@ System.register("angular2/src/router/location", ["angular2/src/router/location_s 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) { +System.register("angular2/src/router/lifecycle/route_lifecycle_reflector", ["angular2/src/facade/lang", "angular2/src/router/lifecycle/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 lifecycle_annotations_impl_1 = require("angular2/src/router/lifecycle/lifecycle_annotations_impl"); var reflection_1 = require("angular2/src/core/reflection/reflection"); function hasLifecycleHook(e, type) { if (!(type instanceof lang_1.Type)) @@ -1838,7 +2130,7 @@ System.register("angular2/src/router/route_lifecycle_reflector", ["angular2/src/ 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) { +System.register("angular2/src/router/directives/router_outlet", ["angular2/src/facade/async", "angular2/src/facade/collection", "angular2/src/facade/lang", "angular2/core", "angular2/src/router/router", "angular2/src/router/instruction", "angular2/src/router/lifecycle/lifecycle_annotations", "angular2/src/router/lifecycle/route_lifecycle_reflector"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -1866,12 +2158,11 @@ System.register("angular2/src/router/router_outlet", ["angular2/src/facade/async 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 hookMod = require("angular2/src/router/lifecycle/lifecycle_annotations"); + var route_lifecycle_reflector_1 = require("angular2/src/router/lifecycle/route_lifecycle_reflector"); var _resolveToTrue = async_1.PromiseWrapper.resolve(true); var RouterOutlet = (function() { function RouterOutlet(_elementRef, _loader, _parentRouter, nameAttr) { @@ -1895,10 +2186,14 @@ System.register("angular2/src/router/router_outlet", ["angular2/src/facade/async 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; + this._componentRef = this._loader.loadNextToLocation(componentType, this._elementRef, providers); + return this._componentRef.then(function(componentRef) { if (route_lifecycle_reflector_1.hasLifecycleHook(hookMod.routerOnActivate, componentType)) { - return _this._componentRef.instance.routerOnActivate(nextInstruction, previousInstruction); + return _this._componentRef.then(function(ref) { + return ref.instance.routerOnActivate(nextInstruction, previousInstruction); + }); + } else { + return componentRef; } }); }; @@ -1906,43 +2201,61 @@ System.register("angular2/src/router/router_outlet", ["angular2/src/facade/async 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 this.activate(nextInstruction); + } else { + return async_1.PromiseWrapper.resolve(route_lifecycle_reflector_1.hasLifecycleHook(hookMod.routerOnReuse, this._currentInstruction.componentType) ? this._componentRef.then(function(ref) { + return ref.instance.routerOnReuse(nextInstruction, previousInstruction); + }) : true); } - 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)); + next = this._componentRef.then(function(ref) { + return ref.instance.routerOnDeactivate(nextInstruction, _this._currentInstruction); + }); } return next.then(function(_) { if (lang_1.isPresent(_this._componentRef)) { - _this._componentRef.dispose(); + var onDispose = _this._componentRef.then(function(ref) { + return ref.dispose(); + }); _this._componentRef = null; + return onDispose; } }); }; RouterOutlet.prototype.routerCanDeactivate = function(nextInstruction) { + var _this = this; 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 this._componentRef.then(function(ref) { + return ref.instance.routerCanDeactivate(nextInstruction, _this._currentInstruction); + }); + } else { + return _resolveToTrue; } - return _resolveToTrue; }; RouterOutlet.prototype.routerCanReuse = function(nextInstruction) { + var _this = this; 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); + result = this._componentRef.then(function(ref) { + return ref.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.prototype.ngOnDestroy = function() { + this._parentRouter.unregisterPrimaryOutlet(this); + }; 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; })(); @@ -1951,10 +2264,19 @@ System.register("angular2/src/router/router_outlet", ["angular2/src/facade/async return module.exports; }); -System.register("angular2/src/router/platform_location", ["angular2/src/platform/dom/dom_adapter", "angular2/core"], true, function(require, exports, module) { +System.register("angular2/src/router/location/browser_platform_location", ["angular2/core", "angular2/src/router/location/platform_location", "angular2/src/platform/dom/dom_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 __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, @@ -1971,26 +2293,36 @@ System.register("angular2/src/router/platform_location", ["angular2/src/platform 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() { + var platform_location_1 = require("angular2/src/router/location/platform_location"); + var dom_adapter_1 = require("angular2/src/platform/dom/dom_adapter"); + var BrowserPlatformLocation = (function(_super) { + __extends(BrowserPlatformLocation, _super); + function BrowserPlatformLocation() { + _super.call(this); this._init(); } - PlatformLocation.prototype._init = function() { + BrowserPlatformLocation.prototype._init = function() { this._location = dom_adapter_1.DOM.getLocation(); this._history = dom_adapter_1.DOM.getHistory(); }; - PlatformLocation.prototype.getBaseHrefFromDOM = function() { + Object.defineProperty(BrowserPlatformLocation.prototype, "location", { + get: function() { + return this._location; + }, + enumerable: true, + configurable: true + }); + BrowserPlatformLocation.prototype.getBaseHrefFromDOM = function() { return dom_adapter_1.DOM.getBaseHref(); }; - PlatformLocation.prototype.onPopState = function(fn) { + BrowserPlatformLocation.prototype.onPopState = function(fn) { dom_adapter_1.DOM.getGlobalEventTarget('window').addEventListener('popstate', fn, false); }; - PlatformLocation.prototype.onHashChange = function(fn) { + BrowserPlatformLocation.prototype.onHashChange = function(fn) { dom_adapter_1.DOM.getGlobalEventTarget('window').addEventListener('hashchange', fn, false); }; - Object.defineProperty(PlatformLocation.prototype, "pathname", { + Object.defineProperty(BrowserPlatformLocation.prototype, "pathname", { get: function() { return this._location.pathname; }, @@ -2000,156 +2332,195 @@ System.register("angular2/src/router/platform_location", ["angular2/src/platform enumerable: true, configurable: true }); - Object.defineProperty(PlatformLocation.prototype, "search", { + Object.defineProperty(BrowserPlatformLocation.prototype, "search", { get: function() { return this._location.search; }, enumerable: true, configurable: true }); - Object.defineProperty(PlatformLocation.prototype, "hash", { + Object.defineProperty(BrowserPlatformLocation.prototype, "hash", { get: function() { return this._location.hash; }, enumerable: true, configurable: true }); - PlatformLocation.prototype.pushState = function(state, title, url) { + BrowserPlatformLocation.prototype.pushState = function(state, title, url) { this._history.pushState(state, title, url); }; - PlatformLocation.prototype.replaceState = function(state, title, url) { + BrowserPlatformLocation.prototype.replaceState = function(state, title, url) { this._history.replaceState(state, title, url); }; - PlatformLocation.prototype.forward = function() { + BrowserPlatformLocation.prototype.forward = function() { this._history.forward(); }; - PlatformLocation.prototype.back = function() { + BrowserPlatformLocation.prototype.back = function() { this._history.back(); }; - PlatformLocation = __decorate([core_1.Injectable(), __metadata('design:paramtypes', [])], PlatformLocation); - return PlatformLocation; - })(); - exports.PlatformLocation = PlatformLocation; + BrowserPlatformLocation = __decorate([core_1.Injectable(), __metadata('design:paramtypes', [])], BrowserPlatformLocation); + return BrowserPlatformLocation; + })(platform_location_1.PlatformLocation); + exports.BrowserPlatformLocation = BrowserPlatformLocation; 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) { +System.register("angular2/src/router/rules/rule_set", ["angular2/src/facade/lang", "angular2/src/facade/exceptions", "angular2/src/facade/collection", "angular2/src/facade/async", "angular2/src/router/rules/rules", "angular2/src/router/route_config/route_config_impl", "angular2/src/router/rules/route_handlers/async_route_handler", "angular2/src/router/rules/route_handlers/sync_route_handler", "angular2/src/router/rules/route_paths/param_route_path", "angular2/src/router/rules/route_paths/regex_route_path"], 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); + var async_1 = require("angular2/src/facade/async"); + var rules_1 = require("angular2/src/router/rules/rules"); + var route_config_impl_1 = require("angular2/src/router/route_config/route_config_impl"); + var async_route_handler_1 = require("angular2/src/router/rules/route_handlers/async_route_handler"); + var sync_route_handler_1 = require("angular2/src/router/rules/route_handlers/sync_route_handler"); + var param_route_path_1 = require("angular2/src/router/rules/route_paths/param_route_path"); + var regex_route_path_1 = require("angular2/src/router/rules/route_paths/regex_route_path"); + var RuleSet = (function() { + function RuleSet() { + this.rulesByName = new collection_1.Map(); + this.auxRulesByName = new collection_1.Map(); + this.auxRulesByPath = new collection_1.Map(); + this.rules = []; + this.defaultRule = null; + } + RuleSet.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 + "\"."); } - return promise_1.PromiseWrapper.resolve(match); + if (config instanceof route_config_impl_1.AuxRoute) { + handler = new sync_route_handler_1.SyncRouteHandler(config.component, config.data); + var routePath_1 = this._getRoutePath(config); + var auxRule = new rules_1.RouteRule(routePath_1, handler); + this.auxRulesByPath.set(routePath_1.toString(), auxRule); + if (lang_1.isPresent(config.name)) { + this.auxRulesByName.set(config.name, auxRule); + } + return auxRule.terminal; + } + var useAsDefault = false; + if (config instanceof route_config_impl_1.Redirect) { + var routePath_2 = this._getRoutePath(config); + var redirector = new rules_1.RedirectRule(routePath_2, config.redirectTo); + this._assertNoHashCollision(redirector.hash, config.path); + this.rules.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 routePath = this._getRoutePath(config); + var newRule = new rules_1.RouteRule(routePath, handler); + this._assertNoHashCollision(newRule.hash, config.path); + if (useAsDefault) { + if (lang_1.isPresent(this.defaultRule)) { + throw new exceptions_1.BaseException("Only one route can be default"); + } + this.defaultRule = newRule; + } + this.rules.push(newRule); + if (lang_1.isPresent(config.name)) { + this.rulesByName.set(config.name, newRule); + } + return newRule.terminal; }; - RedirectRecognizer.prototype.generate = function(params) { - throw new exceptions_1.BaseException("Tried to generate a redirect."); + RuleSet.prototype.recognize = function(urlParse) { + var solutions = []; + this.rules.forEach(function(routeRecognizer) { + var pathMatch = routeRecognizer.recognize(urlParse); + if (lang_1.isPresent(pathMatch)) { + solutions.push(pathMatch); + } + }); + if (solutions.length == 0 && lang_1.isPresent(urlParse) && urlParse.auxiliary.length > 0) { + return [async_1.PromiseWrapper.resolve(new rules_1.PathMatch(null, null, urlParse.auxiliary))]; + } + return solutions; }; - 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)) { + RuleSet.prototype.recognizeAuxiliary = function(urlParse) { + var routeRecognizer = this.auxRulesByPath.get(urlParse.path); + if (lang_1.isPresent(routeRecognizer)) { + return [routeRecognizer.recognize(urlParse)]; + } + return [async_1.PromiseWrapper.resolve(null)]; + }; + RuleSet.prototype.hasRoute = function(name) { + return this.rulesByName.has(name); + }; + RuleSet.prototype.componentLoaded = function(name) { + return this.hasRoute(name) && lang_1.isPresent(this.rulesByName.get(name).handler.componentType); + }; + RuleSet.prototype.loadComponent = function(name) { + return this.rulesByName.get(name).handler.resolveComponentType(); + }; + RuleSet.prototype.generate = function(name, params) { + var rule = this.rulesByName.get(name); + if (lang_1.isBlank(rule)) { 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']); - }); + return rule.generate(params); }; - 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); + RuleSet.prototype.generateAuxiliary = function(name, params) { + var rule = this.auxRulesByName.get(name); + if (lang_1.isBlank(rule)) { + return null; + } + return rule.generate(params); }; - RouteRecognizer.prototype.generateComponentPathValues = function(params) { - return this._pathRecognizer.generate(params); + RuleSet.prototype._assertNoHashCollision = function(hash, path) { + this.rules.forEach(function(rule) { + if (hash == rule.hash) { + throw new exceptions_1.BaseException("Configuration '" + path + "' conflicts with existing route '" + rule.path + "'"); + } + }); }; - 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."); + RuleSet.prototype._getRoutePath = function(config) { + if (lang_1.isPresent(config.regex)) { + if (lang_1.isFunction(config.serializer)) { + return new regex_route_path_1.RegexRoutePath(config.regex, config.serializer); + } else { + throw new exceptions_1.BaseException("Route provides a regex property, '" + config.regex + "', but no serializer property"); + } } - var hashKey = urlPath + '?' + urlParams.join('?'); - if (this._cache.has(hashKey)) { - return this._cache.get(hashKey); + if (lang_1.isPresent(config.path)) { + var path = (config instanceof route_config_impl_1.AuxRoute && config.path.startsWith('/')) ? config.path.substring(1) : config.path; + return new param_route_path_1.ParamRoutePath(path); } - 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; + throw new exceptions_1.BaseException('Route must provide either a path or regex property'); }; - return RouteRecognizer; + return RuleSet; })(); - exports.RouteRecognizer = RouteRecognizer; + exports.RuleSet = RuleSet; + global.define = __define; + return module.exports; +}); + +System.register("angular2/src/router/router_providers", ["angular2/src/router/router_providers_common", "angular2/core", "angular2/src/facade/lang", "angular2/src/router/location/browser_platform_location", "angular2/src/router/location/platform_location"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + var router_providers_common_1 = require("angular2/src/router/router_providers_common"); + var core_1 = require("angular2/core"); + var lang_1 = require("angular2/src/facade/lang"); + var browser_platform_location_1 = require("angular2/src/router/location/browser_platform_location"); + var platform_location_1 = require("angular2/src/router/location/platform_location"); + exports.ROUTER_PROVIDERS = lang_1.CONST_EXPR([router_providers_common_1.ROUTER_PROVIDERS_COMMON, lang_1.CONST_EXPR(new core_1.Provider(platform_location_1.PlatformLocation, {useClass: browser_platform_location_1.BrowserPlatformLocation}))]); + exports.ROUTER_BINDINGS = exports.ROUTER_PROVIDERS; 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) { +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/route_config_impl", "angular2/src/router/rules/rules", "angular2/src/router/rules/rule_set", "angular2/src/router/instruction", "angular2/src/router/route_config/route_config_normalizer", "angular2/src/router/url_parser"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -2180,11 +2551,11 @@ System.register("angular2/src/router/route_registry", ["angular2/src/facade/coll 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 route_config_impl_1 = require("angular2/src/router/route_config/route_config_impl"); + var rules_1 = require("angular2/src/router/rules/rules"); + var rule_set_1 = require("angular2/src/router/rules/rule_set"); var instruction_1 = require("angular2/src/router/instruction"); - var route_config_nomalizer_1 = require("angular2/src/router/route_config_nomalizer"); + var route_config_normalizer_1 = require("angular2/src/router/route_config/route_config_normalizer"); 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')); @@ -2194,18 +2565,18 @@ System.register("angular2/src/router/route_registry", ["angular2/src/facade/coll this._rules = new collection_1.Map(); } RouteRegistry.prototype.config = function(parentComponent, config) { - config = route_config_nomalizer_1.normalizeRouteConfig(config, this); + config = route_config_normalizer_1.normalizeRouteConfig(config, this); if (config instanceof route_config_impl_1.Route) { - route_config_nomalizer_1.assertComponentExists(config.component, config.path); + route_config_normalizer_1.assertComponentExists(config.component, config.path); } else if (config instanceof route_config_impl_1.AuxRoute) { - route_config_nomalizer_1.assertComponentExists(config.component, config.path); + route_config_normalizer_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 rules = this._rules.get(parentComponent); + if (lang_1.isBlank(rules)) { + rules = new rule_set_1.RuleSet(); + this._rules.set(parentComponent, rules); } - var terminal = recognizer.config(config); + var terminal = rules.config(config); if (config instanceof route_config_impl_1.Route) { if (terminal) { assertTerminalComponent(config.component, config.path); @@ -2237,30 +2608,31 @@ System.register("angular2/src/router/route_registry", ["angular2/src/facade/coll }; RouteRegistry.prototype.recognize = function(url, ancestorInstructions) { var parsedUrl = url_parser_1.parser.parse(url); - return this._recognize(parsedUrl, ancestorInstructions); + return this._recognize(parsedUrl, []); }; 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)) { + var parentInstruction = collection_1.ListWrapper.last(ancestorInstructions); + var parentComponent = lang_1.isPresent(parentInstruction) ? parentInstruction.component.componentType : this._rootComponent; + var rules = this._rules.get(parentComponent); + if (lang_1.isBlank(rules)) { return _resolveToNull; } - var possibleMatches = _aux ? componentRecognizer.recognizeAuxiliary(parsedUrl) : componentRecognizer.recognize(parsedUrl); + var possibleMatches = _aux ? rules.recognizeAuxiliary(parsedUrl) : rules.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]] : []; + if (candidate instanceof rules_1.PathMatch) { + var auxParentInstructions = ancestorInstructions.length > 0 ? [collection_1.ListWrapper.last(ancestorInstructions)] : []; var auxInstructions = _this._auxRoutesToUnresolved(candidate.remainingAux, auxParentInstructions); var instruction = new instruction_1.ResolvedInstruction(candidate.instruction, null, auxInstructions); - if (candidate.instruction.terminal) { + if (lang_1.isBlank(candidate.instruction) || candidate.instruction.terminal) { return instruction; } - var newAncestorComponents = ancestorInstructions.concat([instruction]); - return _this._recognize(candidate.remaining, newAncestorComponents).then(function(childInstruction) { + var newAncestorInstructions = ancestorInstructions.concat([instruction]); + return _this._recognize(candidate.remaining, newAncestorInstructions).then(function(childInstruction) { if (lang_1.isBlank(childInstruction)) { return null; } @@ -2271,9 +2643,9 @@ System.register("angular2/src/router/route_registry", ["angular2/src/facade/coll 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 (candidate instanceof rules_1.RedirectMatch) { + var instruction = _this.generate(candidate.redirectTo, ancestorInstructions.concat([null])); + return new instruction_1.RedirectInstruction(instruction.component, instruction.child, instruction.auxInstruction, candidate.specificity); } }); }); @@ -2296,147 +2668,170 @@ System.register("angular2/src/router/route_registry", ["angular2/src/facade/coll 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 == '') { + var params = splitAndFlattenLinkParams(linkParams); + var prevInstruction; + if (collection_1.ListWrapper.first(params) == '') { + params.shift(); + prevInstruction = collection_1.ListWrapper.first(ancestorInstructions); 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 { + prevInstruction = ancestorInstructions.length > 0 ? ancestorInstructions.pop() : null; + if (collection_1.ListWrapper.first(params) == '.') { + params.shift(); + } else if (collection_1.ListWrapper.first(params) == '..') { + while (collection_1.ListWrapper.first(params) == '..') { + if (ancestorInstructions.length <= 0) { + throw new exceptions_1.BaseException("Link \"" + collection_1.ListWrapper.toJSON(linkParams) + "\" has too many \"../\" segments."); + } + prevInstruction = ancestorInstructions.pop(); + params = collection_1.ListWrapper.slice(params, 1); + } + } else { + var routeName = collection_1.ListWrapper.first(params); + var parentComponentType = this._rootComponent; + var grandparentComponentType = null; + if (ancestorInstructions.length > 1) { + var parentComponentInstruction = ancestorInstructions[ancestorInstructions.length - 1]; + var grandComponentInstruction = ancestorInstructions[ancestorInstructions.length - 2]; + parentComponentType = parentComponentInstruction.component.componentType; + grandparentComponentType = grandComponentInstruction.component.componentType; + } else if (ancestorInstructions.length == 1) { + parentComponentType = ancestorInstructions[0].component.componentType; + grandparentComponentType = this._rootComponent; + } + var childRouteExists = this.hasRoute(routeName, parentComponentType); + var parentRouteExists = lang_1.isPresent(grandparentComponentType) && this.hasRoute(routeName, grandparentComponentType); + 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) { + prevInstruction = ancestorInstructions.pop(); } } - } 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 (params[params.length - 1] == '') { + params.pop(); } - if (rest.length < 1) { + if (params.length > 0 && params[0] == '') { + params.shift(); + } + if (params.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); + var generatedInstruction = this._generate(params, ancestorInstructions, prevInstruction, _aux, linkParams); for (var i = ancestorInstructions.length - 1; i >= 0; i--) { var ancestorInstruction = ancestorInstructions[i]; + if (lang_1.isBlank(ancestorInstruction)) { + break; + } generatedInstruction = ancestorInstruction.replaceChild(generatedInstruction); } return generatedInstruction; }; - RouteRegistry.prototype._generate = function(linkParams, ancestorInstructions, _aux) { + RouteRegistry.prototype._generate = function(linkParams, ancestorInstructions, prevInstruction, _aux, _originalLink) { 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 parentComponentType = this._rootComponent; + var componentInstruction = null; + var auxInstructions = {}; + var parentInstruction = collection_1.ListWrapper.last(ancestorInstructions); + if (lang_1.isPresent(parentInstruction) && lang_1.isPresent(parentInstruction.component)) { + parentComponentType = parentInstruction.component.componentType; } - 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; + if (linkParams.length == 0) { + var defaultInstruction = this.generateDefault(parentComponentType); + if (lang_1.isBlank(defaultInstruction)) { + throw new exceptions_1.BaseException("Link \"" + collection_1.ListWrapper.toJSON(_originalLink) + "\" does not resolve to a terminal instruction."); + } + return defaultInstruction; + } + if (lang_1.isPresent(prevInstruction) && !_aux) { + auxInstructions = collection_1.StringMapWrapper.merge(prevInstruction.auxInstruction, auxInstructions); + componentInstruction = prevInstruction.component; + } + var rules = this._rules.get(parentComponentType); + if (lang_1.isBlank(rules)) { + throw new exceptions_1.BaseException("Component \"" + lang_1.getTypeNameForDebugging(parentComponentType) + "\" has no route config."); + } + var linkParamIndex = 0; + var routeParams = {}; + if (linkParamIndex < linkParams.length && lang_1.isString(linkParams[linkParamIndex])) { + var routeName = linkParams[linkParamIndex]; + if (routeName == '' || routeName == '.' || routeName == '..') { + throw new exceptions_1.BaseException("\"" + routeName + "/\" is only allowed at the beginning of a link DSL."); } + linkParamIndex += 1; + if (linkParamIndex < linkParams.length) { + var linkParam = linkParams[linkParamIndex]; + if (lang_1.isStringMap(linkParam) && !lang_1.isArray(linkParam)) { + routeParams = linkParam; + linkParamIndex += 1; + } + } + var routeRecognizer = (_aux ? rules.auxRulesByName : rules.rulesByName).get(routeName); + if (lang_1.isBlank(routeRecognizer)) { + throw new exceptions_1.BaseException("Component \"" + lang_1.getTypeNameForDebugging(parentComponentType) + "\" has no route named \"" + routeName + "\"."); + } + if (lang_1.isBlank(routeRecognizer.handler.componentType)) { + var generatedUrl = routeRecognizer.generateComponentPathValues(routeParams); + return new instruction_1.UnresolvedInstruction(function() { + return routeRecognizer.handler.resolveComponentType().then(function(_) { + return _this._generate(linkParams, ancestorInstructions, prevInstruction, _aux, _originalLink); + }); + }, generatedUrl.urlPath, url_parser_1.convertUrlParamsToArray(generatedUrl.urlParams)); + } + componentInstruction = _aux ? rules.generateAuxiliary(routeName, routeParams) : rules.generate(routeName, routeParams); } - 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); + while (linkParamIndex < linkParams.length && lang_1.isArray(linkParams[linkParamIndex])) { + var auxParentInstruction = [parentInstruction]; + var auxInstruction = this._generate(linkParams[linkParamIndex], auxParentInstruction, null, true, _originalLink); 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 + "\"."); + linkParamIndex += 1; } - 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)) { + if (lang_1.isPresent(componentInstruction) && lang_1.isPresent(componentInstruction.componentType)) { var childInstruction = null; - if (linkIndex + 1 < linkParams.length) { + if (componentInstruction.terminal) { + if (linkParamIndex >= linkParams.length) {} + } else { 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."); - } + var remainingLinkParams = linkParams.slice(linkParamIndex); + childInstruction = this._generate(remainingLinkParams, childAncestorComponents, null, false, _originalLink); } instruction.child = childInstruction; } return instruction; }; RouteRegistry.prototype.hasRoute = function(name, parentComponent) { - var componentRecognizer = this._rules.get(parentComponent); - if (lang_1.isBlank(componentRecognizer)) { + var rules = this._rules.get(parentComponent); + if (lang_1.isBlank(rules)) { return false; } - return componentRecognizer.hasRoute(name); + return rules.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)) { + var rules = this._rules.get(componentCursor); + if (lang_1.isBlank(rules) || lang_1.isBlank(rules.defaultRule)) { 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); + if (lang_1.isPresent(rules.defaultRule.handler.componentType)) { + var componentInstruction = rules.defaultRule.generate({}); + if (!rules.defaultRule.terminal) { + defaultChild = this.generateDefault(rules.defaultRule.handler.componentType); } return new instruction_1.DefaultInstruction(componentInstruction, defaultChild); } return new instruction_1.UnresolvedInstruction(function() { - return componentRecognizer.defaultRoute.handler.resolveComponentType().then(function(_) { + return rules.defaultRule.handler.resolveComponentType().then(function(_) { return _this.generateDefault(componentCursor); }); }); @@ -2446,19 +2841,47 @@ System.register("angular2/src/router/route_registry", ["angular2/src/facade/coll })(); exports.RouteRegistry = RouteRegistry; function splitAndFlattenLinkParams(linkParams) { - return linkParams.reduce(function(accumulation, item) { + var accumulation = []; + linkParams.forEach(function(item) { if (lang_1.isString(item)) { var strItem = item; - return accumulation.concat(strItem.split('/')); + accumulation = accumulation.concat(strItem.split('/')); + } else { + accumulation.push(item); } - accumulation.push(item); - return accumulation; - }, []); + }); + return accumulation; } function mostSpecific(instructions) { - return collection_1.ListWrapper.maximum(instructions, function(instruction) { - return instruction.specificity; + instructions = instructions.filter(function(instruction) { + return lang_1.isPresent(instruction); }); + if (instructions.length == 0) { + return null; + } + if (instructions.length == 1) { + return instructions[0]; + } + var first = instructions[0]; + var rest = instructions.slice(1); + return rest.reduce(function(instruction, contender) { + if (compareSpecificityStrings(contender.specificity, instruction.specificity) == -1) { + return contender; + } + return instruction; + }, first); + } + function compareSpecificityStrings(a, b) { + var l = lang_1.Math.min(a.length, b.length); + for (var i = 0; i < l; i += 1) { + var ai = lang_1.StringWrapper.charCodeAt(a, i); + var bi = lang_1.StringWrapper.charCodeAt(b, i); + var difference = bi - ai; + if (difference != 0) { + return difference; + } + } + return a.length - b.length; } function assertTerminalComponent(component, path) { if (!lang_1.isType(component)) { @@ -2478,7 +2901,7 @@ System.register("angular2/src/router/route_registry", ["angular2/src/facade/coll 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) { +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/location", "angular2/src/router/lifecycle/route_lifecycle_reflector"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -2518,17 +2941,18 @@ System.register("angular2/src/router/router", ["angular2/src/facade/async", "ang 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 location_1 = require("angular2/src/router/location/location"); + var route_lifecycle_reflector_1 = require("angular2/src/router/lifecycle/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) { + function Router(registry, parent, hostComponent, root) { this.registry = registry; this.parent = parent; this.hostComponent = hostComponent; + this.root = root; this.navigating = false; - this._currentInstruction = null; + this.currentInstruction = null; this._currentNavigation = _resolveToTrue; this._outlet = null; this._auxRouters = new collection_1.Map(); @@ -2544,12 +2968,21 @@ System.register("angular2/src/router/router", ["angular2/src/facade/async", "ang if (lang_1.isPresent(outlet.name)) { throw new exceptions_1.BaseException("registerPrimaryOutlet expects to be called with an unnamed outlet."); } + if (lang_1.isPresent(this._outlet)) { + throw new exceptions_1.BaseException("Primary outlet is already registered."); + } this._outlet = outlet; - if (lang_1.isPresent(this._currentInstruction)) { - return this.commit(this._currentInstruction, false); + if (lang_1.isPresent(this.currentInstruction)) { + return this.commit(this.currentInstruction, false); } return _resolveToTrue; }; + Router.prototype.unregisterPrimaryOutlet = function(outlet) { + if (lang_1.isPresent(outlet.name)) { + throw new exceptions_1.BaseException("registerPrimaryOutlet expects to be called with an unnamed outlet."); + } + this._outlet = null; + }; Router.prototype.registerAuxOutlet = function(outlet) { var outletName = outlet.name; if (lang_1.isBlank(outletName)) { @@ -2559,7 +2992,7 @@ System.register("angular2/src/router/router", ["angular2/src/facade/async", "ang this._auxRouters.set(outletName, router); router._outlet = outlet; var auxInstruction; - if (lang_1.isPresent(this._currentInstruction) && lang_1.isPresent(auxInstruction = this._currentInstruction.auxInstruction[outletName])) { + if (lang_1.isPresent(this.currentInstruction) && lang_1.isPresent(auxInstruction = this.currentInstruction.auxInstruction[outletName])) { return router.commit(auxInstruction); } return _resolveToTrue; @@ -2570,7 +3003,7 @@ System.register("angular2/src/router/router", ["angular2/src/facade/async", "ang router = router.parent; instruction = instruction.child; } - return lang_1.isPresent(this._currentInstruction) && this._currentInstruction.component == instruction.component; + return lang_1.isPresent(this.currentInstruction) && this.currentInstruction.component == instruction.component; }; Router.prototype.config = function(definitions) { var _this = this; @@ -2612,6 +3045,22 @@ System.register("angular2/src/router/router", ["angular2/src/facade/async", "ang return _this._afterPromiseFinishNavigating(_this._navigate(instruction, _skipLocationChange)); }); }; + Router.prototype._settleInstruction = function(instruction) { + var _this = this; + return instruction.resolveComponent().then(function(_) { + var unsettledInstructions = []; + if (lang_1.isPresent(instruction.component)) { + instruction.component.reuse = false; + } + 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._navigate = function(instruction, _skipLocationChange) { var _this = this; return this._settleInstruction(instruction).then(function(_) { @@ -2632,23 +3081,12 @@ System.register("angular2/src/router/router", ["angular2/src/facade/async", "ang }); }); }; - 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._emitNavigationFail = function(url) { + async_1.ObservableWrapper.callError(this._subject, url); + }; Router.prototype._afterPromiseFinishNavigating = function(promise) { var _this = this; return async_1.PromiseWrapper.catchError(promise.then(function(_) { @@ -2663,6 +3101,9 @@ System.register("angular2/src/router/router", ["angular2/src/facade/async", "ang if (lang_1.isBlank(this._outlet)) { return _resolveToFalse; } + if (lang_1.isBlank(instruction.component)) { + return _resolveToTrue; + } 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)) { @@ -2671,7 +3112,7 @@ System.register("angular2/src/router/router", ["angular2/src/facade/async", "ang }); }; Router.prototype._canActivate = function(nextInstruction) { - return canActivateOne(nextInstruction, this._currentInstruction); + return canActivateOne(nextInstruction, this.currentInstruction); }; Router.prototype._routerCanDeactivate = function(instruction) { var _this = this; @@ -2685,7 +3126,7 @@ System.register("angular2/src/router/router", ["angular2/src/facade/async", "ang if (lang_1.isPresent(instruction)) { childInstruction = instruction.child; componentInstruction = instruction.component; - reuse = instruction.component.reuse; + reuse = lang_1.isBlank(instruction.component) || instruction.component.reuse; } if (reuse) { next = _resolveToTrue; @@ -2707,9 +3148,9 @@ System.register("angular2/src/router/router", ["angular2/src/facade/async", "ang if (_skipLocationChange === void 0) { _skipLocationChange = false; } - this._currentInstruction = instruction; + this.currentInstruction = instruction; var next = _resolveToTrue; - if (lang_1.isPresent(this._outlet)) { + if (lang_1.isPresent(this._outlet) && lang_1.isPresent(instruction.component)) { var componentInstruction = instruction.component; if (componentInstruction.reuse) { next = this._outlet.reuse(componentInstruction); @@ -2742,8 +3183,8 @@ System.register("angular2/src/router/router", ["angular2/src/facade/async", "ang Router.prototype._finishNavigating = function() { this.navigating = false; }; - Router.prototype.subscribe = function(onNext) { - return async_1.ObservableWrapper.subscribe(this._subject, onNext); + Router.prototype.subscribe = function(onNext, onError) { + return async_1.ObservableWrapper.subscribe(this._subject, onNext, onError); }; Router.prototype.deactivate = function(instruction) { var _this = this; @@ -2769,13 +3210,12 @@ System.register("angular2/src/router/router", ["angular2/src/facade/async", "ang return this.registry.recognize(url, ancestorComponents); }; Router.prototype._getAncestorInstructions = function() { - var ancestorComponents = []; + var ancestorInstructions = [this.currentInstruction]; var ancestorRouter = this; - while (lang_1.isPresent(ancestorRouter.parent) && lang_1.isPresent(ancestorRouter.parent._currentInstruction)) { - ancestorRouter = ancestorRouter.parent; - ancestorComponents.unshift(ancestorRouter._currentInstruction); + while (lang_1.isPresent(ancestorRouter = ancestorRouter.parent)) { + ancestorInstructions.unshift(ancestorRouter.currentInstruction); } - return ancestorComponents; + return ancestorInstructions; }; Router.prototype.renavigate = function() { if (lang_1.isBlank(this.lastNavigationAttempt)) { @@ -2787,6 +3227,7 @@ System.register("angular2/src/router/router", ["angular2/src/facade/async", "ang var ancestorInstructions = this._getAncestorInstructions(); return this.registry.generate(linkParams, ancestorInstructions); }; + Router = __decorate([core_1.Injectable(), __metadata('design:paramtypes', [route_registry_1.RouteRegistry, Router, Object, Router])], Router); return Router; })(); exports.Router = Router; @@ -2795,26 +3236,31 @@ System.register("angular2/src/router/router", ["angular2/src/facade/async", "ang function RootRouter(registry, location, primaryComponent) { var _this = this; _super.call(this, registry, null, primaryComponent); + this.root = this; 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); + if (lang_1.isPresent(instruction)) { + _this.navigateByInstruction(instruction, lang_1.isPresent(change['pop'])).then(function(_) { + if (lang_1.isPresent(change['pop']) && change['type'] != 'hashchange') { + return ; } - } else { - _this._location.go(emitPath, emitQuery); - } - }); + var emitPath = instruction.toUrlPath(); + var emitQuery = instruction.toUrlQuery(); + if (emitPath.length > 0 && emitPath[0] != '/') { + emitPath = '/' + emitPath; + } + if (change['type'] == 'hashchange') { + if (instruction.toRootUrl() != _this._location.path()) { + _this._location.replaceState(emitPath, emitQuery); + } + } else { + _this._location.go(emitPath, emitQuery); + } + }); + } else { + _this._emitNavigationFail(change['url']); + } }); }); this.registry.configFromComponent(primaryComponent); @@ -2827,7 +3273,7 @@ System.register("angular2/src/router/router", ["angular2/src/facade/async", "ang } var emitPath = instruction.toUrlPath(); var emitQuery = instruction.toUrlQuery(); - if (emitPath.length > 0) { + if (emitPath.length > 0 && emitPath[0] != '/') { emitPath = '/' + emitPath; } var promise = _super.prototype.commit.call(this, instruction); @@ -2851,7 +3297,7 @@ System.register("angular2/src/router/router", ["angular2/src/facade/async", "ang var ChildRouter = (function(_super) { __extends(ChildRouter, _super); function ChildRouter(parent, hostComponent) { - _super.call(this, parent.registry, parent, hostComponent); + _super.call(this, parent.registry, parent, hostComponent, parent.root); this.parent = parent; } ChildRouter.prototype.navigateByUrl = function(url, _skipLocationChange) { @@ -2870,6 +3316,9 @@ System.register("angular2/src/router/router", ["angular2/src/facade/async", "ang })(Router); function canActivateOne(nextInstruction, prevInstruction) { var next = _resolveToTrue; + if (lang_1.isBlank(nextInstruction.component)) { + return next; + } if (lang_1.isPresent(nextInstruction.child)) { next = canActivateOne(nextInstruction.child, lang_1.isPresent(prevInstruction) ? prevInstruction.child : null); } @@ -2891,7 +3340,7 @@ System.register("angular2/src/router/router", ["angular2/src/facade/async", "ang 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) { +System.register("angular2/router", ["angular2/src/router/router", "angular2/src/router/directives/router_outlet", "angular2/src/router/directives/router_link", "angular2/src/router/instruction", "angular2/src/router/location/platform_location", "angular2/src/router/route_registry", "angular2/src/router/location/location_strategy", "angular2/src/router/location/hash_location_strategy", "angular2/src/router/location/path_location_strategy", "angular2/src/router/location/location", "angular2/src/router/route_config/route_config_decorator", "angular2/src/router/route_definition", "angular2/src/router/lifecycle/lifecycle_annotations", "angular2/src/router/instruction", "angular2/core", "angular2/src/router/router_providers_common", "angular2/src/router/router_providers", "angular2/src/router/directives/router_outlet", "angular2/src/router/directives/router_link", "angular2/src/facade/lang"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; @@ -2902,69 +3351,45 @@ System.register("angular2/router", ["angular2/src/router/router", "angular2/src/ } var router_1 = require("angular2/src/router/router"); exports.Router = router_1.Router; - var router_outlet_1 = require("angular2/src/router/router_outlet"); + var router_outlet_1 = require("angular2/src/router/directives/router_outlet"); exports.RouterOutlet = router_outlet_1.RouterOutlet; - var router_link_1 = require("angular2/src/router/router_link"); + var router_link_1 = require("angular2/src/router/directives/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"); + var platform_location_1 = require("angular2/src/router/location/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"); + var location_strategy_1 = require("angular2/src/router/location/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"); + var hash_location_strategy_1 = require("angular2/src/router/location/hash_location_strategy"); exports.HashLocationStrategy = hash_location_strategy_1.HashLocationStrategy; - var path_location_strategy_1 = require("angular2/src/router/path_location_strategy"); + var path_location_strategy_1 = require("angular2/src/router/location/path_location_strategy"); exports.PathLocationStrategy = path_location_strategy_1.PathLocationStrategy; - var location_1 = require("angular2/src/router/location"); + var location_1 = require("angular2/src/router/location/location"); exports.Location = location_1.Location; - __export(require("angular2/src/router/route_config_decorator")); + __export(require("angular2/src/router/route_config/route_config_decorator")); __export(require("angular2/src/router/route_definition")); - var lifecycle_annotations_1 = require("angular2/src/router/lifecycle_annotations"); + var lifecycle_annotations_1 = require("angular2/src/router/lifecycle/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 router_providers_common_1 = require("angular2/src/router/router_providers_common"); + exports.ROUTER_PROVIDERS_COMMON = router_providers_common_1.ROUTER_PROVIDERS_COMMON; + var router_providers_1 = require("angular2/src/router/router_providers"); + exports.ROUTER_PROVIDERS = router_providers_1.ROUTER_PROVIDERS; + exports.ROUTER_BINDINGS = router_providers_1.ROUTER_BINDINGS; + var router_outlet_2 = require("angular2/src/router/directives/router_outlet"); + var router_link_2 = require("angular2/src/router/directives/router_link"); 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; }); diff --git a/testapp/ng2/lib/es6-shim/es6-shim.min.js b/testapp/ng2/lib/es6-shim/es6-shim.min.js index 17cdbfa76..6f0d3de23 100644 --- a/testapp/ng2/lib/es6-shim/es6-shim.min.js +++ b/testapp/ng2/lib/es6-shim/es6-shim.min.js @@ -1,12 +1,12 @@ /*! * https://github.com/paulmillr/es6-shim - * @license es6-shim Copyright 2013-2015 by Paul Miller (http://paulmillr.com) + * @license es6-shim Copyright 2013-2016 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 + * es6-shim: v0.35.0 + * see https://github.com/paulmillr/es6-shim/blob/0.35.0/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}); +(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=Object.keys;var o=function notThunker(t){return function notThunk(){return!e(t,this,arguments)}};var i=function(e){try{e();return false}catch(t){return true}};var a=function valueOrFalseIfThrows(e){try{return e()}catch(t){return false}};var u=o(i);var f=function(){return!i(function(){Object.defineProperty({},"x",{get:function(){}})})};var s=!!Object.defineProperty&&f();var c=function foo(){}.name==="foo";var l=Function.call.bind(Array.prototype.forEach);var p=Function.call.bind(Array.prototype.reduce);var v=Function.call.bind(Array.prototype.filter);var y=Function.call.bind(Array.prototype.some);var h=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 b=function(e,t,r){l(n(t),function(n){var o=t[n];h(e,n,o,!!r)})};var g=Function.call.bind(Object.prototype.toString);var d=typeof/abc/==="function"?function IsCallableSlow(e){return typeof e==="function"&&g(e)==="[object Function]"}:function IsCallableFast(e){return typeof e==="function"};var O={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&&d(t.toString)){h(e,"toString",t.toString.bind(t),true)}}};var m=Object.create||function(e,t){var r=function Prototype(){};r.prototype=e;var o=new r;if(typeof t!=="undefined"){n(t).forEach(function(e){O.defineByDescriptor(o,e,t[e])})}return o};var w=function(e,t){if(!Object.setPrototypeOf){return false}return a(function(){var r=function Subclass(t){var r=new e(t);Object.setPrototypeOf(r,Subclass.prototype);return r};Object.setPrototypeOf(r,e);r.prototype=m(e.prototype,{constructor:{value:r}});return t(r)})};var j=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 S=j();var T=S.isFinite;var I=Function.call.bind(String.prototype.indexOf);var E=Function.apply.bind(Array.prototype.indexOf);var P=Function.call.bind(Array.prototype.concat);var M=Function.call.bind(Array.prototype.sort);var C=Function.call.bind(String.prototype.slice);var x=Function.call.bind(Array.prototype.push);var N=Function.apply.bind(Array.prototype.push);var A=Function.call.bind(Array.prototype.shift);var R=Math.max;var _=Math.min;var k=Math.floor;var F=Math.abs;var L=Math.log;var D=Math.sqrt;var z=Function.call.bind(Object.prototype.hasOwnProperty);var q;var G=function(){};var W=S.Symbol||{};var H=W.species||"@@species";var V=Number.isNaN||function isNaN(e){return e!==e};var B=Number.isFinite||function isFinite(e){return typeof e==="number"&&T(e)};var $=function isArguments(e){return g(e)==="[object Arguments]"};var U=function isArguments(e){return e!==null&&typeof e==="object"&&typeof e.length==="number"&&e.length>=0&&g(e)!=="[object Array]"&&g(e.callee)==="[object Function]"};var J=$(arguments)?$:U;var K={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 g(e)==="[object String]"},regex:function(e){return g(e)==="[object RegExp]"},symbol:function(e){return typeof S.Symbol==="function"&&typeof e==="symbol"}};var X=function overrideNative(e,t,r){var n=e[t];h(e,t,r,true);O.preserveToString(e[t],n)};var Z=typeof W==="function"&&typeof W["for"]==="function"&&K.symbol(W());var Y=K.symbol(W.iterator)?W.iterator:"_es6-shim iterator_";if(S.Set&&typeof(new S.Set)["@@iterator"]==="function"){Y="@@iterator"}if(!S.Reflect){h(S,"Reflect",{},true)}var Q=S.Reflect;var ee=String;var te={Call:function Call(t,r){var n=arguments.length>2?arguments[2]:[];if(!te.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)}return e},TypeIsObject:function(e){if(e===void 0||e===null||e===true||e===false){return false}return typeof e==="function"||typeof e==="object"},ToObject:function(e,t){return Object(te.RequireObjectCoercible(e,t))},IsCallable:d,IsConstructor:function(e){return te.IsCallable(e)},ToInt32:function(e){return te.ToNumber(e)>>0},ToUint32:function(e){return te.ToNumber(e)>>>0},ToNumber:function(e){if(g(e)==="[object Symbol]"){throw new TypeError("Cannot convert a Symbol value to a number")}return+e},ToInteger:function(e){var t=te.ToNumber(e);if(V(t)){return 0}if(t===0||!B(t)){return t}return(t>0?1:-1)*k(F(t))},ToLength:function(e){var t=te.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 V(e)&&V(t)},SameValueZero:function(e,t){return e===t||V(e)&&V(t)},IsIterable:function(e){return te.TypeIsObject(e)&&(typeof e[Y]!=="undefined"||J(e))},GetIterator:function(e){if(J(e)){return new q(e,"value")}var t=te.GetMethod(e,Y);if(!te.IsCallable(t)){throw new TypeError("value is not an iterable")}var r=te.Call(t,e);if(!te.TypeIsObject(r)){throw new TypeError("bad iterator")}return r},GetMethod:function(e,t){var r=te.ToObject(e)[t];if(r===void 0||r===null){return void 0}if(!te.IsCallable(r)){throw new TypeError("Method not callable: "+t)}return r},IteratorComplete:function(e){return!!e.done},IteratorClose:function(e,t){var r=te.GetMethod(e,"return");if(r===void 0){return}var n,o;try{n=te.Call(r,e)}catch(i){o=i}if(t){return}if(o){throw o}if(!te.TypeIsObject(n)){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(!te.TypeIsObject(t)){throw new TypeError("bad iterator")}return t},IteratorStep:function(e){var t=te.IteratorNext(e);var r=te.IteratorComplete(t);return r?false:t},Construct:function(e,t,r,n){var o=typeof r==="undefined"?e:r;if(!n&&Q.construct){return Q.construct(e,t,o)}var i=o.prototype;if(!te.TypeIsObject(i)){i=Object.prototype}var a=m(i);var u=te.Call(e,a,t);return te.TypeIsObject(u)?u:a},SpeciesConstructor:function(e,t){var r=e.constructor;if(r===void 0){return t}if(!te.TypeIsObject(r)){throw new TypeError("Bad constructor")}var n=r[H];if(n===void 0||n===null){return t}if(!te.IsConstructor(n)){throw new TypeError("Bad @@species")}return n},CreateHTML:function(e,t,r,n){var o=te.ToString(e);var i="<"+t;if(r!==""){var a=te.ToString(n);var u=a.replace(/"/g,""");i+=" "+r+'="'+u+'"'}var f=i+">";var s=f+o;return s+""},IsRegExp:function IsRegExp(e){if(!te.TypeIsObject(e)){return false}var t=e[W.match];if(typeof t!=="undefined"){return!!t}return K.regex(e)},ToString:function ToString(e){return ee(e)}};if(s&&Z){var re=function defineWellKnownSymbol(e){if(K.symbol(W[e])){return W[e]}var t=W["for"]("Symbol."+e);Object.defineProperty(W,e,{configurable:false,enumerable:false,writable:false,value:t});return t};if(!K.symbol(W.search)){var ne=re("search");var oe=String.prototype.search;h(RegExp.prototype,ne,function search(e){return te.Call(oe,e,[this])});var ie=function search(e){var t=te.RequireObjectCoercible(this);if(e!==null&&typeof e!=="undefined"){var r=te.GetMethod(e,ne);if(typeof r!=="undefined"){return te.Call(r,e,[t])}}return te.Call(oe,t,[te.ToString(e)])};X(String.prototype,"search",ie)}if(!K.symbol(W.replace)){var ae=re("replace");var ue=String.prototype.replace;h(RegExp.prototype,ae,function replace(e,t){return te.Call(ue,e,[this,t])});var fe=function replace(e,t){var r=te.RequireObjectCoercible(this);if(e!==null&&typeof e!=="undefined"){var n=te.GetMethod(e,ae);if(typeof n!=="undefined"){return te.Call(n,e,[r,t])}}return te.Call(ue,r,[te.ToString(e),t])};X(String.prototype,"replace",fe)}if(!K.symbol(W.split)){var se=re("split");var ce=String.prototype.split;h(RegExp.prototype,se,function split(e,t){return te.Call(ce,e,[this,t])});var le=function split(e,t){var r=te.RequireObjectCoercible(this);if(e!==null&&typeof e!=="undefined"){var n=te.GetMethod(e,se);if(typeof n!=="undefined"){return te.Call(n,e,[r,t])}}return te.Call(ce,r,[te.ToString(e),t])};X(String.prototype,"split",le)}var pe=K.symbol(W.match);var ve=pe&&function(){var e={};e[W.match]=function(){return 42};return"a".match(e)!==42}();if(!pe||ve){var ye=re("match");var he=String.prototype.match;h(RegExp.prototype,ye,function match(e){return te.Call(he,e,[this])});var be=function match(e){var t=te.RequireObjectCoercible(this);if(e!==null&&typeof e!=="undefined"){var r=te.GetMethod(e,ye);if(typeof r!=="undefined"){return te.Call(r,e,[t])}}return te.Call(he,t,[te.ToString(e)])};X(String.prototype,"match",be)}}var ge=function wrapConstructor(e,t,r){O.preserveToString(t,e);if(Object.setPrototypeOf){Object.setPrototypeOf(e,t)}if(s){l(Object.getOwnPropertyNames(e),function(n){if(n in G||r[n]){return}O.proxy(e,n,t)})}else{l(Object.keys(e),function(n){if(n in G||r[n]){return}t[n]=e[n]})}t.prototype=e.prototype;O.redefine(e.prototype,"constructor",t)};var de=function(){return this};var Oe=function(e){if(s&&!z(e,H)){O.getter(e,H,de)}};var me=function(e,t){var r=t||function iterator(){return this};h(e,Y,r);if(!e[Y]&&K.symbol(Y)){e[Y]=r}};var we=function createDataProperty(e,t,r){if(s){Object.defineProperty(e,t,{configurable:true,enumerable:true,writable:true,value:r})}else{e[t]=r}};var je=function createDataPropertyOrThrow(e,t,r){we(e,t,r);if(!te.SameValue(e[t],r)){throw new TypeError("property is nonconfigurable")}};var Se=function(e,t,r,n){if(!te.TypeIsObject(e)){throw new TypeError("Constructor requires `new`: "+t.name)}var o=t.prototype;if(!te.TypeIsObject(o)){o=r}var i=m(o);for(var a in n){if(z(n,a)){var u=n[a];h(i,a,u,true)}}return i};if(String.fromCodePoint&&String.fromCodePoint.length!==1){var Te=String.fromCodePoint;X(String,"fromCodePoint",function fromCodePoint(e){return te.Call(Te,this,arguments)})}var Ie={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){x(t,String.fromCharCode(r))}else{r-=65536;x(t,String.fromCharCode((r>>10)+55296));x(t,String.fromCharCode(r%1024+56320))}}return t.join("")},raw:function raw(e){var t=te.ToObject(e,"bad callSite");var r=te.ToObject(t.raw,"bad raw value");var n=r.length;var o=te.ToLength(n);if(o<=0){return""}var i=[];var a=0;var u,f,s,c;while(a=o){break}f=a+1=Pe){throw new RangeError("repeat count must be less than infinity and not overflow maximum string size")}return Ee(t,r)},startsWith:function startsWith(e){var t=te.ToString(te.RequireObjectCoercible(this));if(te.IsRegExp(e)){throw new TypeError('Cannot call method "startsWith" with a regex')}var r=te.ToString(e);var n;if(arguments.length>1){n=arguments[1]}var o=R(te.ToInteger(n),0);return C(t,o,o+r.length)===r},endsWith:function endsWith(e){var t=te.ToString(te.RequireObjectCoercible(this));if(te.IsRegExp(e)){throw new TypeError('Cannot call method "endsWith" with a regex')}var r=te.ToString(e);var n=t.length;var o;if(arguments.length>1){o=arguments[1]}var i=typeof o==="undefined"?n:te.ToInteger(o);var a=_(R(i,0),n);return C(t,a-r.length,a)===r},includes:function includes(e){if(te.IsRegExp(e)){throw new TypeError('"includes" does not accept a RegExp')}var t=te.ToString(e);var r;if(arguments.length>1){r=arguments[1]}return I(this,t,r)!==-1},codePointAt:function codePointAt(e){var t=te.ToString(te.RequireObjectCoercible(this));var r=te.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){X(String.prototype,"includes",Me.includes)}if(String.prototype.startsWith&&String.prototype.endsWith){var Ce=i(function(){"/a/".startsWith(/a/)});var xe=a(function(){return"abc".startsWith("a",Infinity)===false});if(!Ce||!xe){X(String.prototype,"startsWith",Me.startsWith);X(String.prototype,"endsWith",Me.endsWith)}}if(Z){var Ne=a(function(){var e=/a/;e[W.match]=false;return"/a/".startsWith(e)});if(!Ne){X(String.prototype,"startsWith",Me.startsWith)}var Ae=a(function(){var e=/a/;e[W.match]=false;return"/a/".endsWith(e)});if(!Ae){X(String.prototype,"endsWith",Me.endsWith)}var Re=a(function(){var e=/a/;e[W.match]=false;return"/a/".includes(e)});if(!Re){X(String.prototype,"includes",Me.includes)}}b(String.prototype,Me);var _e=[" \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 ke=new RegExp("(^["+_e+"]+)|(["+_e+"]+$)","g");var Fe=function trim(){return te.ToString(te.RequireObjectCoercible(this)).replace(ke,"")};var Le=["\x85","\u200b","\ufffe"].join("");var De=new RegExp("["+Le+"]","g");var ze=/^[\-+]0x[0-9a-f]+$/i;var qe=Le.trim().length!==Le.length;h(String.prototype,"trim",Fe,qe);var Ge=function(e){te.RequireObjectCoercible(e);this._s=te.ToString(e);this._i=0};Ge.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}};me(Ge.prototype);me(String.prototype,function(){return new Ge(this)});var We={from:function from(e){var r=this;var n;if(arguments.length>1){n=arguments[1]}var o,i;if(typeof n==="undefined"){o=false}else{if(!te.IsCallable(n)){throw new TypeError("Array.from: when provided, the second argument must be a function")}if(arguments.length>2){i=arguments[2]}o=true}var a=typeof(J(e)||te.GetMethod(e,Y))!=="undefined";var u,f,s;if(a){f=te.IsConstructor(r)?Object(new r):[];var c=te.GetIterator(e);var l,p;s=0;while(true){l=te.IteratorStep(c);if(l===false){break}p=l.value;try{if(o){p=typeof i==="undefined"?n(p,s):t(n,i,p,s)}f[s]=p}catch(v){te.IteratorClose(c,true);throw v}s+=1}u=s}else{var y=te.ToObject(e);u=te.ToLength(y.length);f=te.IsConstructor(r)?Object(new r(u)):new Array(u);var h;for(s=0;s2){f=arguments[2]}var s=typeof f==="undefined"?n:te.ToInteger(f);var c=s<0?R(n+s,0):_(s,n);var l=_(c-u,n-a);var p=1;if(u0){if(u in r){r[a]=r[u]}else{delete r[a]}u+=p;a+=p;l-=1}return r},fill:function fill(e){var t;if(arguments.length>1){t=arguments[1]}var r;if(arguments.length>2){r=arguments[2]}var n=te.ToObject(this);var o=te.ToLength(n.length);t=te.ToInteger(typeof t==="undefined"?0:t);r=te.ToInteger(typeof r==="undefined"?o:r);var i=t<0?R(o+t,0):_(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;i1&&typeof arguments[1]!=="undefined"){return te.Call(Ye,this,arguments)}else{return t(Ye,this,e)}})}var Qe=-(Math.pow(2,32)-1);var et=function(e,r){var n={length:Qe};n[r?(n.length>>>0)-1:0]=true;return a(function(){t(e,n,function(){throw new RangeError("should not reach here")},[]);return true})};if(!et(Array.prototype.forEach)){var tt=Array.prototype.forEach;X(Array.prototype,"forEach",function forEach(e){return te.Call(tt,this.length>=0?this:[],arguments)},true)}if(!et(Array.prototype.map)){var rt=Array.prototype.map;X(Array.prototype,"map",function map(e){return te.Call(rt,this.length>=0?this:[],arguments)},true)}if(!et(Array.prototype.filter)){var nt=Array.prototype.filter;X(Array.prototype,"filter",function filter(e){return te.Call(nt,this.length>=0?this:[],arguments)},true)}if(!et(Array.prototype.some)){var ot=Array.prototype.some;X(Array.prototype,"some",function some(e){return te.Call(ot,this.length>=0?this:[],arguments)},true)}if(!et(Array.prototype.every)){var it=Array.prototype.every;X(Array.prototype,"every",function every(e){return te.Call(it,this.length>=0?this:[],arguments)},true)}if(!et(Array.prototype.reduce)){var at=Array.prototype.reduce;X(Array.prototype,"reduce",function reduce(e){return te.Call(at,this.length>=0?this:[],arguments)},true)}if(!et(Array.prototype.reduceRight,true)){var ut=Array.prototype.reduceRight;X(Array.prototype,"reduceRight",function reduceRight(e){return te.Call(ut,this.length>=0?this:[],arguments)},true)}var ft=Number("0o10")!==8;var st=Number("0b10")!==2;var ct=y(Le,function(e){return Number(e+0+e)===0});if(ft||st||ct){var lt=Number;var pt=/^0b[01]+$/i;var vt=/^0o[0-7]+$/i;var yt=pt.test.bind(pt);var ht=vt.test.bind(vt);var bt=function(e){var t;if(typeof e.valueOf==="function"){t=e.valueOf();if(K.primitive(t)){return t}}if(typeof e.toString==="function"){t=e.toString();if(K.primitive(t)){return t}}throw new TypeError("No default value")};var gt=De.test.bind(De);var dt=ze.test.bind(ze);var Ot=function(){var e=function Number(t){var r;if(arguments.length>0){r=K.primitive(t)?t:bt(t,"number")}else{r=0}if(typeof r==="string"){r=te.Call(Fe,r);if(yt(r)){r=parseInt(C(r,2),2)}else if(ht(r)){r=parseInt(C(r,2),8)}else if(gt(r)||dt(r)){r=NaN}}var n=this;var o=a(function(){lt.prototype.valueOf.call(n);return true});if(n instanceof e&&!o){return new lt(r)}return lt(r)};return e}();ge(lt,Ot,{});b(Ot,{NaN:lt.NaN,MAX_VALUE:lt.MAX_VALUE,MIN_VALUE:lt.MIN_VALUE,NEGATIVE_INFINITY:lt.NEGATIVE_INFINITY,POSITIVE_INFINITY:lt.POSITIVE_INFINITY});Number=Ot;O.redefine(S,"Number",Ot)}var mt=Math.pow(2,53)-1;b(Number,{MAX_SAFE_INTEGER:mt,MIN_SAFE_INTEGER:-mt,EPSILON:2.220446049250313e-16,parseInt:S.parseInt,parseFloat:S.parseFloat,isFinite:B,isInteger:function isInteger(e){return B(e)&&te.ToInteger(e)===e},isSafeInteger:function isSafeInteger(e){return Number.isInteger(e)&&F(e)<=Number.MAX_SAFE_INTEGER},isNaN:V});h(Number,"parseInt",S.parseInt,Number.parseInt!==S.parseInt);if(![,1].find(function(e,t){return t===0})){X(Array.prototype,"find",Ue.find)}if([,1].findIndex(function(e,t){return t===0})!==0){X(Array.prototype,"findIndex",Ue.findIndex)}var wt=Function.bind.call(Function.bind,Object.prototype.propertyIsEnumerable);var jt=function ensureEnumerable(e,t){if(s&&wt(e,t)){Object.defineProperty(e,t,{enumerable:false})}};var St=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*L((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(L(t)/3);n=(t/(n*n)+2*n)/3}return r?-n:n},clz32:function clz32(e){var t=Number(e);var r=te.ToUint32(t);if(r===0){return 32}return gr?te.Call(gr,r):31-k(L(r+.5)*Math.LOG2E)},cosh:function cosh(e){var t=Number(e);if(t===0){return 1}if(Number.isNaN(t)){return NaN}if(!T(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(!T(t)||t===0){return t}if(F(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*D(r)},log2:function log2(e){return L(e)*Math.LOG2E},log10:function log10(e){return L(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*(L(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(!T(t)||t===0){return t}if(F(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>=20){return 1}if(t<=-20){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?-k(-t):k(t)},imul:function imul(e,t){var r=te.ToUint32(e);var n=te.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||V(t)){return t}var r=Math.sign(t);var n=F(t);if(nhr||V(i)){return r*Infinity}return r*i}};b(Math,dr);h(Math,"log1p",dr.log1p,Math.log1p(-1e-17)!==-1e-17);h(Math,"asinh",dr.asinh,Math.asinh(-1e7)!==-Math.asinh(1e7));h(Math,"tanh",dr.tanh,Math.tanh(-2e-17)!==-2e-17);h(Math,"acosh",dr.acosh,Math.acosh(Number.MAX_VALUE)===Infinity);h(Math,"cbrt",dr.cbrt,Math.abs(1-Math.cbrt(1e-300)/1e-100)/Number.EPSILON>8);h(Math,"sinh",dr.sinh,Math.sinh(-2e-17)!==-2e-17);var Or=Math.expm1(10);h(Math,"expm1",dr.expm1,Or>22025.465794806718||Or<22025.465794806718); +var mr=Math.round;var wr=Math.round(.5-Number.EPSILON/4)===0&&Math.round(-.5+Number.EPSILON/3.99)===1;var jr=pr+1;var Sr=2*pr-1;var Tr=[jr,Sr].every(function(e){return Math.round(e)===e});h(Math,"round",function round(e){var t=k(e);var r=t===-1?-0:t+1;return e-t<.5?t:r},!wr||!Tr);O.preserveToString(Math.round,mr);var Ir=Math.imul;if(Math.imul(4294967295,5)!==-5){Math.imul=dr.imul;O.preserveToString(Math.imul,Ir)}if(Math.imul.length!==2){X(Math,"imul",function imul(e,t){return te.Call(Ir,Math,arguments)})}var Er=function(){var e=S.setTimeout;if(typeof e!=="function"&&typeof e!=="object"){return}te.IsPromise=function(e){if(!te.TypeIsObject(e)){return false}if(typeof e._promise==="undefined"){return false}return true};var r=function(e){if(!te.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.resolve=void 0;t.reject=void 0;t.promise=new e(r);if(!(te.IsCallable(t.resolve)&&te.IsCallable(t.reject))){throw new TypeError("Bad promise constructor")}};var n;if(typeof window!=="undefined"&&te.IsCallable(window.postMessage)){n=function(){var e=[];var t="zero-timeout-message";var r=function(r){x(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=A(e);n()}};window.addEventListener("message",n,true);return r}}var o=function(){var e=S.Promise;var t=e&&e.resolve&&e.resolve();return t&&function(e){return t.then(e)}};var i=te.IsCallable(S.setImmediate)?S.setImmediate:typeof process==="object"&&process.nextTick?process.nextTick:o()||(te.IsCallable(n)?n():function(t){e(t,0)});var a=function(e){return e};var u=function(e){throw e};var f=0;var s=1;var c=2;var l=0;var p=1;var v=2;var y={};var h=function(e,t,r){i(function(){g(e,t,r)})};var g=function(e,t,r){var n,o;if(t===y){return e(r)}try{n=e(r);o=t.resolve}catch(i){n=i;o=t.reject}o(n)};var d=function(e,t){var r=e._promise;var n=r.reactionLength;if(n>0){h(r.fulfillReactionHandler0,r.reactionCapability0,t);r.fulfillReactionHandler0=void 0;r.rejectReactions0=void 0;r.reactionCapability0=void 0;if(n>1){for(var o=1,i=0;o0){h(r.rejectReactionHandler0,r.reactionCapability0,t);r.fulfillReactionHandler0=void 0;r.rejectReactions0=void 0;r.reactionCapability0=void 0;if(n>1){for(var o=1,i=0;o2&&arguments[2]===y;if(b&&o===E){i=y}else{i=new r(o)}var g=te.IsCallable(e)?e:a;var d=te.IsCallable(t)?t:u;var O=n._promise;var m;if(O.state===f){if(O.reactionLength===0){O.fulfillReactionHandler0=g;O.rejectReactionHandler0=d;O.reactionCapability0=i}else{var w=3*(O.reactionLength-1);O[w+l]=g;O[w+p]=d;O[w+v]=i}O.reactionLength+=1}else if(O.state===s){m=O.result;h(g,i,m)}else if(O.state===c){m=O.result;h(d,i,m)}else{throw new TypeError("unexpected Promise state")}return i.promise}});y=new r(E);I=T.then;return E}();if(S.Promise){delete S.Promise.accept;delete S.Promise.defer;delete S.Promise.prototype.chain}if(typeof Er==="function"){b(S,{Promise:Er});var Pr=w(S.Promise,function(e){return e.resolve(42).then(function(){})instanceof e});var Mr=!i(function(){S.Promise.reject(42).then(null,5).then(null,G)});var Cr=i(function(){S.Promise.call(3,G)});var xr=function(e){var t=e.resolve(5);t.constructor={};var r=e.resolve(t);try{r.then(null,G).then(null,G)}catch(n){return true}return t===r}(S.Promise);var Nr=s&&function(){var e=0;var t=Object.defineProperty({},"then",{get:function(){e+=1}});Promise.resolve(t);return e===1}();var Ar=function BadResolverPromise(e){var t=new Promise(e);e(3,function(){});this.then=t.then;this.constructor=BadResolverPromise};Ar.prototype=Promise.prototype;Ar.all=Promise.all;var Rr=a(function(){return!!Ar.all([1,2])});if(!Pr||!Mr||!Cr||xr||!Nr||Rr){Promise=Er;X(S,"Promise",Er)}if(Promise.all.length!==1){var _r=Promise.all;X(Promise,"all",function all(e){return te.Call(_r,this,arguments)})}if(Promise.race.length!==1){var kr=Promise.race;X(Promise,"race",function race(e){return te.Call(kr,this,arguments)})}if(Promise.resolve.length!==1){var Fr=Promise.resolve;X(Promise,"resolve",function resolve(e){return te.Call(Fr,this,arguments)})}if(Promise.reject.length!==1){var Lr=Promise.reject;X(Promise,"reject",function reject(e){return te.Call(Lr,this,arguments)})}jt(Promise,"all");jt(Promise,"race");jt(Promise,"resolve");jt(Promise,"reject");Oe(Promise)}var Dr=function(e){var t=n(p(e,function(e,t){e[t]=true;return e},{}));return e.join(":")===t.join(":")};var zr=Dr(["z","a","bb"]);var qr=Dr(["z",1,"a","3",2]);if(s){var Gr=function fastkey(e){if(!zr){return null}if(typeof e==="undefined"||e===null){return"^"+te.ToString(e)}else if(typeof e==="string"){return"$"+e}else if(typeof e==="number"){if(!qr){return"n"+e}return e}else if(typeof e==="boolean"){return"b"+e}return null};var Wr=function emptyObject(){return Object.create?Object.create(null):{}};var Hr=function addIterableToMap(e,n,o){if(r(o)||K.string(o)){l(o,function(e){if(!te.TypeIsObject(e)){throw new TypeError("Iterator value "+e+" is not an entry object")}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(!te.IsCallable(a)){throw new TypeError("bad map")}i=te.GetIterator(o)}if(typeof i!=="undefined"){while(true){var u=te.IteratorStep(i);if(u===false){break}var f=u.value;try{if(!te.TypeIsObject(f)){throw new TypeError("Iterator value "+f+" is not an entry object")}t(a,n,f[0],f[1])}catch(s){te.IteratorClose(i,true);throw s}}}}};var Vr=function addIterableToSet(e,n,o){if(r(o)||K.string(o)){l(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(!te.IsCallable(a)){throw new TypeError("bad set")}i=te.GetIterator(o)}if(typeof i!=="undefined"){while(true){var u=te.IteratorStep(i);if(u===false){break}var f=u.value;try{t(a,n,f)}catch(s){te.IteratorClose(i,true);throw s}}}}};var Br={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(!te.TypeIsObject(e)||!n(e)){throw new TypeError("Method Map.prototype."+t+" called on incompatible receiver "+te.ToString(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}}};me(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=Se(this,Map,a,{_es6map:true,_head:null,_storage:Wr(),_size:0});var t=new r(null,null);t.next=t.prev=t;e._head=t;if(arguments.length>0){Hr(Map,e,arguments[0])}return e};a=u.prototype;O.getter(a,"size",function(){if(typeof this._size==="undefined"){throw new TypeError("size method called on incompatible Map")}return this._size});b(a,{get:function get(e){o(this,"get");var t=Gr(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(te.SameValueZero(i.key,e)){return i.value}}},has:function has(e){o(this,"has");var t=Gr(e);if(t!==null){return typeof this._storage[t]!=="undefined"}var r=this._head,n=r;while((n=n.next)!==r){if(te.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=Gr(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(te.SameValueZero(i.key,e)){i.value=t;return this}}a=a||new r(e,t);if(te.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=Gr(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(te.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=Wr();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)}}}});me(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(!te.TypeIsObject(t)||!e(t)){throw new TypeError("Set.prototype."+r+" called on incompatible receiver "+te.ToString(t))}};var o;var i=function Set(){if(!(this instanceof Set)){throw new TypeError('Constructor Set requires "new"')}if(this&&this._es6set){throw new TypeError("Bad construction")}var e=Se(this,Set,o,{_es6set:true,"[[SetData]]":null,_storage:Wr()});if(!e._es6set){throw new TypeError("bad set")}if(arguments.length>0){Vr(Set,e,arguments[0])}return e};o=i.prototype;var a=function(e){var t=e;if(t==="^null"){return null}else if(t==="^undefined"){return void 0}else{var r=t.charAt(0);if(r==="$"){return C(t,1)}else if(r==="n"){return+C(t,1)}else if(r==="b"){return t==="btrue"}}return+t};var u=function ensureMap(e){if(!e["[[SetData]]"]){var t=e["[[SetData]]"]=new Br.Map;l(n(e._storage),function(e){var r=a(e);t.set(r,r)});e["[[SetData]]"]=t}e._storage=null};O.getter(i.prototype,"size",function(){r(this,"size");if(this._storage){return n(this._storage).length}u(this);return this["[[SetData]]"].size});b(i.prototype,{has:function has(e){r(this,"has");var t;if(this._storage&&(t=Gr(e))!==null){return!!this._storage[t]}u(this);return this["[[SetData]]"].has(e)},add:function add(e){r(this,"add");var t;if(this._storage&&(t=Gr(e))!==null){this._storage[t]=true;return this}u(this);this["[[SetData]]"].set(e,e);return this},"delete":function(e){r(this,"delete");var t;if(this._storage&&(t=Gr(e))!==null){var n=z(this._storage,t);return delete this._storage[t]&&n}u(this);return this["[[SetData]]"]["delete"](e)},clear:function clear(){r(this,"clear");if(this._storage){this._storage=Wr()}if(this["[[SetData]]"]){this["[[SetData]]"].clear()}},values:function values(){r(this,"values");u(this);return this["[[SetData]]"].values()},entries:function entries(){r(this,"entries");u(this);return this["[[SetData]]"].entries()},forEach:function forEach(e){r(this,"forEach");var n=arguments.length>1?arguments[1]:null;var o=this;u(o);this["[[SetData]]"].forEach(function(r,i){if(n){t(e,n,i,i,o)}else{e(i,i,o)}})}});h(i.prototype,"keys",i.prototype.values,true);me(i.prototype,i.prototype.values);return i}()};if(S.Map||S.Set){var $r=a(function(){return new Map([[1,2]]).get(1)===2});if(!$r){var Ur=S.Map;S.Map=function Map(){if(!(this instanceof Map)){throw new TypeError('Constructor Map requires "new"')}var e=new Ur;if(arguments.length>0){Hr(Map,e,arguments[0])}delete e.constructor;Object.setPrototypeOf(e,S.Map.prototype);return e};S.Map.prototype=m(Ur.prototype);h(S.Map.prototype,"constructor",S.Map,true);O.preserveToString(S.Map,Ur)}var Jr=new Map;var Kr=function(){var e=new Map([[1,0],[2,0],[3,0],[4,0]]);e.set(-0,e);return e.get(0)===e&&e.get(-0)===e&&e.has(0)&&e.has(-0)}();var Xr=Jr.set(1,2)===Jr;if(!Kr||!Xr){var Zr=Map.prototype.set;X(Map.prototype,"set",function set(e,r){t(Zr,this,e===0?0:e,r);return this})}if(!Kr){var Yr=Map.prototype.get;var Qr=Map.prototype.has;b(Map.prototype,{get:function get(e){return t(Yr,this,e===0?0:e)},has:function has(e){return t(Qr,this,e===0?0:e)}},true);O.preserveToString(Map.prototype.get,Yr);O.preserveToString(Map.prototype.has,Qr)}var en=new Set;var tn=function(e){e["delete"](0);e.add(-0);return!e.has(0)}(en);var rn=en.add(1)===en;if(!tn||!rn){var nn=Set.prototype.add;Set.prototype.add=function add(e){t(nn,this,e===0?0:e);return this};O.preserveToString(Set.prototype.add,nn)}if(!tn){var on=Set.prototype.has;Set.prototype.has=function has(e){return t(on,this,e===0?0:e)};O.preserveToString(Set.prototype.has,on);var an=Set.prototype["delete"];Set.prototype["delete"]=function SetDelete(e){return t(an,this,e===0?0:e)};O.preserveToString(Set.prototype["delete"],an)}var un=w(S.Map,function(e){var t=new e([]);t.set(42,42);return t instanceof e});var fn=Object.setPrototypeOf&&!un;var sn=function(){try{return!(S.Map()instanceof S.Map)}catch(e){return e instanceof TypeError}}();if(S.Map.length!==0||fn||!sn){var cn=S.Map;S.Map=function Map(){if(!(this instanceof Map)){throw new TypeError('Constructor Map requires "new"')}var e=new cn;if(arguments.length>0){Hr(Map,e,arguments[0])}delete e.constructor;Object.setPrototypeOf(e,Map.prototype);return e};S.Map.prototype=cn.prototype;h(S.Map.prototype,"constructor",S.Map,true);O.preserveToString(S.Map,cn)}var ln=w(S.Set,function(e){var t=new e([]);t.add(42,42);return t instanceof e});var pn=Object.setPrototypeOf&&!ln;var vn=function(){try{return!(S.Set()instanceof S.Set)}catch(e){return e instanceof TypeError}}();if(S.Set.length!==0||pn||!vn){var yn=S.Set;S.Set=function Set(){if(!(this instanceof Set)){throw new TypeError('Constructor Set requires "new"')}var e=new yn;if(arguments.length>0){Vr(Set,e,arguments[0])}delete e.constructor;Object.setPrototypeOf(e,Set.prototype);return e};S.Set.prototype=yn.prototype;h(S.Set.prototype,"constructor",S.Set,true);O.preserveToString(S.Set,yn)}var hn=!a(function(){return(new Map).keys().next().done});if(typeof S.Map.prototype.clear!=="function"||(new S.Set).size!==0||(new S.Map).size!==0||typeof S.Map.prototype.keys!=="function"||typeof S.Set.prototype.keys!=="function"||typeof S.Map.prototype.forEach!=="function"||typeof S.Set.prototype.forEach!=="function"||u(S.Map)||u(S.Set)||typeof(new S.Map).keys().next!=="function"||hn||!un){b(S,{Map:Br.Map,Set:Br.Set},true)}if(S.Set.prototype.keys!==S.Set.prototype.values){h(S.Set.prototype,"keys",S.Set.prototype.values,true)}me(Object.getPrototypeOf((new S.Map).keys()));me(Object.getPrototypeOf((new S.Set).keys()));if(c&&S.Set.prototype.has.name!=="has"){var bn=S.Set.prototype.has;X(S.Set.prototype,"has",function has(e){return t(bn,this,e)})}}b(S,Br);Oe(S.Map);Oe(S.Set)}var gn=function throwUnlessTargetIsObject(e){if(!te.TypeIsObject(e)){throw new TypeError("target must be an object")}};var dn={apply:function apply(){return te.Call(te.Call,null,arguments)},construct:function construct(e,t){if(!te.IsConstructor(e)){throw new TypeError("First argument must be a constructor.")}var r=arguments.length>2?arguments[2]:e;if(!te.IsConstructor(r)){throw new TypeError("new.target must be a constructor.")}return te.Construct(e,t,r,"internal")},deleteProperty:function deleteProperty(e,t){gn(e);if(s){var r=Object.getOwnPropertyDescriptor(e,t);if(r&&!r.configurable){return false}}return delete e[t]},has:function has(e,t){gn(e);return t in e}};if(Object.getOwnPropertyNames){Object.assign(dn,{ownKeys:function ownKeys(e){gn(e);var t=Object.getOwnPropertyNames(e);if(te.IsCallable(Object.getOwnPropertySymbols)){N(t,Object.getOwnPropertySymbols(e))}return t}})}var On=function ConvertExceptionToBoolean(e){return!i(e)};if(Object.preventExtensions){Object.assign(dn,{isExtensible:function isExtensible(e){gn(e);return Object.isExtensible(e)},preventExtensions:function preventExtensions(e){gn(e);return On(function(){Object.preventExtensions(e)})}})}if(s){var mn=function get(e,t,r){var n=Object.getOwnPropertyDescriptor(e,t);if(!n){var o=Object.getPrototypeOf(e);if(o===null){return void 0}return mn(o,t,r)}if("value"in n){return n.value}if(n.get){return te.Call(n.get,r)}return void 0};var wn=function set(e,r,n,o){var i=Object.getOwnPropertyDescriptor(e,r);if(!i){var a=Object.getPrototypeOf(e);if(a!==null){return wn(a,r,n,o)}i={value:void 0,writable:true,enumerable:true,configurable:true}}if("value"in i){if(!i.writable){return false}if(!te.TypeIsObject(o)){return false}var u=Object.getOwnPropertyDescriptor(o,r);if(u){return Q.defineProperty(o,r,{value:n})}else{return Q.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(dn,{defineProperty:function defineProperty(e,t,r){gn(e);return On(function(){Object.defineProperty(e,t,r)})},getOwnPropertyDescriptor:function getOwnPropertyDescriptor(e,t){gn(e);return Object.getOwnPropertyDescriptor(e,t)},get:function get(e,t){gn(e);var r=arguments.length>2?arguments[2]:e;return mn(e,t,r)},set:function set(e,t,r){gn(e);var n=arguments.length>3?arguments[3]:e;return wn(e,t,r,n)}})}if(Object.getPrototypeOf){var jn=Object.getPrototypeOf;dn.getPrototypeOf=function getPrototypeOf(e){gn(e);return jn(e)}}if(Object.setPrototypeOf&&dn.getPrototypeOf){var Sn=function(e,t){var r=t;while(r){if(e===r){return true}r=dn.getPrototypeOf(r)}return false};Object.assign(dn,{setPrototypeOf:function setPrototypeOf(e,t){gn(e);if(t!==null&&!te.TypeIsObject(t)){throw new TypeError("proto must be an object or null")}if(t===Q.getPrototypeOf(e)){return true}if(Q.isExtensible&&!Q.isExtensible(e)){return false}if(Sn(e,t)){return false}Object.setPrototypeOf(e,t);return true}})}var Tn=function(e,t){if(!te.IsCallable(S.Reflect[e])){h(S.Reflect,e,t)}else{var r=a(function(){S.Reflect[e](1);S.Reflect[e](NaN);S.Reflect[e](true);return true});if(r){X(S.Reflect,e,t)}}};Object.keys(dn).forEach(function(e){Tn(e,dn[e])});var In=S.Reflect.getPrototypeOf;if(c&&In&&In.name!=="getPrototypeOf"){X(S.Reflect,"getPrototypeOf",function getPrototypeOf(e){return t(In,S.Reflect,e)})}if(S.Reflect.setPrototypeOf){if(a(function(){S.Reflect.setPrototypeOf(1,{});return true})){X(S.Reflect,"setPrototypeOf",dn.setPrototypeOf)}}if(S.Reflect.defineProperty){if(!a(function(){var e=!S.Reflect.defineProperty(1,"test",{value:1});var t=typeof Object.preventExtensions!=="function"||!S.Reflect.defineProperty(Object.preventExtensions({}),"test",{});return e&&t})){X(S.Reflect,"defineProperty",dn.defineProperty)}}if(S.Reflect.construct){if(!a(function(){var e=function F(){};return S.Reflect.construct(function(){},[],e)instanceof e})){X(S.Reflect,"construct",dn.construct)}}if(String(new Date(NaN))!=="Invalid Date"){var En=Date.prototype.toString;var Pn=function toString(){var e=+this;if(e!==e){return"Invalid Date"}return te.Call(En,this)};X(Date.prototype,"toString",Pn)}var Mn={anchor:function anchor(e){return te.CreateHTML(this,"a","name",e)},big:function big(){return te.CreateHTML(this,"big","","")},blink:function blink(){return te.CreateHTML(this,"blink","","")},bold:function bold(){return te.CreateHTML(this,"b","","")},fixed:function fixed(){return te.CreateHTML(this,"tt","","")},fontcolor:function fontcolor(e){return te.CreateHTML(this,"font","color",e)},fontsize:function fontsize(e){return te.CreateHTML(this,"font","size",e)},italics:function italics(){return te.CreateHTML(this,"i","","")},link:function link(e){return te.CreateHTML(this,"a","href",e)},small:function small(){return te.CreateHTML(this,"small","","")},strike:function strike(){return te.CreateHTML(this,"strike","","")},sub:function sub(){return te.CreateHTML(this,"sub","","")},sup:function sub(){return te.CreateHTML(this,"sup","","")}};l(Object.keys(Mn),function(e){var r=String.prototype[e];var n=false;if(te.IsCallable(r)){var o=t(r,"",' " ');var i=P([],o.match(/"/g)).length;n=o!==o.toLowerCase()||i>2}else{n=true}if(n){X(String.prototype,e,Mn[e])}});var Cn=function(){if(!Z){return false}var e=typeof JSON==="object"&&typeof JSON.stringify==="function"?JSON.stringify:null;if(!e){return false}if(typeof e(W())!=="undefined"){return true}if(e([W()])!=="[null]"){return true}var t={a:W()};t[W()]=true;if(e(t)!=="{}"){return true}return false}();var xn=a(function(){if(!Z){return true}return JSON.stringify(Object(W()))==="{}"&&JSON.stringify([Object(W())])==="[{}]"});if(Cn||!xn){var Nn=JSON.stringify;X(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=te.IsCallable(n)?n:null;var a=function(e,r){var n=i?t(i,this,e,r):r;if(typeof n!=="symbol"){if(K.symbol(n)){return Tt({})(n)}else{return n}}};o.push(a)}else{o.push(n)}if(arguments.length>2){o.push(arguments[2])}return Nn.apply(this,o)})}return S}); //# sourceMappingURL=es6-shim.map diff --git a/testapp/ng2/lib/rxjs/bundles/Rx.js b/testapp/ng2/lib/rxjs/bundles/Rx.js index befc0c746..09d4bcb8c 100644 --- a/testapp/ng2/lib/rxjs/bundles/Rx.js +++ b/testapp/ng2/lib/rxjs/bundles/Rx.js @@ -1,152 +1,384 @@ +/** + @license + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2015-2016 Netflix, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + **/ "format register"; -System.register("rxjs/util/noop", [], true, function(require, exports, module) { +System.register("rxjs/util/root", [], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; - function noop() {} - exports.noop = noop; + "use strict"; + 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/util/throwError", [], true, function(require, exports, module) { +System.register("rxjs/util/SymbolShim", ["rxjs/util/root"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; - function throwError(e) { - throw e; + "use strict"; + var root_1 = require("rxjs/util/root"); + function polyfillSymbol(root) { + var Symbol = ensureSymbol(root); + ensureIterator(Symbol, root); + ensureObservable(Symbol); + ensureFor(Symbol); + return Symbol; } - exports.throwError = throwError; + 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/tryOrOnError", [], true, function(require, exports, module) { +System.register("rxjs/util/isFunction", [], 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; + "use strict"; + function isFunction(x) { + return typeof x === 'function'; } - exports.tryOrOnError = tryOrOnError; + exports.isFunction = isFunction; global.define = __define; return module.exports; }); -System.register("rxjs/Subscription", ["rxjs/util/noop"], true, function(require, exports, module) { +System.register("rxjs/util/isArray", [], 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; + "use strict"; + exports.isArray = Array.isArray || (function(x) { + return x && typeof x.length === 'number'; + }); global.define = __define; return module.exports; }); -System.register("rxjs/util/root", [], true, function(require, exports, module) { +System.register("rxjs/util/isObject", [], 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; + "use strict"; + function isObject(x) { + return x != null && typeof x === 'object'; } + exports.isObject = isObject; + 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; + "use strict"; + exports.errorObject = {e: {}}; + 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; + "use strict"; + var SymbolShim_1 = require("rxjs/util/SymbolShim"); + exports.rxSubscriber = SymbolShim_1.SymbolShim.for('rxSubscriber'); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/Observer", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + exports.empty = { + isUnsubscribed: true, + next: function(value) {}, + error: function(err) { + throw err; + }, + complete: function() {} + }; global.define = __define; return module.exports; }); -System.register("rxjs/subject/SubjectSubscription", ["rxjs/Subscription", "rxjs/Subscriber"], true, function(require, exports, module) { +System.register("rxjs/subject/SubjectSubscription", ["rxjs/Subscription"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -157,7 +389,6 @@ System.register("rxjs/subject/SubjectSubscription", ["rxjs/Subscription", "rxjs/ 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) { @@ -173,38 +404,40 @@ System.register("rxjs/subject/SubjectSubscription", ["rxjs/Subscription", "rxjs/ this.isUnsubscribed = true; var subject = this.subject; var observers = subject.observers; - this.subject = void 0; + this.subject = null; 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); + }(Subscription_1.Subscription)); exports.SubjectSubscription = SubjectSubscription; global.define = __define; return module.exports; }); -System.register("rxjs/util/errorObject", [], true, function(require, exports, module) { +System.register("rxjs/util/throwError", [], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; - exports.errorObject = {e: {}}; + "use strict"; + function throwError(e) { + throw e; + } + exports.throwError = throwError; global.define = __define; return module.exports; }); -System.register("rxjs/observable/throw", ["rxjs/Observable"], true, function(require, exports, module) { +System.register("rxjs/util/ObjectUnsubscribedError", [], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -214,45 +447,24 @@ System.register("rxjs/observable/throw", ["rxjs/Observable"], true, function(req } 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; + var ObjectUnsubscribedError = (function(_super) { + __extends(ObjectUnsubscribedError, _super); + function ObjectUnsubscribedError() { + _super.call(this, 'object unsubscribed'); + this.name = 'ObjectUnsubscribedError'; } - 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; + return ObjectUnsubscribedError; + }(Error)); + exports.ObjectUnsubscribedError = ObjectUnsubscribedError; global.define = __define; return module.exports; }); -System.register("rxjs/observable/empty", ["rxjs/Observable"], true, function(require, exports, module) { +System.register("rxjs/observable/ScalarObservable", ["rxjs/Observable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -263,29 +475,93 @@ System.register("rxjs/observable/empty", ["rxjs/Observable"], true, function(req 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) { + var ScalarObservable = (function(_super) { + __extends(ScalarObservable, _super); + function ScalarObservable(value, scheduler) { _super.call(this); + this.value = value; this.scheduler = scheduler; + this._isScalar = true; } - EmptyObservable.create = function(scheduler) { - return new EmptyObservable(scheduler); - }; - EmptyObservable.dispatch = function(_a) { - var subscriber = _a.subscriber; - subscriber.complete(); + ScalarObservable.create = function(value, scheduler) { + return new ScalarObservable(value, scheduler); }; - EmptyObservable.prototype._subscribe = function(subscriber) { + 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) { + return 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; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/EmptyObservable", ["rxjs/Observable"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + 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})); + return scheduler.schedule(EmptyObservable.dispatch, 0, {subscriber: subscriber}); } else { subscriber.complete(); } }; return EmptyObservable; - })(Observable_1.Observable); + }(Observable_1.Observable)); exports.EmptyObservable = EmptyObservable; global.define = __define; return module.exports; @@ -295,6 +571,7 @@ System.register("rxjs/util/isScheduler", [], true, function(require, exports, mo var global = System.global, __define = global.define; global.define = undefined; + "use strict"; function isScheduler(value) { return value && typeof value.schedule === 'function'; } @@ -307,6 +584,7 @@ System.register("rxjs/OuterSubscriber", ["rxjs/Subscriber"], true, function(requ var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -322,26 +600,40 @@ System.register("rxjs/OuterSubscriber", ["rxjs/Subscriber"], true, function(requ function OuterSubscriber() { _super.apply(this, arguments); } - OuterSubscriber.prototype.notifyComplete = function(inner) { - this.destination.complete(); - }; - OuterSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex) { + OuterSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { this.destination.next(innerValue); }; - OuterSubscriber.prototype.notifyError = function(error, inner) { + OuterSubscriber.prototype.notifyError = function(error, innerSub) { this.destination.error(error); }; + OuterSubscriber.prototype.notifyComplete = function(innerSub) { + this.destination.complete(); + }; return OuterSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); exports.OuterSubscriber = OuterSubscriber; 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; + "use strict"; + 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/InnerSubscriber", ["rxjs/Subscriber"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -362,152 +654,28 @@ System.register("rxjs/InnerSubscriber", ["rxjs/Subscriber"], true, function(requ this.index = 0; } InnerSubscriber.prototype._next = function(value) { - var index = this.index++; - this.parent.notifyNext(this.outerValue, value, this.outerIndex, index); + this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this); }; InnerSubscriber.prototype._error = function(error) { this.parent.notifyError(error, this); + this.unsubscribe(); }; InnerSubscriber.prototype._complete = function() { this.parent.notifyComplete(this); + this.unsubscribe(); }; return InnerSubscriber; - })(Subscriber_1.Subscriber); + }(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) { +System.register("rxjs/operator/mergeAll", ["rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -519,6 +687,13 @@ System.register("rxjs/operator/mergeAll-support", ["rxjs/OuterSubscriber", "rxjs }; var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); + function mergeAll(concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + return this.lift(new MergeAllOperator(concurrent)); + } + exports.mergeAll = mergeAll; var MergeAllOperator = (function() { function MergeAllOperator(concurrent) { this.concurrent = concurrent; @@ -527,7 +702,7 @@ System.register("rxjs/operator/mergeAll-support", ["rxjs/OuterSubscriber", "rxjs return new MergeAllSubscriber(observer, this.concurrent); }; return MergeAllOperator; - })(); + }()); exports.MergeAllOperator = MergeAllOperator; var MergeAllSubscriber = (function(_super) { __extends(MergeAllSubscriber, _super); @@ -540,12 +715,8 @@ System.register("rxjs/operator/mergeAll-support", ["rxjs/OuterSubscriber", "rxjs } 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)); - } + this.active++; + this.add(subscribeToResult_1.subscribeToResult(this, observable)); } else { this.buffer.push(observable); } @@ -567,27 +738,36 @@ System.register("rxjs/operator/mergeAll-support", ["rxjs/OuterSubscriber", "rxjs } }; return MergeAllSubscriber; - })(OuterSubscriber_1.OuterSubscriber); + }(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) { +System.register("rxjs/operator/merge", ["rxjs/observable/ArrayObservable", "rxjs/operator/mergeAll", "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"); + "use strict"; + var ArrayObservable_1 = require("rxjs/observable/ArrayObservable"); + var mergeAll_1 = require("rxjs/operator/mergeAll"); var isScheduler_1 = require("rxjs/util/isScheduler"); function merge() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; + } + observables.unshift(this); + return mergeStatic.apply(this, observables); + } + exports.merge = merge; + function mergeStatic() { 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 scheduler = null; var last = observables[observables.length - 1]; if (isScheduler_1.isScheduler(last)) { scheduler = observables.pop(); @@ -600,17 +780,18 @@ System.register("rxjs/operator/merge-static", ["rxjs/observable/fromArray", "rxj if (observables.length === 1) { return observables[0]; } - return new fromArray_1.ArrayObservable(observables, scheduler).lift(new mergeAll_support_1.MergeAllOperator(concurrent)); + return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new mergeAll_1.MergeAllOperator(concurrent)); } - exports.merge = merge; + exports.mergeStatic = mergeStatic; global.define = __define; return module.exports; }); -System.register("rxjs/subject/AsyncSubject", ["rxjs/Subject"], true, function(require, exports, module) { +System.register("rxjs/operator/race", ["rxjs/util/isArray", "rxjs/observable/ArrayObservable", "rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -620,35 +801,133 @@ System.register("rxjs/subject/AsyncSubject", ["rxjs/Subject"], true, function(re } 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; + var isArray_1 = require("rxjs/util/isArray"); + var ArrayObservable_1 = require("rxjs/observable/ArrayObservable"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); + function race() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; } - AsyncSubject.prototype._subscribe = function(subscriber) { - if (this.completeSignal && this._hasNext) { - subscriber.next(this._value); + if (observables.length === 1 && isArray_1.isArray(observables[0])) { + observables = observables[0]; + } + observables.unshift(this); + return raceStatic.apply(this, observables); + } + exports.race = race; + function raceStatic() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; + } + if (observables.length === 1) { + if (isArray_1.isArray(observables[0])) { + observables = observables[0]; + } else { + return observables[0]; } - return _super.prototype._subscribe.call(this, subscriber); + } + return new ArrayObservable_1.ArrayObservable(observables).lift(new RaceOperator()); + } + exports.raceStatic = raceStatic; + var RaceOperator = (function() { + function RaceOperator() {} + RaceOperator.prototype.call = function(subscriber) { + return new RaceSubscriber(subscriber); + }; + return RaceOperator; + }()); + exports.RaceOperator = RaceOperator; + var RaceSubscriber = (function(_super) { + __extends(RaceSubscriber, _super); + function RaceSubscriber(destination) { + _super.call(this, destination); + this.hasFirst = false; + this.observables = []; + this.subscriptions = []; + } + RaceSubscriber.prototype._next = function(observable) { + this.observables.push(observable); }; - AsyncSubject.prototype._next = function(value) { - this._value = value; - this._hasNext = true; + RaceSubscriber.prototype._complete = function() { + var observables = this.observables; + var len = observables.length; + if (len === 0) { + this.destination.complete(); + } else { + for (var i = 0; i < len; i++) { + var observable = observables[i]; + var subscription = subscribeToResult_1.subscribeToResult(this, observable, observable, i); + this.subscriptions.push(subscription); + this.add(subscription); + } + this.observables = null; + } }; - AsyncSubject.prototype._complete = function() { - var index = -1; + RaceSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { + if (!this.hasFirst) { + this.hasFirst = true; + for (var i = 0; i < this.subscriptions.length; i++) { + if (i !== outerIndex) { + var subscription = this.subscriptions[i]; + subscription.unsubscribe(); + this.remove(subscription); + } + } + this.subscriptions = null; + } + this.destination.next(innerValue); + }; + return RaceSubscriber; + }(OuterSubscriber_1.OuterSubscriber)); + exports.RaceSubscriber = RaceSubscriber; + 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; + "use strict"; + 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.apply(this, arguments); + this.value = null; + this.hasNext = false; + } + AsyncSubject.prototype._subscribe = function(subscriber) { + if (this.hasCompleted && 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) { + if (this.hasNext) { while (++index < len) { var o = observers[index]; - o.next(this._value); + o.next(this.value); o.complete(); } } else { @@ -657,18 +936,173 @@ System.register("rxjs/subject/AsyncSubject", ["rxjs/Subject"], true, function(re } } this.isUnsubscribed = false; + this.unsubscribe(); }; return AsyncSubject; - })(Subject_1.Subject); + }(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) { +System.register("rxjs/observable/BoundNodeCallbackObservable", ["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; + "use strict"; + 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 BoundNodeCallbackObservable = (function(_super) { + __extends(BoundNodeCallbackObservable, _super); + function BoundNodeCallbackObservable(callbackFunc, selector, args, scheduler) { + _super.call(this); + this.callbackFunc = callbackFunc; + this.selector = selector; + this.args = args; + this.scheduler = scheduler; + } + BoundNodeCallbackObservable.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 BoundNodeCallbackObservable(callbackFunc, selector, args, scheduler); + }; + }; + BoundNodeCallbackObservable.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; + var err = innerArgs.shift(); + if (err) { + subject.error(err); + } else 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 { + return scheduler.schedule(dispatch, 0, { + source: this, + subscriber: subscriber + }); + } + }; + return BoundNodeCallbackObservable; + }(Observable_1.Observable)); + exports.BoundNodeCallbackObservable = BoundNodeCallbackObservable; + function dispatch(state) { + var self = this; + 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; + var err = innerArgs.shift(); + if (err) { + subject.error(err); + } else if (selector) { + var result_2 = tryCatch_1.tryCatch(selector).apply(this, innerArgs); + if (result_2 === errorObject_1.errorObject) { + self.add(scheduler.schedule(dispatchError, 0, { + err: errorObject_1.errorObject.e, + subject: subject + })); + } else { + self.add(scheduler.schedule(dispatchNext, 0, { + value: result_2, + subject: subject + })); + } + } else { + var value = innerArgs.length === 1 ? innerArgs[0] : innerArgs; + self.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); + } + } + self.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/observable/DeferObservable", ["rxjs/Observable", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -699,27 +1133,29 @@ System.register("rxjs/observable/defer", ["rxjs/Observable", "rxjs/util/tryCatch } }; return DeferObservable; - })(Observable_1.Observable); + }(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) { +System.register("rxjs/add/observable/empty", ["rxjs/Observable", "rxjs/observable/EmptyObservable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var empty_1 = require("rxjs/observable/empty"); - Observable_1.Observable.empty = empty_1.EmptyObservable.create; + var EmptyObservable_1 = require("rxjs/observable/EmptyObservable"); + Observable_1.Observable.empty = EmptyObservable_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) { +System.register("rxjs/observable/PromiseObservable", ["rxjs/util/root", "rxjs/Observable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -729,112 +1165,112 @@ System.register("rxjs/observable/fromPromise", ["rxjs/Observable", "rxjs/Subscri } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; + var root_1 = require("rxjs/util/root"); 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; + scheduler = null; } _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; + scheduler = null; } 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) { + var scheduler = this.scheduler; + if (scheduler == null) { if (this._isScalar) { - subscriber.next(this.value); - subscriber.complete(); + if (!subscriber.isUnsubscribed) { + subscriber.next(this.value); + subscriber.complete(); + } } else { promise.then(function(value) { - _this._isScalar = true; _this.value = value; - subscriber.next(value); - subscriber.complete(); + _this._isScalar = true; + if (!subscriber.isUnsubscribed) { + subscriber.next(value); + subscriber.complete(); + } }, function(err) { - return subscriber.error(err); + if (!subscriber.isUnsubscribed) { + subscriber.error(err); + } }).then(null, function(err) { - setTimeout(function() { + root_1.root.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 - })); + if (!subscriber.isUnsubscribed) { + return scheduler.schedule(dispatchNext, 0, { + value: this.value, + subscriber: subscriber + }); + } } else { promise.then(function(value) { - _this._isScalar = true; _this.value = value; - subscription.add(scheduler.schedule(dispatchNext, 0, { - value: value, - subscriber: subscriber - })); + _this._isScalar = true; + if (!subscriber.isUnsubscribed) { + subscriber.add(scheduler.schedule(dispatchNext, 0, { + value: value, + subscriber: subscriber + })); + } }, function(err) { - return subscription.add(scheduler.schedule(dispatchError, 0, { - err: err, - subscriber: subscriber - })); + if (!subscriber.isUnsubscribed) { + subscriber.add(scheduler.schedule(dispatchError, 0, { + err: err, + subscriber: subscriber + })); + } }).then(null, function(err) { - scheduler.schedule(function() { + root_1.root.setTimeout(function() { throw err; }); }); } - return subscription; } }; return PromiseObservable; - })(Observable_1.Observable); + }(Observable_1.Observable)); exports.PromiseObservable = PromiseObservable; function dispatchNext(_a) { var value = _a.value, subscriber = _a.subscriber; - subscriber.next(value); - subscriber.complete(); + if (!subscriber.isUnsubscribed) { + 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'; + if (!subscriber.isUnsubscribed) { + subscriber.error(err); + } } - 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) { +System.register("rxjs/observable/IteratorObservable", ["rxjs/util/root", "rxjs/util/isObject", "rxjs/util/tryCatch", "rxjs/Observable", "rxjs/util/isFunction", "rxjs/util/SymbolShim", "rxjs/util/errorObject"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -844,22 +1280,28 @@ System.register("rxjs/observable/IteratorObservable", ["rxjs/Observable", "rxjs/ } 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 isObject_1 = require("rxjs/util/isObject"); var tryCatch_1 = require("rxjs/util/tryCatch"); + var Observable_1 = require("rxjs/Observable"); + var isFunction_1 = require("rxjs/util/isFunction"); + var SymbolShim_1 = require("rxjs/util/SymbolShim"); 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') { + if (isObject_1.isObject(project)) { + this.thisArg = project; + this.scheduler = thisArg; + } else if (isFunction_1.isFunction(project)) { + this.project = project; + this.thisArg = thisArg; + this.scheduler = scheduler; + } else if (project != null) { throw new Error('When provided, `project` must be a function.'); } this.iterator = getIterator(iterator); @@ -909,13 +1351,13 @@ System.register("rxjs/observable/IteratorObservable", ["rxjs/Observable", "rxjs/ thisArg = _a.thisArg, scheduler = _a.scheduler; if (scheduler) { - subscriber.add(scheduler.schedule(IteratorObservable.dispatch, 0, { + return scheduler.schedule(IteratorObservable.dispatch, 0, { index: index, thisArg: thisArg, project: project, iterator: iterator, subscriber: subscriber - })); + }); } else { do { var result = iterator.next(); @@ -939,7 +1381,7 @@ System.register("rxjs/observable/IteratorObservable", ["rxjs/Observable", "rxjs/ } }; return IteratorObservable; - })(Observable_1.Observable); + }(Observable_1.Observable)); exports.IteratorObservable = IteratorObservable; var StringIterator = (function() { function StringIterator(str, idx, len) { @@ -966,7 +1408,7 @@ System.register("rxjs/observable/IteratorObservable", ["rxjs/Observable", "rxjs/ }; }; return StringIterator; - })(); + }()); var ArrayIterator = (function() { function ArrayIterator(arr, idx, len) { if (idx === void 0) { @@ -992,7 +1434,7 @@ System.register("rxjs/observable/IteratorObservable", ["rxjs/Observable", "rxjs/ }; }; return ArrayIterator; - })(); + }()); function getIterator(obj) { var i = obj[SymbolShim_1.SymbolShim.iterator]; if (!i && typeof obj === 'string') { @@ -1041,37 +1483,127 @@ System.register("rxjs/observable/IteratorObservable", ["rxjs/Observable", "rxjs/ return module.exports; }); -System.register("rxjs/Notification", ["rxjs/Observable"], true, function(require, exports, module) { +System.register("rxjs/observable/ArrayLikeObservable", ["rxjs/Observable", "rxjs/observable/ScalarObservable", "rxjs/observable/EmptyObservable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; + 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 Notification = (function() { - function Notification(kind, value, exception) { - this.kind = kind; - this.value = value; - this.exception = exception; - this.hasValue = kind === 'N'; + var ScalarObservable_1 = require("rxjs/observable/ScalarObservable"); + var EmptyObservable_1 = require("rxjs/observable/EmptyObservable"); + var ArrayLikeObservable = (function(_super) { + __extends(ArrayLikeObservable, _super); + function ArrayLikeObservable(arrayLike, mapFn, thisArg, scheduler) { + _super.call(this); + this.arrayLike = arrayLike; + this.scheduler = scheduler; + if (!mapFn && !scheduler && arrayLike.length === 1) { + this._isScalar = true; + this.value = arrayLike[0]; + } + if (mapFn) { + this.mapFn = mapFn.bind(thisArg); + } } - 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(); + ArrayLikeObservable.create = function(arrayLike, mapFn, thisArg, scheduler) { + var length = arrayLike.length; + if (length === 0) { + return new EmptyObservable_1.EmptyObservable(); + } else if (length === 1 && !mapFn) { + return new ScalarObservable_1.ScalarObservable(arrayLike[0], scheduler); + } else { + return new ArrayLikeObservable(arrayLike, mapFn, thisArg, scheduler); } }; - 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(); + ArrayLikeObservable.dispatch = function(state) { + var arrayLike = state.arrayLike, + index = state.index, + length = state.length, + mapFn = state.mapFn, + subscriber = state.subscriber; + if (subscriber.isUnsubscribed) { + return ; + } + if (index >= length) { + subscriber.complete(); + return ; + } + var result = mapFn ? mapFn(arrayLike[index], index) : arrayLike[index]; + subscriber.next(result); + state.index = index + 1; + this.schedule(state); + }; + ArrayLikeObservable.prototype._subscribe = function(subscriber) { + var index = 0; + var _a = this, + arrayLike = _a.arrayLike, + mapFn = _a.mapFn, + scheduler = _a.scheduler; + var length = arrayLike.length; + if (scheduler) { + return scheduler.schedule(ArrayLikeObservable.dispatch, 0, { + arrayLike: arrayLike, + index: index, + length: length, + mapFn: mapFn, + subscriber: subscriber + }); + } else { + for (var i = 0; i < length && !subscriber.isUnsubscribed; i++) { + var result = mapFn ? mapFn(arrayLike[i], i) : arrayLike[i]; + subscriber.next(result); + } + subscriber.complete(); + } + }; + return ArrayLikeObservable; + }(Observable_1.Observable)); + exports.ArrayLikeObservable = ArrayLikeObservable; + 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; + "use strict"; + 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 && observer.next(this.value); + case 'E': + return observer.error && observer.error(this.exception); + case 'C': + return observer.complete && observer.complete(); + } + }; + Notification.prototype.do = function(next, error, complete) { + var kind = this.kind; + switch (kind) { + case 'N': + return next && next(this.value); + case 'E': + return error && error(this.exception); + case 'C': + return complete && complete(); } }; Notification.prototype.accept = function(nextOrObserver, error, complete) { @@ -1107,28 +1639,30 @@ System.register("rxjs/Notification", ["rxjs/Observable"], true, function(require 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) { +System.register("rxjs/add/observable/fromArray", ["rxjs/Observable", "rxjs/observable/ArrayObservable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; 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; + var ArrayObservable_1 = require("rxjs/observable/ArrayObservable"); + Observable_1.Observable.fromArray = ArrayObservable_1.ArrayObservable.create; + Observable_1.Observable.of = ArrayObservable_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) { +System.register("rxjs/observable/FromEventObservable", ["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; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -1142,6 +1676,21 @@ System.register("rxjs/observable/fromEvent", ["rxjs/Observable", "rxjs/util/tryC var tryCatch_1 = require("rxjs/util/tryCatch"); var errorObject_1 = require("rxjs/util/errorObject"); var Subscription_1 = require("rxjs/Subscription"); + function isNodeStyleEventEmmitter(sourceObj) { + return !!sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function'; + } + function isJQueryStyleEventEmitter(sourceObj) { + return !!sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function'; + } + function isNodeList(sourceObj) { + return !!sourceObj && sourceObj.toString() === '[object NodeList]'; + } + function isHTMLCollection(sourceObj) { + return !!sourceObj && sourceObj.toString() === '[object HTMLCollection]'; + } + function isEventTarget(sourceObj) { + return !!sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function'; + } var FromEventObservable = (function(_super) { __extends(FromEventObservable, _super); function FromEventObservable(sourceObj, eventName, selector) { @@ -1155,23 +1704,22 @@ System.register("rxjs/observable/fromEvent", ["rxjs/Observable", "rxjs/util/tryC }; FromEventObservable.setupSubscription = function(sourceObj, eventName, handler, subscriber) { var unsubscribe; - var tag = sourceObj.toString(); - if (tag === '[object NodeList]' || tag === '[object HTMLCollection]') { + if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) { 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') { + } else if (isEventTarget(sourceObj)) { sourceObj.addEventListener(eventName, handler); unsubscribe = function() { return sourceObj.removeEventListener(eventName, handler); }; - } else if (typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function') { + } else if (isJQueryStyleEventEmitter(sourceObj)) { sourceObj.on(eventName, handler); unsubscribe = function() { return sourceObj.off(eventName, handler); }; - } else if (typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function') { + } else if (isNodeStyleEventEmmitter(sourceObj)) { sourceObj.addListener(eventName, handler); unsubscribe = function() { return sourceObj.removeListener(eventName, handler); @@ -1183,10 +1731,14 @@ System.register("rxjs/observable/fromEvent", ["rxjs/Observable", "rxjs/util/tryC var sourceObj = this.sourceObj; var eventName = this.eventName; var selector = this.selector; - var handler = selector ? function(e) { - var result = tryCatch_1.tryCatch(selector)(e); + var handler = selector ? function() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + var result = tryCatch_1.tryCatch(selector).apply(void 0, args); if (result === errorObject_1.errorObject) { - subscriber.error(result.e); + subscriber.error(errorObject_1.errorObject.e); } else { subscriber.next(result); } @@ -1196,16 +1748,17 @@ System.register("rxjs/observable/fromEvent", ["rxjs/Observable", "rxjs/util/tryC FromEventObservable.setupSubscription(sourceObj, eventName, handler, subscriber); }; return FromEventObservable; - })(Observable_1.Observable); + }(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) { +System.register("rxjs/observable/FromEventPatternObservable", ["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; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -1253,30 +1806,32 @@ System.register("rxjs/observable/fromEventPattern", ["rxjs/Observable", "rxjs/Su })); }; return FromEventPatternObservable; - })(Observable_1.Observable); + }(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) { +System.register("rxjs/add/observable/fromPromise", ["rxjs/Observable", "rxjs/observable/PromiseObservable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var fromPromise_1 = require("rxjs/observable/fromPromise"); - Observable_1.Observable.fromPromise = fromPromise_1.PromiseObservable.create; + var PromiseObservable_1 = require("rxjs/observable/PromiseObservable"); + Observable_1.Observable.fromPromise = PromiseObservable_1.PromiseObservable.create; global.define = __define; return module.exports; }); -System.register("rxjs/util/isNumeric", [], true, function(require, exports, module) { +System.register("rxjs/util/isNumeric", ["rxjs/util/isArray"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; - var is_array = Array.isArray; + "use strict"; + var isArray_1 = require("rxjs/util/isArray"); function isNumeric(val) { - return !is_array(val) && (val - parseFloat(val) + 1) >= 0; + return !isArray_1.isArray(val) && (val - parseFloat(val) + 1) >= 0; } exports.isNumeric = isNumeric; ; @@ -1288,13 +1843,14 @@ System.register("rxjs/util/Immediate", ["rxjs/util/root"], true, function(requir var global = System.global, __define = global.define; global.define = undefined; + "use strict"; 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; + if (root.setImmediate && typeof root.setImmediate === 'function') { + this.setImmediate = root.setImmediate.bind(root); + this.clearImmediate = root.clearImmediate.bind(root); } else { this.nextHandle = 1; this.tasksByHandle = {}; @@ -1333,14 +1889,14 @@ System.register("rxjs/util/Immediate", ["rxjs/util/root"], true, function(requir ImmediateDefinition.prototype.canUsePostMessage = function() { var root = this.root; if (root.postMessage && !root.importScripts) { - var postMessageIsAsynchronous = true; + var postMessageIsAsynchronous_1 = true; var oldOnMessage = root.onmessage; root.onmessage = function() { - postMessageIsAsynchronous = false; + postMessageIsAsynchronous_1 = false; }; root.postMessage('', '*'); root.onmessage = oldOnMessage; - return postMessageIsAsynchronous; + return postMessageIsAsynchronous_1; } return false; }; @@ -1466,17 +2022,18 @@ System.register("rxjs/util/Immediate", ["rxjs/util/root"], true, function(requir 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) { +System.register("rxjs/scheduler/FutureAction", ["rxjs/util/root", "rxjs/Subscription"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -1486,30 +2043,131 @@ System.register("rxjs/observable/never", ["rxjs/Observable", "rxjs/util/noop"], } 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() { + var root_1 = require("rxjs/util/root"); + var Subscription_1 = require("rxjs/Subscription"); + var FutureAction = (function(_super) { + __extends(FutureAction, _super); + function FutureAction(scheduler, work) { _super.call(this); + this.scheduler = scheduler; + this.work = work; } - InfiniteObservable.create = function() { - return new InfiniteObservable(); + FutureAction.prototype.execute = function() { + if (this.isUnsubscribed) { + throw new Error('How did did we execute a canceled Action?'); + } + this.work(this.state); }; - InfiniteObservable.prototype._subscribe = function(subscriber) { - noop_1.noop(); + FutureAction.prototype.schedule = function(state, delay) { + if (delay === void 0) { + delay = 0; + } + if (this.isUnsubscribed) { + return this; + } + return this._schedule(state, delay); + }; + FutureAction.prototype._schedule = function(state, delay) { + var _this = this; + if (delay === void 0) { + delay = 0; + } + this.delay = delay; + this.state = state; + var id = this.id; + if (id != null) { + this.id = undefined; + root_1.root.clearTimeout(id); + } + this.id = root_1.root.setTimeout(function() { + _this.id = null; + var scheduler = _this.scheduler; + scheduler.actions.push(_this); + scheduler.flush(); + }, delay); + return this; + }; + FutureAction.prototype._unsubscribe = function() { + var _a = this, + id = _a.id, + scheduler = _a.scheduler; + var actions = scheduler.actions; + var index = actions.indexOf(this); + if (id != null) { + this.id = null; + root_1.root.clearTimeout(id); + } + if (index !== -1) { + actions.splice(index, 1); + } + this.work = null; + this.state = null; + this.scheduler = null; + }; + return FutureAction; + }(Subscription_1.Subscription)); + exports.FutureAction = FutureAction; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/scheduler/QueueAction", ["rxjs/scheduler/FutureAction"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + 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 FutureAction_1 = require("rxjs/scheduler/FutureAction"); + var QueueAction = (function(_super) { + __extends(QueueAction, _super); + function QueueAction() { + _super.apply(this, arguments); + } + QueueAction.prototype._schedule = function(state, delay) { + if (delay === void 0) { + delay = 0; + } + if (delay > 0) { + return _super.prototype._schedule.call(this, state, delay); + } + this.delay = delay; + this.state = state; + var scheduler = this.scheduler; + scheduler.actions.push(this); + scheduler.flush(); + return this; }; - return InfiniteObservable; - })(Observable_1.Observable); - exports.InfiniteObservable = InfiniteObservable; + return QueueAction; + }(FutureAction_1.FutureAction)); + exports.QueueAction = QueueAction; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/noop", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + function noop() {} + exports.noop = noop; global.define = __define; return module.exports; }); -System.register("rxjs/observable/range", ["rxjs/Observable"], true, function(require, exports, module) { +System.register("rxjs/observable/RangeObservable", ["rxjs/Observable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -1560,12 +2218,12 @@ System.register("rxjs/observable/range", ["rxjs/Observable"], true, function(req var end = this.end; var scheduler = this.scheduler; if (scheduler) { - subscriber.add(scheduler.schedule(RangeObservable.dispatch, 0, { + return scheduler.schedule(RangeObservable.dispatch, 0, { index: index, end: end, start: start, subscriber: subscriber - })); + }); } else { do { if (index++ >= end) { @@ -1580,19 +2238,57 @@ System.register("rxjs/observable/range", ["rxjs/Observable"], true, function(req } }; return RangeObservable; - })(Observable_1.Observable); + }(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) { +System.register("rxjs/observable/ErrorObservable", ["rxjs/Observable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; + 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 throw_1 = require("rxjs/observable/throw"); - Observable_1.Observable.throw = throw_1.ErrorObservable.create; + 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) { + return 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; }); @@ -1601,6 +2297,7 @@ System.register("rxjs/util/isDate", [], true, function(require, exports, module) var global = System.global, __define = global.define; global.define = undefined; + "use strict"; function isDate(value) { return value instanceof Date && !isNaN(+value); } @@ -1609,10 +2306,11 @@ System.register("rxjs/util/isDate", [], true, function(require, exports, module) 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) { +System.register("rxjs/operator/zip", ["rxjs/observable/ArrayObservable", "rxjs/util/isArray", "rxjs/Subscriber", "rxjs/OuterSubscriber", "rxjs/util/subscribeToResult", "rxjs/util/SymbolShim"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -1622,13 +2320,33 @@ System.register("rxjs/operator/zip-support", ["rxjs/Subscriber", "rxjs/util/tryC } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; + var ArrayObservable_1 = require("rxjs/observable/ArrayObservable"); + var isArray_1 = require("rxjs/util/isArray"); 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; + function zipProto() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; + } + observables.unshift(this); + return zipStatic.apply(this, observables); + } + exports.zipProto = zipProto; + function zipStatic() { + 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 ArrayObservable_1.ArrayObservable(observables).lift(new ZipOperator(project)); + } + exports.zipStatic = zipStatic; var ZipOperator = (function() { function ZipOperator(project) { this.project = project; @@ -1637,7 +2355,7 @@ System.register("rxjs/operator/zip-support", ["rxjs/Subscriber", "rxjs/util/tryC return new ZipSubscriber(subscriber, this.project); }; return ZipOperator; - })(); + }()); exports.ZipOperator = ZipOperator; var ZipSubscriber = (function(_super) { __extends(ZipSubscriber, _super); @@ -1655,7 +2373,7 @@ System.register("rxjs/operator/zip-support", ["rxjs/Subscriber", "rxjs/util/tryC ZipSubscriber.prototype._next = function(value) { var iterators = this.iterators; var index = this.index++; - if (isArray(value)) { + if (isArray_1.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]())); @@ -1670,7 +2388,7 @@ System.register("rxjs/operator/zip-support", ["rxjs/Subscriber", "rxjs/util/tryC for (var i = 0; i < len; i++) { var iterator = iterators[i]; if (iterator.stillUnsubscribed) { - iterator.subscribe(iterator, i); + this.add(iterator.subscribe(iterator, i)); } else { this.active--; } @@ -1706,14 +2424,8 @@ System.register("rxjs/operator/zip-support", ["rxjs/Subscriber", "rxjs/util/tryC } 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); - } + if (this.project) { + this._tryProject(args); } else { destination.next(args); } @@ -1721,8 +2433,18 @@ System.register("rxjs/operator/zip-support", ["rxjs/Subscriber", "rxjs/util/tryC destination.complete(); } }; + ZipSubscriber.prototype._tryProject = function(args) { + var result; + try { + result = this.project.apply(this, args); + } catch (err) { + this.destination.error(err); + return ; + } + this.destination.next(result); + }; return ZipSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); exports.ZipSubscriber = ZipSubscriber; var StaticIterator = (function() { function StaticIterator(iterator) { @@ -1742,7 +2464,7 @@ System.register("rxjs/operator/zip-support", ["rxjs/Subscriber", "rxjs/util/tryC return nextResult && nextResult.done; }; return StaticIterator; - })(); + }()); var StaticArrayIterator = (function() { function StaticArrayIterator(array) { this.array = array; @@ -1768,7 +2490,7 @@ System.register("rxjs/operator/zip-support", ["rxjs/Subscriber", "rxjs/util/tryC return this.array.length === this.index; }; return StaticArrayIterator; - })(); + }()); var ZipBufferIterator = (function(_super) { __extends(ZipBufferIterator, _super); function ZipBufferIterator(destination, parent, observable, index) { @@ -1808,23 +2530,24 @@ System.register("rxjs/operator/zip-support", ["rxjs/Subscriber", "rxjs/util/tryC this.destination.complete(); } }; - ZipBufferIterator.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex) { + ZipBufferIterator.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { this.buffer.push(innerValue); this.parent.checkIterators(); }; ZipBufferIterator.prototype.subscribe = function(value, index) { - this.add(subscribeToResult_1.subscribeToResult(this, this.observable, this, index)); + return subscribeToResult_1.subscribeToResult(this, this.observable, this, index); }; return ZipBufferIterator; - })(OuterSubscriber_1.OuterSubscriber); + }(OuterSubscriber_1.OuterSubscriber)); global.define = __define; return module.exports; }); -System.register("rxjs/operator/buffer", ["rxjs/Subscriber"], true, function(require, exports, module) { +System.register("rxjs/operator/buffer", ["rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -1834,7 +2557,8 @@ System.register("rxjs/operator/buffer", ["rxjs/Subscriber"], true, function(requ } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; - var Subscriber_1 = require("rxjs/Subscriber"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); function buffer(closingNotifier) { return this.lift(new BufferOperator(closingNotifier)); } @@ -1847,52 +2571,24 @@ System.register("rxjs/operator/buffer", ["rxjs/Subscriber"], true, function(requ 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)); + this.add(subscribeToResult_1.subscribeToResult(this, closingNotifier)); } 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() { + BufferSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { 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); + }(OuterSubscriber_1.OuterSubscriber)); global.define = __define; return module.exports; }); @@ -1901,6 +2597,7 @@ System.register("rxjs/operator/bufferCount", ["rxjs/Subscriber"], true, function var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -1927,7 +2624,7 @@ System.register("rxjs/operator/bufferCount", ["rxjs/Subscriber"], true, function return new BufferCountSubscriber(subscriber, this.bufferSize, this.startBufferEvery); }; return BufferCountOperator; - })(); + }()); var BufferCountSubscriber = (function(_super) { __extends(BufferCountSubscriber, _super); function BufferCountSubscriber(destination, bufferSize, startBufferEvery) { @@ -1960,9 +2657,6 @@ System.register("rxjs/operator/bufferCount", ["rxjs/Subscriber"], true, function 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; @@ -1972,10 +2666,10 @@ System.register("rxjs/operator/bufferCount", ["rxjs/Subscriber"], true, function destination.next(buffer); } } - destination.complete(); + _super.prototype._complete.call(this); }; return BufferCountSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); global.define = __define; return module.exports; }); @@ -1984,6 +2678,7 @@ System.register("rxjs/operator/bufferTime", ["rxjs/Subscriber", "rxjs/scheduler/ var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -2015,7 +2710,7 @@ System.register("rxjs/operator/bufferTime", ["rxjs/Subscriber", "rxjs/scheduler/ 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) { @@ -2056,14 +2751,19 @@ System.register("rxjs/operator/bufferTime", ["rxjs/Subscriber", "rxjs/scheduler/ }; BufferTimeSubscriber.prototype._error = function(err) { this.buffers.length = 0; - this.destination.error(err); + _super.prototype._error.call(this, err); }; BufferTimeSubscriber.prototype._complete = function() { - var buffers = this.buffers; + var _a = this, + buffers = _a.buffers, + destination = _a.destination; while (buffers.length > 0) { - this.destination.next(buffers.shift()); + destination.next(buffers.shift()); } - this.destination.complete(); + _super.prototype._complete.call(this); + }; + BufferTimeSubscriber.prototype._unsubscribe = function() { + this.buffers = null; }; BufferTimeSubscriber.prototype.openBuffer = function() { var buffer = []; @@ -2076,7 +2776,7 @@ System.register("rxjs/operator/bufferTime", ["rxjs/Subscriber", "rxjs/scheduler/ buffers.splice(buffers.indexOf(buffer), 1); }; return BufferTimeSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); function dispatchBufferTimeSpanOnly(state) { var subscriber = state.subscriber; var prevBuffer = state.buffer; @@ -2116,6 +2816,7 @@ System.register("rxjs/operator/bufferToggle", ["rxjs/Subscriber", "rxjs/Subscrip var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -2142,7 +2843,7 @@ System.register("rxjs/operator/bufferToggle", ["rxjs/Subscriber", "rxjs/Subscrip return new BufferToggleSubscriber(subscriber, this.openings, this.closingSelector); }; return BufferToggleOperator; - })(); + }()); var BufferToggleSubscriber = (function(_super) { __extends(BufferToggleSubscriber, _super); function BufferToggleSubscriber(destination, openings, closingSelector) { @@ -2150,7 +2851,7 @@ System.register("rxjs/operator/bufferToggle", ["rxjs/Subscriber", "rxjs/Subscrip this.openings = openings; this.closingSelector = closingSelector; this.contexts = []; - this.add(this.openings._subscribe(new BufferToggleOpeningsSubscriber(this))); + this.add(this.openings.subscribe(new BufferToggleOpeningsSubscriber(this))); } BufferToggleSubscriber.prototype._next = function(value) { var contexts = this.contexts; @@ -2168,7 +2869,7 @@ System.register("rxjs/operator/bufferToggle", ["rxjs/Subscriber", "rxjs/Subscrip context.subscription = null; } this.contexts = null; - this.destination.error(err); + _super.prototype._error.call(this, err); }; BufferToggleSubscriber.prototype._complete = function() { var contexts = this.contexts; @@ -2180,14 +2881,14 @@ System.register("rxjs/operator/bufferToggle", ["rxjs/Subscriber", "rxjs/Subscrip context.subscription = null; } this.contexts = null; - this.destination.complete(); + _super.prototype._complete.call(this); }; 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); + this._error(errorObject_1.errorObject.e); } else { var context = { buffer: [], @@ -2195,7 +2896,7 @@ System.register("rxjs/operator/bufferToggle", ["rxjs/Subscriber", "rxjs/Subscrip }; contexts.push(context); var subscriber = new BufferToggleClosingsSubscriber(this, context); - var subscription = closingNotifier._subscribe(subscriber); + var subscription = closingNotifier.subscribe(subscriber); context.subscription.add(subscription); this.add(subscription); } @@ -2213,7 +2914,7 @@ System.register("rxjs/operator/bufferToggle", ["rxjs/Subscriber", "rxjs/Subscrip subscription.unsubscribe(); }; return BufferToggleSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); var BufferToggleOpeningsSubscriber = (function(_super) { __extends(BufferToggleOpeningsSubscriber, _super); function BufferToggleOpeningsSubscriber(parent) { @@ -2228,7 +2929,7 @@ System.register("rxjs/operator/bufferToggle", ["rxjs/Subscriber", "rxjs/Subscrip }; BufferToggleOpeningsSubscriber.prototype._complete = function() {}; return BufferToggleOpeningsSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); var BufferToggleClosingsSubscriber = (function(_super) { __extends(BufferToggleClosingsSubscriber, _super); function BufferToggleClosingsSubscriber(parent, context) { @@ -2246,15 +2947,16 @@ System.register("rxjs/operator/bufferToggle", ["rxjs/Subscriber", "rxjs/Subscrip this.parent.closeBuffer(this.context); }; return BufferToggleClosingsSubscriber; - })(Subscriber_1.Subscriber); + }(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) { +System.register("rxjs/operator/bufferWhen", ["rxjs/Subscription", "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; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -2264,9 +2966,11 @@ System.register("rxjs/operator/bufferWhen", ["rxjs/Subscriber", "rxjs/util/tryCa } 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"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); function bufferWhen(closingSelector) { return this.lift(new BufferWhenOperator(closingSelector)); } @@ -2279,74 +2983,223 @@ System.register("rxjs/operator/bufferWhen", ["rxjs/Subscriber", "rxjs/util/tryCa 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.subscribing = false; 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); + if (buffer) { + this.destination.next(buffer); + } + _super.prototype._complete.call(this); + }; + BufferWhenSubscriber.prototype._unsubscribe = function() { this.buffer = null; - this.destination.complete(); + this.subscribing = false; + }; + BufferWhenSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.openBuffer(); + }; + BufferWhenSubscriber.prototype.notifyComplete = function() { + if (this.subscribing) { + this.complete(); + } else { + this.openBuffer(); + } }; BufferWhenSubscriber.prototype.openBuffer = function() { - var prevClosingNotification = this.closingNotification; - if (prevClosingNotification) { - this.remove(prevClosingNotification); - prevClosingNotification.unsubscribe(); + var closingSubscription = this.closingSubscription; + if (closingSubscription) { + this.remove(closingSubscription); + closingSubscription.unsubscribe(); } var buffer = this.buffer; - if (buffer) { + if (this.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); + this.error(errorObject_1.errorObject.e); } else { - this.add(this.closingNotification = closingNotifier._subscribe(new BufferClosingNotifierSubscriber(this))); + closingSubscription = new Subscription_1.Subscription(); + this.closingSubscription = closingSubscription; + this.add(closingSubscription); + this.subscribing = true; + closingSubscription.add(subscribeToResult_1.subscribeToResult(this, closingNotifier)); + this.subscribing = false; } }; return BufferWhenSubscriber; - })(Subscriber_1.Subscriber); - var BufferClosingNotifierSubscriber = (function(_super) { - __extends(BufferClosingNotifierSubscriber, _super); - function BufferClosingNotifierSubscriber(parent) { + }(OuterSubscriber_1.OuterSubscriber)); + 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; + "use strict"; + var QueueScheduler_1 = require("rxjs/scheduler/QueueScheduler"); + exports.queue = new QueueScheduler_1.QueueScheduler(); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/observable/ConnectableObservable", ["rxjs/Observable", "rxjs/Subscriber", "rxjs/Subscription"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + 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 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); + }; + ConnectableObservable.prototype._closeSubscription = function() { + this.subject = null; + this.subscription = null; + }; + 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._closeSubscription(); + this.connectable = null; + }; + 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.parent = parent; + this.destination = destination; + this.refCountObservable = refCountObservable; + this.connection = refCountObservable.connection; + destination.add(this); } - BufferClosingNotifierSubscriber.prototype._next = function() { - this.parent.openBuffer(); + RefCountSubscriber.prototype._next = function(value) { + this.destination.next(value); }; - BufferClosingNotifierSubscriber.prototype._error = function(err) { - this.parent.error(err); + 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 = null; + this.unsubscribe(); + } }; - BufferClosingNotifierSubscriber.prototype._complete = function() { - this.parent.openBuffer(); + 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 = null; + } + } }; - return BufferClosingNotifierSubscriber; - })(Subscriber_1.Subscriber); + return RefCountSubscriber; + }(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) { +System.register("rxjs/operator/catch", ["rxjs/Subscriber"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -2357,13 +3210,10 @@ System.register("rxjs/operator/catch", ["rxjs/Subscriber", "rxjs/util/tryCatch", 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; + var operator = new CatchOperator(selector); + var caught = this.lift(operator); + return (operator.caught = caught); } exports._catch = _catch; var CatchOperator = (function() { @@ -2374,124 +3224,94 @@ System.register("rxjs/operator/catch", ["rxjs/Subscriber", "rxjs/util/tryCatch", 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; + _super.call(this, 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.error = function(err) { + if (!this.isStopped) { + var result = void 0; + try { + result = this.selector(err, this.caught); + } catch (err) { + this.destination.error(err); + return ; + } + this._innerSub(result); } }; - CatchSubscriber.prototype._complete = function() { - this.lastSubscription.unsubscribe(); - this.destination.complete(); - }; - CatchSubscriber.prototype._unsubscribe = function() { - this.lastSubscription.unsubscribe(); + CatchSubscriber.prototype._innerSub = function(result) { + this.unsubscribe(); + this.destination.remove(this); + result.subscribe(this.destination); }; return CatchSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); global.define = __define; return module.exports; }); -System.register("rxjs/operator/combineAll", ["rxjs/operator/combineLatest-support"], true, function(require, exports, module) { +System.register("rxjs/operator/combineAll", ["rxjs/operator/combineLatest"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; - var combineLatest_support_1 = require("rxjs/operator/combineLatest-support"); + "use strict"; + var combineLatest_1 = require("rxjs/operator/combineLatest"); function combineAll(project) { - return this.lift(new combineLatest_support_1.CombineLatestOperator(project)); + return this.lift(new combineLatest_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) { +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 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; + "use strict"; + 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/operator/concat", ["rxjs/util/isScheduler", "rxjs/observable/fromArray", "rxjs/operator/mergeAll-support"], true, function(require, exports, module) { +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 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; + "use strict"; + 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/operator/concatAll", ["rxjs/operator/mergeAll-support"], true, function(require, exports, module) { +System.register("rxjs/operator/concatAll", ["rxjs/operator/mergeAll"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; - var mergeAll_support_1 = require("rxjs/operator/mergeAll-support"); + "use strict"; + var mergeAll_1 = require("rxjs/operator/mergeAll"); function concatAll() { - return this.lift(new mergeAll_support_1.MergeAllOperator(1)); + return this.lift(new mergeAll_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) { +System.register("rxjs/operator/mergeMap", ["rxjs/util/subscribeToResult", "rxjs/OuterSubscriber"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -2501,10 +3321,15 @@ System.register("rxjs/operator/mergeMap-support", ["rxjs/util/tryCatch", "rxjs/u } 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"); + function mergeMap(project, resultSelector, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + return this.lift(new MergeMapOperator(project, resultSelector, concurrent)); + } + exports.mergeMap = mergeMap; var MergeMapOperator = (function() { function MergeMapOperator(project, resultSelector, concurrent) { if (concurrent === void 0) { @@ -2518,7 +3343,7 @@ System.register("rxjs/operator/mergeMap-support", ["rxjs/util/tryCatch", "rxjs/u return new MergeMapSubscriber(observer, this.project, this.resultSelector, this.concurrent); }; return MergeMapOperator; - })(); + }()); exports.MergeMapOperator = MergeMapOperator; var MergeMapSubscriber = (function(_super) { __extends(MergeMapSubscriber, _super); @@ -2537,19 +3362,23 @@ System.register("rxjs/operator/mergeMap-support", ["rxjs/util/tryCatch", "rxjs/u } 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); - } + this._tryNext(value); } else { this.buffer.push(value); } }; + MergeMapSubscriber.prototype._tryNext = function(value) { + var result; + var index = this.index++; + try { + result = this.project(value, index); + } catch (err) { + this.destination.error(err); + return ; + } + this.active++; + this._innerSub(result, value, index); + }; MergeMapSubscriber.prototype._innerSub = function(ish, value, index) { this.add(subscribeToResult_1.subscribeToResult(this, ish, value, index)); }; @@ -2559,20 +3388,22 @@ System.register("rxjs/operator/mergeMap-support", ["rxjs/util/tryCatch", "rxjs/u 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); - } + MergeMapSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { + if (this.resultSelector) { + this._notifyResultSelector(outerValue, innerValue, outerIndex, innerIndex); } else { - destination.next(innerValue); + this.destination.next(innerValue); + } + }; + MergeMapSubscriber.prototype._notifyResultSelector = function(outerValue, innerValue, outerIndex, innerIndex) { + var result; + try { + result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex); + } catch (err) { + this.destination.error(err); + return ; } + this.destination.next(result); }; MergeMapSubscriber.prototype.notifyComplete = function(innerSub) { var buffer = this.buffer; @@ -2585,16 +3416,17 @@ System.register("rxjs/operator/mergeMap-support", ["rxjs/util/tryCatch", "rxjs/u } }; return MergeMapSubscriber; - })(OuterSubscriber_1.OuterSubscriber); + }(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) { +System.register("rxjs/operator/mergeMapTo", ["rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -2604,15 +3436,20 @@ System.register("rxjs/operator/mergeMapTo-support", ["rxjs/util/tryCatch", "rxjs } 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; - } + function mergeMapTo(observable, resultSelector, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + return this.lift(new MergeMapToOperator(observable, resultSelector, concurrent)); + } + exports.mergeMapTo = mergeMapTo; + 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; @@ -2621,7 +3458,7 @@ System.register("rxjs/operator/mergeMapTo-support", ["rxjs/util/tryCatch", "rxjs return new MergeMapToSubscriber(observer, this.ish, this.resultSelector, this.concurrent); }; return MergeMapToOperator; - })(); + }()); exports.MergeMapToOperator = MergeMapToOperator; var MergeMapToSubscriber = (function(_super) { __extends(MergeMapToSubscriber, _super); @@ -2659,21 +3496,29 @@ System.register("rxjs/operator/mergeMapTo-support", ["rxjs/util/tryCatch", "rxjs this.destination.complete(); } }; - MergeMapToSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex) { + MergeMapToSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { 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); - } + this.trySelectResult(outerValue, innerValue, outerIndex, innerIndex); } else { destination.next(innerValue); } }; + MergeMapToSubscriber.prototype.trySelectResult = function(outerValue, innerValue, outerIndex, innerIndex) { + var _a = this, + resultSelector = _a.resultSelector, + destination = _a.destination; + var result; + try { + result = resultSelector(outerValue, innerValue, outerIndex, innerIndex); + } catch (err) { + destination.error(err); + return ; + } + destination.next(result); + }; MergeMapToSubscriber.prototype.notifyError = function(err) { this.destination.error(err); }; @@ -2688,16 +3533,17 @@ System.register("rxjs/operator/mergeMapTo-support", ["rxjs/util/tryCatch", "rxjs } }; return MergeMapToSubscriber; - })(OuterSubscriber_1.OuterSubscriber); + }(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) { +System.register("rxjs/operator/count", ["rxjs/Subscriber"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -2708,8 +3554,6 @@ System.register("rxjs/operator/count", ["rxjs/Subscriber", "rxjs/util/tryCatch", 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)); } @@ -2723,7 +3567,7 @@ System.register("rxjs/operator/count", ["rxjs/Subscriber", "rxjs/util/tryCatch", return new CountSubscriber(subscriber, this.predicate, this.source); }; return CountOperator; - })(); + }()); var CountSubscriber = (function(_super) { __extends(CountSubscriber, _super); function CountSubscriber(destination, predicate, source) { @@ -2734,17 +3578,22 @@ System.register("rxjs/operator/count", ["rxjs/Subscriber", "rxjs/util/tryCatch", 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 (this.predicate) { + this._tryPredicate(value); + } else { + this.count++; } - if (passed) { - this.count += 1; + }; + CountSubscriber.prototype._tryPredicate = function(value) { + var result; + try { + result = this.predicate(value, this.index++, this.source); + } catch (err) { + this.destination.error(err); + return ; + } + if (result) { + this.count++; } }; CountSubscriber.prototype._complete = function() { @@ -2752,7 +3601,7 @@ System.register("rxjs/operator/count", ["rxjs/Subscriber", "rxjs/util/tryCatch", this.destination.complete(); }; return CountSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); global.define = __define; return module.exports; }); @@ -2761,6 +3610,7 @@ System.register("rxjs/operator/dematerialize", ["rxjs/Subscriber"], true, functi var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -2781,7 +3631,7 @@ System.register("rxjs/operator/dematerialize", ["rxjs/Subscriber"], true, functi return new DeMaterializeSubscriber(subscriber); }; return DeMaterializeOperator; - })(); + }()); var DeMaterializeSubscriber = (function(_super) { __extends(DeMaterializeSubscriber, _super); function DeMaterializeSubscriber(destination) { @@ -2791,15 +3641,16 @@ System.register("rxjs/operator/dematerialize", ["rxjs/Subscriber"], true, functi value.observe(this.destination); }; return DeMaterializeSubscriber; - })(Subscriber_1.Subscriber); + }(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) { +System.register("rxjs/operator/debounce", ["rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -2809,11 +3660,8 @@ System.register("rxjs/operator/debounce", ["rxjs/observable/fromPromise", "rxjs/ } 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"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); function debounce(durationSelector) { return this.lift(new DebounceOperator(durationSelector)); } @@ -2822,90 +3670,68 @@ System.register("rxjs/operator/debounce", ["rxjs/observable/fromPromise", "rxjs/ function DebounceOperator(durationSelector) { this.durationSelector = durationSelector; } - DebounceOperator.prototype.call = function(observer) { - return new DebounceSubscriber(observer, this.durationSelector); + DebounceOperator.prototype.call = function(subscriber) { + return new DebounceSubscriber(subscriber, 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; + this.hasValue = false; + this.durationSubscription = null; } - 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); + try { + var result = this.durationSelector.call(this, value); + if (result) { + this._tryNext(value, result); } - this.lastValue = value; - this.clearDebounce(); - this.add(this.debouncedSubscription = debounce._subscribe(new DurationSelectorSubscriber(this, currentIndex))); + } catch (err) { + this.destination.error(err); } }; DebounceSubscriber.prototype._complete = function() { - this.debouncedNext(); + this.emitValue(); 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; + DebounceSubscriber.prototype._tryNext = function(value, duration) { + var subscription = this.durationSubscription; + this.value = value; + this.hasValue = true; + if (subscription) { + subscription.unsubscribe(); + this.remove(subscription); } - }; - 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(); - } + subscription = subscribeToResult_1.subscribeToResult(this, duration); + if (!subscription.isUnsubscribed) { + this.add(this.durationSubscription = subscription); } }; - DurationSelectorSubscriber.prototype._next = function(unused) { - this.debounceNext(); + DebounceSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.emitValue(); }; - DurationSelectorSubscriber.prototype._error = function(err) { - this.parent.error(err); + DebounceSubscriber.prototype.notifyComplete = function() { + this.emitValue(); }; - DurationSelectorSubscriber.prototype._complete = function() { - this.debounceNext(); + DebounceSubscriber.prototype.emitValue = function() { + if (this.hasValue) { + var value = this.value; + var subscription = this.durationSubscription; + if (subscription) { + this.durationSubscription = null; + subscription.unsubscribe(); + this.remove(subscription); + } + this.value = null; + this.hasValue = false; + _super.prototype._next.call(this, value); + } }; - return DurationSelectorSubscriber; - })(Subscriber_1.Subscriber); + return DebounceSubscriber; + }(OuterSubscriber_1.OuterSubscriber)); global.define = __define; return module.exports; }); @@ -2914,6 +3740,7 @@ System.register("rxjs/operator/debounceTime", ["rxjs/Subscriber", "rxjs/schedule var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -2941,7 +3768,7 @@ System.register("rxjs/operator/debounceTime", ["rxjs/Subscriber", "rxjs/schedule return new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler); }; return DebounceTimeOperator; - })(); + }()); var DebounceTimeSubscriber = (function(_super) { __extends(DebounceTimeSubscriber, _super); function DebounceTimeSubscriber(destination, dueTime, scheduler) { @@ -2950,10 +3777,12 @@ System.register("rxjs/operator/debounceTime", ["rxjs/Subscriber", "rxjs/schedule this.scheduler = scheduler; this.debouncedSubscription = null; this.lastValue = null; + this.hasValue = false; } DebounceTimeSubscriber.prototype._next = function(value) { this.clearDebounce(); this.lastValue = value; + this.hasValue = true; this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this)); }; DebounceTimeSubscriber.prototype._complete = function() { @@ -2962,9 +3791,10 @@ System.register("rxjs/operator/debounceTime", ["rxjs/Subscriber", "rxjs/schedule }; DebounceTimeSubscriber.prototype.debouncedNext = function() { this.clearDebounce(); - if (this.lastValue != null) { + if (this.hasValue) { this.destination.next(this.lastValue); this.lastValue = null; + this.hasValue = false; } }; DebounceTimeSubscriber.prototype.clearDebounce = function() { @@ -2976,7 +3806,7 @@ System.register("rxjs/operator/debounceTime", ["rxjs/Subscriber", "rxjs/schedule } }; return DebounceTimeSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); function dispatchNext(subscriber) { subscriber.debouncedNext(); } @@ -2988,6 +3818,7 @@ System.register("rxjs/operator/defaultIfEmpty", ["rxjs/Subscriber"], true, funct var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -3013,7 +3844,7 @@ System.register("rxjs/operator/defaultIfEmpty", ["rxjs/Subscriber"], true, funct return new DefaultIfEmptySubscriber(subscriber, this.defaultValue); }; return DefaultIfEmptyOperator; - })(); + }()); var DefaultIfEmptySubscriber = (function(_super) { __extends(DefaultIfEmptySubscriber, _super); function DefaultIfEmptySubscriber(destination, defaultValue) { @@ -3032,15 +3863,16 @@ System.register("rxjs/operator/defaultIfEmpty", ["rxjs/Subscriber"], true, funct this.destination.complete(); }; return DefaultIfEmptySubscriber; - })(Subscriber_1.Subscriber); + }(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) { +System.register("rxjs/operator/delay", ["rxjs/scheduler/asap", "rxjs/util/isDate", "rxjs/Subscriber", "rxjs/Notification"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -3050,16 +3882,16 @@ System.register("rxjs/operator/delay", ["rxjs/Subscriber", "rxjs/Notification", } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; + var asap_1 = require("rxjs/scheduler/asap"); + var isDate_1 = require("rxjs/util/isDate"); 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; + scheduler = asap_1.asap; } var absoluteDelay = isDate_1.isDate(delay); - var delayFor = absoluteDelay ? (+delay - scheduler.now()) : delay; + var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay); return this.lift(new DelayOperator(delayFor, scheduler)); } exports.delay = delay; @@ -3072,7 +3904,7 @@ System.register("rxjs/operator/delay", ["rxjs/Subscriber", "rxjs/Notification", return new DelaySubscriber(subscriber, this.delay, this.scheduler); }; return DelayOperator; - })(); + }()); var DelaySubscriber = (function(_super) { __extends(DelaySubscriber, _super); function DelaySubscriber(destination, delay, scheduler) { @@ -3129,14 +3961,153 @@ System.register("rxjs/operator/delay", ["rxjs/Subscriber", "rxjs/Notification", this.scheduleNotification(Notification_1.Notification.createComplete()); }; return DelaySubscriber; - })(Subscriber_1.Subscriber); + }(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/delayWhen", ["rxjs/Subscriber", "rxjs/Observable", "rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + 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 OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); + function delayWhen(delayDurationSelector, subscriptionDelay) { + if (subscriptionDelay) { + return new SubscriptionDelayObservable(this, subscriptionDelay).lift(new DelayWhenOperator(delayDurationSelector)); + } + return this.lift(new DelayWhenOperator(delayDurationSelector)); + } + exports.delayWhen = delayWhen; + var DelayWhenOperator = (function() { + function DelayWhenOperator(delayDurationSelector) { + this.delayDurationSelector = delayDurationSelector; + } + DelayWhenOperator.prototype.call = function(subscriber) { + return new DelayWhenSubscriber(subscriber, this.delayDurationSelector); + }; + return DelayWhenOperator; + }()); + var DelayWhenSubscriber = (function(_super) { + __extends(DelayWhenSubscriber, _super); + function DelayWhenSubscriber(destination, delayDurationSelector) { + _super.call(this, destination); + this.delayDurationSelector = delayDurationSelector; + this.completed = false; + this.delayNotifierSubscriptions = []; + this.values = []; + } + DelayWhenSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.destination.next(outerValue); + this.removeSubscription(innerSub); + this.tryComplete(); + }; + DelayWhenSubscriber.prototype.notifyError = function(error, innerSub) { + this._error(error); + }; + DelayWhenSubscriber.prototype.notifyComplete = function(innerSub) { + var value = this.removeSubscription(innerSub); + if (value) { + this.destination.next(value); + } + this.tryComplete(); + }; + DelayWhenSubscriber.prototype._next = function(value) { + try { + var delayNotifier = this.delayDurationSelector(value); + if (delayNotifier) { + this.tryDelay(delayNotifier, value); + } + } catch (err) { + this.destination.error(err); + } + }; + DelayWhenSubscriber.prototype._complete = function() { + this.completed = true; + this.tryComplete(); + }; + DelayWhenSubscriber.prototype.removeSubscription = function(subscription) { + subscription.unsubscribe(); + var subscriptionIdx = this.delayNotifierSubscriptions.indexOf(subscription); + var value = null; + if (subscriptionIdx !== -1) { + value = this.values[subscriptionIdx]; + this.delayNotifierSubscriptions.splice(subscriptionIdx, 1); + this.values.splice(subscriptionIdx, 1); + } + return value; + }; + DelayWhenSubscriber.prototype.tryDelay = function(delayNotifier, value) { + var notifierSubscription = subscribeToResult_1.subscribeToResult(this, delayNotifier, value); + this.add(notifierSubscription); + this.delayNotifierSubscriptions.push(notifierSubscription); + this.values.push(value); + }; + DelayWhenSubscriber.prototype.tryComplete = function() { + if (this.completed && this.delayNotifierSubscriptions.length === 0) { + this.destination.complete(); + } + }; + return DelayWhenSubscriber; + }(OuterSubscriber_1.OuterSubscriber)); + var SubscriptionDelayObservable = (function(_super) { + __extends(SubscriptionDelayObservable, _super); + function SubscriptionDelayObservable(source, subscriptionDelay) { + _super.call(this); + this.source = source; + this.subscriptionDelay = subscriptionDelay; + } + SubscriptionDelayObservable.prototype._subscribe = function(subscriber) { + this.subscriptionDelay.subscribe(new SubscriptionDelaySubscriber(subscriber, this.source)); + }; + return SubscriptionDelayObservable; + }(Observable_1.Observable)); + var SubscriptionDelaySubscriber = (function(_super) { + __extends(SubscriptionDelaySubscriber, _super); + function SubscriptionDelaySubscriber(parent, source) { + _super.call(this); + this.parent = parent; + this.source = source; + this.sourceSubscribed = false; + } + SubscriptionDelaySubscriber.prototype._next = function(unused) { + this.subscribeToSource(); + }; + SubscriptionDelaySubscriber.prototype._error = function(err) { + this.unsubscribe(); + this.parent.error(err); + }; + SubscriptionDelaySubscriber.prototype._complete = function() { + this.subscribeToSource(); + }; + SubscriptionDelaySubscriber.prototype.subscribeToSource = function() { + if (!this.sourceSubscribed) { + this.sourceSubscribed = true; + this.unsubscribe(); + this.source.subscribe(this.parent); + } + }; + return SubscriptionDelaySubscriber; + }(Subscriber_1.Subscriber)); global.define = __define; return module.exports; }); @@ -3145,6 +4116,7 @@ System.register("rxjs/operator/distinctUntilChanged", ["rxjs/Subscriber", "rxjs/ var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -3157,24 +4129,26 @@ System.register("rxjs/operator/distinctUntilChanged", ["rxjs/Subscriber", "rxjs/ 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)); + function distinctUntilChanged(compare, keySelector) { + return this.lift(new DistinctUntilChangedOperator(compare, keySelector)); } exports.distinctUntilChanged = distinctUntilChanged; var DistinctUntilChangedOperator = (function() { - function DistinctUntilChangedOperator(compare) { + function DistinctUntilChangedOperator(compare, keySelector) { this.compare = compare; + this.keySelector = keySelector; } DistinctUntilChangedOperator.prototype.call = function(subscriber) { - return new DistinctUntilChangedSubscriber(subscriber, this.compare); + return new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector); }; return DistinctUntilChangedOperator; - })(); + }()); var DistinctUntilChangedSubscriber = (function(_super) { __extends(DistinctUntilChangedSubscriber, _super); - function DistinctUntilChangedSubscriber(destination, compare) { + function DistinctUntilChangedSubscriber(destination, compare, keySelector) { _super.call(this, destination); - this.hasValue = false; + this.keySelector = keySelector; + this.hasKey = false; if (typeof compare === 'function') { this.compare = compare; } @@ -3183,31 +4157,39 @@ System.register("rxjs/operator/distinctUntilChanged", ["rxjs/Subscriber", "rxjs/ return x === y; }; DistinctUntilChangedSubscriber.prototype._next = function(value) { + var keySelector = this.keySelector; + var key = value; + if (keySelector) { + key = tryCatch_1.tryCatch(this.keySelector)(value); + if (key === errorObject_1.errorObject) { + return this.destination.error(errorObject_1.errorObject.e); + } + } var result = false; - if (this.hasValue) { - result = tryCatch_1.tryCatch(this.compare)(this.value, value); + if (this.hasKey) { + result = tryCatch_1.tryCatch(this.compare)(this.key, key); if (result === errorObject_1.errorObject) { - this.destination.error(errorObject_1.errorObject.e); - return ; + return this.destination.error(errorObject_1.errorObject.e); } } else { - this.hasValue = true; + this.hasKey = true; } if (Boolean(result) === false) { - this.value = value; + this.key = key; this.destination.next(value); } }; return DistinctUntilChangedSubscriber; - })(Subscriber_1.Subscriber); + }(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) { +System.register("rxjs/operator/do", ["rxjs/Subscriber", "rxjs/util/noop"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -3219,8 +4201,6 @@ System.register("rxjs/operator/do", ["rxjs/Subscriber", "rxjs/util/noop", "rxjs/ }; 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') { @@ -3243,7 +4223,7 @@ System.register("rxjs/operator/do", ["rxjs/Subscriber", "rxjs/util/noop", "rxjs/ 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) { @@ -3252,40 +4232,44 @@ System.register("rxjs/operator/do", ["rxjs/Subscriber", "rxjs/util/noop", "rxjs/ 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._next = function(value) { + try { + this.__next(value); + } catch (err) { + this.destination.error(err); + return ; } + this.destination.next(value); }; - 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._error = function(err) { + try { + this.__error(err); + } catch (err) { + this.destination.error(err); + return ; } + this.destination.error(err); }; 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(); + try { + this.__complete(); + } catch (err) { + this.destination.error(err); + return ; } + this.destination.complete(); }; return DoSubscriber; - })(Subscriber_1.Subscriber); + }(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) { +System.register("rxjs/operator/expand", ["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; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -3299,6 +4283,17 @@ System.register("rxjs/operator/expand-support", ["rxjs/util/tryCatch", "rxjs/uti var errorObject_1 = require("rxjs/util/errorObject"); var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); + 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 ExpandOperator(project, concurrent, scheduler)); + } + exports.expand = expand; var ExpandOperator = (function() { function ExpandOperator(project, concurrent, scheduler) { this.project = project; @@ -3309,7 +4304,7 @@ System.register("rxjs/operator/expand-support", ["rxjs/util/tryCatch", "rxjs/uti return new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler); }; return ExpandOperator; - })(); + }()); exports.ExpandOperator = ExpandOperator; var ExpandSubscriber = (function(_super) { __extends(ExpandSubscriber, _super); @@ -3343,7 +4338,7 @@ System.register("rxjs/operator/expand-support", ["rxjs/util/tryCatch", "rxjs/uti destination.next(value); var result = tryCatch_1.tryCatch(this.project)(value, index); if (result === errorObject_1.errorObject) { - destination.error(result.e); + destination.error(errorObject_1.errorObject.e); } else if (!this.scheduler) { this.subscribeToProjection(result, value, index); } else { @@ -3360,12 +4355,8 @@ System.register("rxjs/operator/expand-support", ["rxjs/util/tryCatch", "rxjs/uti } }; 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)); - } + this.active++; + this.add(subscribeToResult_1.subscribeToResult(this, result, value, index)); }; ExpandSubscriber.prototype._complete = function() { this.hasCompleted = true; @@ -3373,6 +4364,9 @@ System.register("rxjs/operator/expand-support", ["rxjs/util/tryCatch", "rxjs/uti this.destination.complete(); } }; + ExpandSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this._next(innerValue); + }; ExpandSubscriber.prototype.notifyComplete = function(innerSub) { var buffer = this.buffer; this.remove(innerSub); @@ -3384,20 +4378,18 @@ System.register("rxjs/operator/expand-support", ["rxjs/util/tryCatch", "rxjs/uti this.destination.complete(); } }; - ExpandSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex) { - this._next(innerValue); - }; return ExpandSubscriber; - })(OuterSubscriber_1.OuterSubscriber); + }(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) { +System.register("rxjs/operator/filter", ["rxjs/Subscriber"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -3408,8 +4400,6 @@ System.register("rxjs/operator/filter", ["rxjs/Subscriber", "rxjs/util/tryCatch" 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)); } @@ -3423,25 +4413,30 @@ System.register("rxjs/operator/filter", ["rxjs/Subscriber", "rxjs/util/tryCatch" 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.select = select; 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); + FilterSubscriber.prototype._next = function(value) { + var result; + try { + result = this.select.call(this.thisArg, value, this.count++); + } catch (err) { + this.destination.error(err); + return ; + } + if (result) { + this.destination.next(value); } }; return FilterSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); global.define = __define; return module.exports; }); @@ -3450,6 +4445,7 @@ System.register("rxjs/operator/finally", ["rxjs/Subscriber", "rxjs/Subscription" var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -3473,7 +4469,7 @@ System.register("rxjs/operator/finally", ["rxjs/Subscriber", "rxjs/Subscription" return new FinallySubscriber(subscriber, this.finallySelector); }; return FinallyOperator; - })(); + }()); var FinallySubscriber = (function(_super) { __extends(FinallySubscriber, _super); function FinallySubscriber(destination, finallySelector) { @@ -3481,7 +4477,7 @@ System.register("rxjs/operator/finally", ["rxjs/Subscriber", "rxjs/Subscription" this.add(new Subscription_1.Subscription(finallySelector)); } return FinallySubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); global.define = __define; return module.exports; }); @@ -3490,22 +4486,52 @@ System.register("rxjs/util/EmptyError", [], true, function(require, exports, mod var global = System.global, __define = global.define; global.define = undefined; - var EmptyError = (function() { + "use strict"; + 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 EmptyError = (function(_super) { + __extends(EmptyError, _super); function EmptyError() { + _super.call(this, 'no elements in sequence'); this.name = 'EmptyError'; - this.message = 'no elements in sequence'; } return EmptyError; - })(); + }(Error)); exports.EmptyError = EmptyError; global.define = __define; return module.exports; }); +System.register("rxjs/Operator", ["rxjs/Subscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + var Subscriber_1 = require("rxjs/Subscriber"); + var Operator = (function() { + function Operator() {} + Operator.prototype.call = function(subscriber) { + return new Subscriber_1.Subscriber(subscriber); + }; + return Operator; + }()); + exports.Operator = Operator; + 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; + "use strict"; var MapPolyfill = (function() { function MapPolyfill() { this.size = 0; @@ -3537,13 +4563,18 @@ System.register("rxjs/util/MapPolyfill", [], true, function(require, exports, mo this.size--; return true; }; + MapPolyfill.prototype.clear = function() { + this._keys.length = 0; + this._values.length = 0; + this.size = 0; + }; 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; @@ -3553,6 +4584,7 @@ System.register("rxjs/util/FastMap", [], true, function(require, exports, module var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var FastMap = (function() { function FastMap() { this.values = {}; @@ -3580,16 +4612,17 @@ System.register("rxjs/util/FastMap", [], true, function(require, exports, module 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) { +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; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -3599,77 +4632,117 @@ System.register("rxjs/operator/groupBy-support", ["rxjs/Subscription", "rxjs/Obs } 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; + 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); } - 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; + IgnoreElementsSubscriber.prototype._next = function(unused) { + noop_1.noop(); }; - 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++; + return IgnoreElementsSubscriber; + }(Subscriber_1.Subscriber)); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/inspect", ["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; + "use strict"; + 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; } - 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(); + 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 inspect(durationSelector) { + return this.lift(new InspectOperator(durationSelector)); + } + exports.inspect = inspect; + var InspectOperator = (function() { + function InspectOperator(durationSelector) { + this.durationSelector = durationSelector; + } + InspectOperator.prototype.call = function(subscriber) { + return new InspectSubscriber(subscriber, this.durationSelector); + }; + return InspectOperator; + }()); + var InspectSubscriber = (function(_super) { + __extends(InspectSubscriber, _super); + function InspectSubscriber(destination, durationSelector) { + _super.call(this, destination); + this.durationSelector = durationSelector; + this.hasValue = false; + } + InspectSubscriber.prototype._next = function(value) { + this.value = value; + this.hasValue = true; + if (!this.throttled) { + var duration = tryCatch_1.tryCatch(this.durationSelector)(value); + if (duration === errorObject_1.errorObject) { + this.destination.error(errorObject_1.errorObject.e); + } else { + this.add(this.throttled = subscribeToResult_1.subscribeToResult(this, duration)); } } }; - return InnerRefCountSubscription; - })(Subscription_1.Subscription); - exports.InnerRefCountSubscription = InnerRefCountSubscription; + InspectSubscriber.prototype.clearThrottle = function() { + var _a = this, + value = _a.value, + hasValue = _a.hasValue, + throttled = _a.throttled; + if (throttled) { + this.remove(throttled); + this.throttled = null; + throttled.unsubscribe(); + } + if (hasValue) { + this.value = null; + this.hasValue = false; + this.destination.next(value); + } + }; + InspectSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex) { + this.clearThrottle(); + }; + InspectSubscriber.prototype.notifyComplete = function() { + this.clearThrottle(); + }; + return InspectSubscriber; + }(OuterSubscriber_1.OuterSubscriber)); global.define = __define; return module.exports; }); -System.register("rxjs/operator/ignoreElements", ["rxjs/Subscriber", "rxjs/util/noop"], true, function(require, exports, module) { +System.register("rxjs/operator/inspectTime", ["rxjs/scheduler/asap", "rxjs/Subscriber"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -3679,38 +4752,70 @@ System.register("rxjs/operator/ignoreElements", ["rxjs/Subscriber", "rxjs/util/n } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; + var asap_1 = require("rxjs/scheduler/asap"); var Subscriber_1 = require("rxjs/Subscriber"); - var noop_1 = require("rxjs/util/noop"); - function ignoreElements() { - return this.lift(new IgnoreElementsOperator()); + function inspectTime(delay, scheduler) { + if (scheduler === void 0) { + scheduler = asap_1.asap; + } + return this.lift(new InspectTimeOperator(delay, scheduler)); } - exports.ignoreElements = ignoreElements; - ; - var IgnoreElementsOperator = (function() { - function IgnoreElementsOperator() {} - IgnoreElementsOperator.prototype.call = function(subscriber) { - return new IgnoreElementsSubscriber(subscriber); + exports.inspectTime = inspectTime; + var InspectTimeOperator = (function() { + function InspectTimeOperator(delay, scheduler) { + this.delay = delay; + this.scheduler = scheduler; + } + InspectTimeOperator.prototype.call = function(subscriber) { + return new InspectTimeSubscriber(subscriber, this.delay, this.scheduler); }; - return IgnoreElementsOperator; - })(); - var IgnoreElementsSubscriber = (function(_super) { - __extends(IgnoreElementsSubscriber, _super); - function IgnoreElementsSubscriber() { - _super.apply(this, arguments); + return InspectTimeOperator; + }()); + var InspectTimeSubscriber = (function(_super) { + __extends(InspectTimeSubscriber, _super); + function InspectTimeSubscriber(destination, delay, scheduler) { + _super.call(this, destination); + this.delay = delay; + this.scheduler = scheduler; + this.hasValue = false; } - IgnoreElementsSubscriber.prototype._next = function(unused) { - noop_1.noop(); + InspectTimeSubscriber.prototype._next = function(value) { + this.value = value; + this.hasValue = true; + if (!this.throttled) { + this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.delay, this)); + } }; - return IgnoreElementsSubscriber; - })(Subscriber_1.Subscriber); + InspectTimeSubscriber.prototype.clearThrottle = function() { + var _a = this, + value = _a.value, + hasValue = _a.hasValue, + throttled = _a.throttled; + if (throttled) { + this.remove(throttled); + this.throttled = null; + throttled.unsubscribe(); + } + if (hasValue) { + this.value = null; + this.hasValue = false; + this.destination.next(value); + } + }; + return InspectTimeSubscriber; + }(Subscriber_1.Subscriber)); + function dispatchNext(subscriber) { + subscriber.clearThrottle(); + } 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) { +System.register("rxjs/operator/every", ["rxjs/Subscriber"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -3720,34 +4825,9 @@ System.register("rxjs/operator/every", ["rxjs/observable/ScalarObservable", "rxj } 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; @@ -3761,7 +4841,7 @@ System.register("rxjs/operator/every", ["rxjs/observable/ScalarObservable", "rxj 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) { @@ -3770,16 +4850,21 @@ System.register("rxjs/operator/every", ["rxjs/observable/ScalarObservable", "rxj this.thisArg = thisArg; this.source = source; this.index = 0; + this.thisArg = thisArg || this; } 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) { + var result = false; + try { + result = this.predicate.call(this.thisArg, value, this.index++, this.source); + } catch (err) { + this.destination.error(err); + return ; + } + if (!result) { this.notifyComplete(false); } }; @@ -3787,15 +4872,16 @@ System.register("rxjs/operator/every", ["rxjs/observable/ScalarObservable", "rxj this.notifyComplete(true); }; return EverySubscriber; - })(Subscriber_1.Subscriber); + }(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) { +System.register("rxjs/operator/last", ["rxjs/Subscriber", "rxjs/util/EmptyError"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -3806,8 +4892,6 @@ System.register("rxjs/operator/last", ["rxjs/Subscriber", "rxjs/util/tryCatch", 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)); @@ -3824,7 +4908,7 @@ System.register("rxjs/operator/last", ["rxjs/Subscriber", "rxjs/util/tryCatch", 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) { @@ -3841,35 +4925,46 @@ System.register("rxjs/operator/last", ["rxjs/Subscriber", "rxjs/util/tryCatch", } } 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); + if (this.predicate) { + this._tryPredicate(value, index); + } else { + if (this.resultSelector) { + this._tryResultSelector(value, index); 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; + this.lastValue = value; + this.hasValue = true; + } + }; + LastSubscriber.prototype._tryPredicate = function(value, index) { + var result; + try { + result = this.predicate(value, index, this.source); + } catch (err) { + this.destination.error(err); + return ; + } + if (result) { + if (this.resultSelector) { + this._tryResultSelector(value, index); + return ; } - } else { this.lastValue = value; this.hasValue = true; } }; + LastSubscriber.prototype._tryResultSelector = function(value, index) { + var result; + try { + result = this.resultSelector(value, index); + } catch (err) { + this.destination.error(err); + return ; + } + this.lastValue = result; + this.hasValue = true; + }; LastSubscriber.prototype._complete = function() { var destination = this.destination; if (this.hasValue) { @@ -3880,15 +4975,29 @@ System.register("rxjs/operator/last", ["rxjs/Subscriber", "rxjs/util/tryCatch", } }; return LastSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/let", [], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + function letProto(func) { + return func(this); + } + exports.letProto = letProto; global.define = __define; return module.exports; }); -System.register("rxjs/operator/map", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { +System.register("rxjs/operator/map", ["rxjs/Subscriber"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -3899,8 +5008,6 @@ System.register("rxjs/operator/map", ["rxjs/Subscriber", "rxjs/util/tryCatch", " 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()`?'); @@ -3917,25 +5024,27 @@ System.register("rxjs/operator/map", ["rxjs/Subscriber", "rxjs/util/tryCatch", " 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; + this.thisArg = thisArg || this; } - 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); + MapSubscriber.prototype._next = function(value) { + var result; + try { + result = this.project.call(this.thisArg, value, this.count++); + } catch (err) { + this.destination.error(err); + return ; } + this.destination.next(result); }; return MapSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); global.define = __define; return module.exports; }); @@ -3944,6 +5053,7 @@ System.register("rxjs/operator/mapTo", ["rxjs/Subscriber"], true, function(requi var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -3966,7 +5076,7 @@ System.register("rxjs/operator/mapTo", ["rxjs/Subscriber"], true, function(requi return new MapToSubscriber(subscriber, this.value); }; return MapToOperator; - })(); + }()); var MapToSubscriber = (function(_super) { __extends(MapToSubscriber, _super); function MapToSubscriber(destination, value) { @@ -3977,7 +5087,7 @@ System.register("rxjs/operator/mapTo", ["rxjs/Subscriber"], true, function(requi this.destination.next(this.value); }; return MapToSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); global.define = __define; return module.exports; }); @@ -3986,6 +5096,7 @@ System.register("rxjs/operator/materialize", ["rxjs/Subscriber", "rxjs/Notificat var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -4007,7 +5118,7 @@ System.register("rxjs/operator/materialize", ["rxjs/Subscriber", "rxjs/Notificat return new MaterializeSubscriber(subscriber); }; return MaterializeOperator; - })(); + }()); var MaterializeSubscriber = (function(_super) { __extends(MaterializeSubscriber, _super); function MaterializeSubscriber(destination) { @@ -4027,224 +5138,80 @@ System.register("rxjs/operator/materialize", ["rxjs/Subscriber", "rxjs/Notificat destination.complete(); }; return MaterializeSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); global.define = __define; return module.exports; }); -System.register("rxjs/operator/merge", ["rxjs/operator/merge-static"], true, function(require, exports, module) { +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 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; + "use strict"; + 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/operator/mergeAll", ["rxjs/operator/mergeAll-support"], true, function(require, exports, module) { +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 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; + "use strict"; + 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/operator/mergeMap", ["rxjs/operator/mergeMap-support"], true, function(require, exports, module) { +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 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; + "use strict"; + 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/operator/mergeMapTo", ["rxjs/operator/mergeMapTo-support"], true, function(require, exports, module) { +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 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; + "use strict"; + 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/observable/ConnectableObservable", ["rxjs/Observable", "rxjs/Subscription", "rxjs/Subscriber"], true, function(require, exports, module) { +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 __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 __()); - }; + "use strict"; 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); + var multicast_1 = require("rxjs/operator/multicast"); + Observable_1.Observable.prototype.multicast = multicast_1.multicast; global.define = __define; return module.exports; }); -System.register("rxjs/operator/observeOn", ["rxjs/operator/observeOn-support"], true, function(require, exports, module) { +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 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; + "use strict"; + 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; }); @@ -4253,6 +5220,7 @@ System.register("rxjs/util/not", [], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; function not(pred, thisArg) { function notPred() { return !(notPred.pred.apply(notPred.thisArg, arguments)); @@ -4266,50 +5234,63 @@ System.register("rxjs/util/not", [], true, function(require, exports, module) { return module.exports; }); -System.register("rxjs/operator/publish", ["rxjs/Subject", "rxjs/operator/multicast"], true, function(require, exports, module) { +System.register("rxjs/operator/pluck", ["rxjs/operator/map"], 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()); + "use strict"; + var map_1 = require("rxjs/operator/map"); + function pluck() { + var properties = []; + for (var _i = 0; _i < arguments.length; _i++) { + properties[_i - 0] = arguments[_i]; + } + var length = properties.length; + if (length === 0) { + throw new Error('List of properties cannot be empty.'); + } + return map_1.map.call(this, plucker(properties, length)); + } + exports.pluck = pluck; + function plucker(props, length) { + var mapper = function(x) { + var currentProp = x; + for (var i = 0; i < length; i++) { + var p = currentProp[props[i]]; + if (typeof p !== 'undefined') { + currentProp = p; + } else { + return undefined; + } + } + return currentProp; + }; + return mapper; } - exports.publish = publish; global.define = __define; return module.exports; }); -System.register("rxjs/util/ObjectUnsubscribedError", [], true, function(require, exports, module) { +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 __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; + "use strict"; + 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/subject/ReplaySubject", ["rxjs/Subject", "rxjs/scheduler/queue"], true, function(require, exports, module) { +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; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -4320,70 +5301,59 @@ System.register("rxjs/subject/ReplaySubject", ["rxjs/Subject", "rxjs/scheduler/q 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; - } + 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.events = []; - this.bufferSize = bufferSize < 1 ? 1 : bufferSize; - this._windowTime = windowTime < 1 ? 1 : windowTime; - this.scheduler = scheduler; + this._value = _value; } - 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); + BehaviorSubject.prototype.getValue = function() { + if (this.hasErrored) { + throwError_1.throwError(this.errorValue); + } else if (this.isUnsubscribed) { + throwError_1.throwError(new ObjectUnsubscribedError_1.ObjectUnsubscribedError()); + } else { + return 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); + 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 && !subscription.isUnsubscribed) { + subscriber.next(this._value); } - return _super.prototype._subscribe.call(this, subscriber); + return subscription; }; - ReplaySubject.prototype._getNow = function() { - return (this.scheduler || queue_1.queue).now(); + BehaviorSubject.prototype._next = function(value) { + _super.prototype._next.call(this, this._value = value); }; - 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; + BehaviorSubject.prototype._error = function(err) { + this.hasErrored = true; + _super.prototype._error.call(this, this.errorValue = err); }; - return ReplaySubject; - })(Subject_1.Subject); - exports.ReplaySubject = ReplaySubject; - var ReplayEvent = (function() { - function ReplayEvent(time, value) { - this.time = time; - this.value = value; - } - return ReplayEvent; - })(); + return BehaviorSubject; + }(Subject_1.Subject)); + exports.BehaviorSubject = BehaviorSubject; + 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; + "use strict"; + 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; }); @@ -4392,6 +5362,7 @@ System.register("rxjs/operator/publishLast", ["rxjs/subject/AsyncSubject", "rxjs var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var AsyncSubject_1 = require("rxjs/subject/AsyncSubject"); var multicast_1 = require("rxjs/operator/multicast"); function publishLast() { @@ -4402,11 +5373,24 @@ System.register("rxjs/operator/publishLast", ["rxjs/subject/AsyncSubject", "rxjs return module.exports; }); -System.register("rxjs/operator/reduce-support", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { +System.register("rxjs/add/operator/race", ["rxjs/Observable", "rxjs/operator/race"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; - var __extends = (this && this.__extends) || function(d, b) { + "use strict"; + var Observable_1 = require("rxjs/Observable"); + var race_1 = require("rxjs/operator/race"); + Observable_1.Observable.prototype.race = race_1.race; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/reduce", ["rxjs/Subscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; @@ -4416,8 +5400,10 @@ System.register("rxjs/operator/reduce-support", ["rxjs/Subscriber", "rxjs/util/t 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 reduce(project, seed) { + return this.lift(new ReduceOperator(project, seed)); + } + exports.reduce = reduce; var ReduceOperator = (function() { function ReduceOperator(project, seed) { this.project = project; @@ -4427,7 +5413,7 @@ System.register("rxjs/operator/reduce-support", ["rxjs/Subscriber", "rxjs/util/t return new ReduceSubscriber(subscriber, this.project, this.seed); }; return ReduceOperator; - })(); + }()); exports.ReduceOperator = ReduceOperator; var ReduceSubscriber = (function(_super) { __extends(ReduceSubscriber, _super); @@ -4438,19 +5424,24 @@ System.register("rxjs/operator/reduce-support", ["rxjs/Subscriber", "rxjs/util/t this.project = project; this.hasSeed = typeof seed !== 'undefined'; } - ReduceSubscriber.prototype._next = function(x) { + ReduceSubscriber.prototype._next = function(value) { 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; - } + this._tryReduce(value); } else { - this.acc = x; + this.acc = value; this.hasValue = true; } }; + ReduceSubscriber.prototype._tryReduce = function(value) { + var result; + try { + result = this.project(this.acc, value); + } catch (err) { + this.destination.error(err); + return ; + } + this.acc = result; + }; ReduceSubscriber.prototype._complete = function() { if (this.hasValue || this.hasSeed) { this.destination.next(this.acc); @@ -4458,16 +5449,17 @@ System.register("rxjs/operator/reduce-support", ["rxjs/Subscriber", "rxjs/util/t this.destination.complete(); }; return ReduceSubscriber; - })(Subscriber_1.Subscriber); + }(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) { +System.register("rxjs/operator/repeat", ["rxjs/Subscriber", "rxjs/observable/EmptyObservable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -4478,15 +5470,17 @@ System.register("rxjs/operator/repeat", ["rxjs/Subscriber", "rxjs/observable/emp d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Subscriber_1 = require("rxjs/Subscriber"); - var empty_1 = require("rxjs/observable/empty"); + var EmptyObservable_1 = require("rxjs/observable/EmptyObservable"); function repeat(count) { if (count === void 0) { count = -1; } if (count === 0) { - return new empty_1.EmptyObservable(); + return new EmptyObservable_1.EmptyObservable(); + } else if (count < 0) { + return this.lift(new RepeatOperator(-1, this)); } else { - return this.lift(new RepeatOperator(count, this)); + return this.lift(new RepeatOperator(count - 1, this)); } } exports.repeat = repeat; @@ -4496,74 +5490,35 @@ System.register("rxjs/operator/repeat", ["rxjs/Subscriber", "rxjs/observable/emp this.source = source; } RepeatOperator.prototype.call = function(subscriber) { - return new FirstRepeatSubscriber(subscriber, this.count, this.source); + return new RepeatSubscriber(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; + }()); + var RepeatSubscriber = (function(_super) { + __extends(RepeatSubscriber, _super); + function RepeatSubscriber(destination, count, source) { + _super.call(this, 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); + RepeatSubscriber.prototype.complete = function() { + if (!this.isStopped) { + var _a = this, + source = _a.source, + count = _a.count; + if (count === 0) { + return _super.prototype.complete.call(this); + } else if (count > -1) { + this.count = count - 1; + } + this.unsubscribe(); + this.isStopped = false; + this.isUnsubscribed = false; + source.subscribe(this); } }; - 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); + return RepeatSubscriber; + }(Subscriber_1.Subscriber)); global.define = __define; return module.exports; }); @@ -4572,6 +5527,7 @@ System.register("rxjs/operator/retry", ["rxjs/Subscriber"], true, function(requi var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -4584,7 +5540,7 @@ System.register("rxjs/operator/retry", ["rxjs/Subscriber"], true, function(requi var Subscriber_1 = require("rxjs/Subscriber"); function retry(count) { if (count === void 0) { - count = 0; + count = -1; } return this.lift(new RetryOperator(count, this)); } @@ -4595,85 +5551,44 @@ System.register("rxjs/operator/retry", ["rxjs/Subscriber"], true, function(requi this.source = source; } RetryOperator.prototype.call = function(subscriber) { - return new FirstRetrySubscriber(subscriber, this.count, this.source); + return new RetrySubscriber(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; + }()); + var RetrySubscriber = (function(_super) { + __extends(RetrySubscriber, _super); + function RetrySubscriber(destination, count, source) { + _super.call(this, 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) { + RetrySubscriber.prototype.error = function(err) { + if (!this.isStopped) { + var _a = this, + source = _a.source, + count = _a.count; + if (count === 0) { + return _super.prototype.error.call(this, err); + } else if (count > -1) { + this.count = count - 1; + } 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); + this.isStopped = false; + this.isUnsubscribed = false; + source.subscribe(this); } }; - RetryMoreSubscriber.prototype._complete = function() { - this.parent.destination.complete(); - }; - return RetryMoreSubscriber; - })(Subscriber_1.Subscriber); + return RetrySubscriber; + }(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) { +System.register("rxjs/operator/retryWhen", ["rxjs/Subject", "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; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -4683,10 +5598,11 @@ System.register("rxjs/operator/retryWhen", ["rxjs/Subscriber", "rxjs/Subject", " } 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"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); function retryWhen(notifier) { return this.lift(new RetryWhenOperator(notifier, this)); } @@ -4697,123 +5613,82 @@ System.register("rxjs/operator/retryWhen", ["rxjs/Subscriber", "rxjs/Subject", " this.source = source; } RetryWhenOperator.prototype.call = function(subscriber) { - return new FirstRetryWhenSubscriber(subscriber, this.notifier, this.source); + return new RetryWhenSubscriber(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; + }()); + var RetryWhenSubscriber = (function(_super) { + __extends(RetryWhenSubscriber, _super); + function RetryWhenSubscriber(destination, notifier, source) { + _super.call(this, 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); + RetryWhenSubscriber.prototype.error = function(err) { + if (!this.isStopped) { + var errors = this.errors; + var retries = this.retries; + var retriesSubscription = this.retriesSubscription; + if (!retries) { + errors = new Subject_1.Subject(); + retries = tryCatch_1.tryCatch(this.notifier)(errors); + if (retries === errorObject_1.errorObject) { + return _super.prototype.error.call(this, errorObject_1.errorObject.e); } + retriesSubscription = subscribeToResult_1.subscribeToResult(this, retries); + } else { + this.errors = null; + this.retriesSubscription = null; } - this.errors.next(err); + this.unsubscribe(); + this.isUnsubscribed = false; + this.errors = errors; + this.retries = retries; + this.retriesSubscription = retriesSubscription; + 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(); + RetryWhenSubscriber.prototype._unsubscribe = function() { + var _a = this, + errors = _a.errors, + retriesSubscription = _a.retriesSubscription; + if (errors) { + errors.unsubscribe(); + this.errors = null; } - }; - FirstRetryWhenSubscriber.prototype.tearDown = function() { - _super.prototype.unsubscribe.call(this); - this.lastSubscription.unsubscribe(); - var notificationSubscription = this.notificationSubscription; - if (notificationSubscription) { - notificationSubscription.unsubscribe(); + if (retriesSubscription) { + retriesSubscription.unsubscribe(); + this.retriesSubscription = null; } + this.retries = null; }; - FirstRetryWhenSubscriber.prototype.resubscribe = function() { + RetryWhenSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { 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(); + errors = _a.errors, + retries = _a.retries, + retriesSubscription = _a.retriesSubscription; + this.errors = null; + this.retries = null; + this.retriesSubscription = null; + this.unsubscribe(); + this.isStopped = false; + this.isUnsubscribed = false; + this.errors = errors; + this.retries = retries; + this.retriesSubscription = retriesSubscription; + this.source.subscribe(this); }; - return RetryNotificationSubscriber; - })(Subscriber_1.Subscriber); + return RetryWhenSubscriber; + }(OuterSubscriber_1.OuterSubscriber)); global.define = __define; return module.exports; }); -System.register("rxjs/operator/sample", ["rxjs/Subscriber"], true, function(require, exports, module) { +System.register("rxjs/operator/sample", ["rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -4823,7 +5698,8 @@ System.register("rxjs/operator/sample", ["rxjs/Subscriber"], true, function(requ } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; - var Subscriber_1 = require("rxjs/Subscriber"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); function sample(notifier) { return this.lift(new SampleOperator(notifier)); } @@ -4836,44 +5712,32 @@ System.register("rxjs/operator/sample", ["rxjs/Subscriber"], true, function(requ 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))); + this.add(subscribeToResult_1.subscribeToResult(this, notifier)); } SampleSubscriber.prototype._next = function(value) { - this.lastValue = value; + this.value = value; this.hasValue = true; }; - SampleSubscriber.prototype.notifyNext = function() { + SampleSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.emitValue(); + }; + SampleSubscriber.prototype.notifyComplete = function() { + this.emitValue(); + }; + SampleSubscriber.prototype.emitValue = function() { if (this.hasValue) { this.hasValue = false; - this.destination.next(this.lastValue); + this.destination.next(this.value); } }; 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); + }(OuterSubscriber_1.OuterSubscriber)); global.define = __define; return module.exports; }); @@ -4882,6 +5746,7 @@ System.register("rxjs/operator/sampleTime", ["rxjs/Subscriber", "rxjs/scheduler/ var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -4909,7 +5774,7 @@ System.register("rxjs/operator/sampleTime", ["rxjs/Subscriber", "rxjs/scheduler/ return new SampleTimeSubscriber(subscriber, this.delay, this.scheduler); }; return SampleTimeOperator; - })(); + }()); var SampleTimeSubscriber = (function(_super) { __extends(SampleTimeSubscriber, _super); function SampleTimeSubscriber(destination, delay, scheduler) { @@ -4933,7 +5798,7 @@ System.register("rxjs/operator/sampleTime", ["rxjs/Subscriber", "rxjs/scheduler/ } }; return SampleTimeSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); function dispatchNotification(state) { var subscriber = state.subscriber, delay = state.delay; @@ -4944,10 +5809,11 @@ System.register("rxjs/operator/sampleTime", ["rxjs/Subscriber", "rxjs/scheduler/ return module.exports; }); -System.register("rxjs/operator/scan", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { +System.register("rxjs/operator/scan", ["rxjs/Subscriber"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -4958,8 +5824,6 @@ System.register("rxjs/operator/scan", ["rxjs/Subscriber", "rxjs/util/tryCatch", 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)); } @@ -4973,7 +5837,7 @@ System.register("rxjs/operator/scan", ["rxjs/Subscriber", "rxjs/util/tryCatch", return new ScanSubscriber(subscriber, this.accumulator, this.seed); }; return ScanOperator; - })(); + }()); var ScanSubscriber = (function(_super) { __extends(ScanSubscriber, _super); function ScanSubscriber(destination, accumulator, seed) { @@ -5000,17 +5864,21 @@ System.register("rxjs/operator/scan", ["rxjs/Subscriber", "rxjs/util/tryCatch", 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 this._tryNext(value); + } + }; + ScanSubscriber.prototype._tryNext = function(value) { + var result; + try { + result = this.accumulator(this.seed, value); + } catch (err) { + this.destination.error(err); } + this.seed = result; + this.destination.next(result); }; return ScanSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); global.define = __define; return module.exports; }); @@ -5019,6 +5887,7 @@ System.register("rxjs/operator/share", ["rxjs/operator/multicast", "rxjs/Subject var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var multicast_1 = require("rxjs/operator/multicast"); var Subject_1 = require("rxjs/Subject"); function shareSubjectFactory() { @@ -5033,10 +5902,11 @@ System.register("rxjs/operator/share", ["rxjs/operator/multicast", "rxjs/Subject return module.exports; }); -System.register("rxjs/operator/single", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject", "rxjs/util/EmptyError"], true, function(require, exports, module) { +System.register("rxjs/operator/single", ["rxjs/Subscriber", "rxjs/util/EmptyError"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -5047,8 +5917,6 @@ System.register("rxjs/operator/single", ["rxjs/Subscriber", "rxjs/util/tryCatch" 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)); @@ -5063,7 +5931,7 @@ System.register("rxjs/operator/single", ["rxjs/Subscriber", "rxjs/util/tryCatch" return new SingleSubscriber(subscriber, this.predicate, this.source); }; return SingleOperator; - })(); + }()); var SingleSubscriber = (function(_super) { __extends(SingleSubscriber, _super); function SingleSubscriber(destination, predicate, source) { @@ -5083,18 +5951,23 @@ System.register("rxjs/operator/single", ["rxjs/Subscriber", "rxjs/util/tryCatch" }; SingleSubscriber.prototype._next = function(value) { var predicate = this.predicate; - var currentIndex = this.index++; + 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); - } + this.tryNext(value); } else { this.applySingleValue(value); } }; + SingleSubscriber.prototype.tryNext = function(value) { + try { + var result = this.predicate(value, this.index, this.source); + if (result) { + this.applySingleValue(value); + } + } catch (err) { + this.destination.error(err); + } + }; SingleSubscriber.prototype._complete = function() { var destination = this.destination; if (this.index > 0) { @@ -5105,7 +5978,7 @@ System.register("rxjs/operator/single", ["rxjs/Subscriber", "rxjs/util/tryCatch" } }; return SingleSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); global.define = __define; return module.exports; }); @@ -5114,6 +5987,7 @@ System.register("rxjs/operator/skip", ["rxjs/Subscriber"], true, function(requir var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -5136,7 +6010,7 @@ System.register("rxjs/operator/skip", ["rxjs/Subscriber"], true, function(requir return new SkipSubscriber(subscriber, this.total); }; return SkipOperator; - })(); + }()); var SkipSubscriber = (function(_super) { __extends(SkipSubscriber, _super); function SkipSubscriber(destination, total) { @@ -5150,15 +6024,16 @@ System.register("rxjs/operator/skip", ["rxjs/Subscriber"], true, function(requir } }; return SkipSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); global.define = __define; return module.exports; }); -System.register("rxjs/operator/skipUntil", ["rxjs/Subscriber"], true, function(require, exports, module) { +System.register("rxjs/operator/skipUntil", ["rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -5168,7 +6043,8 @@ System.register("rxjs/operator/skipUntil", ["rxjs/Subscriber"], true, function(r } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; - var Subscriber_1 = require("rxjs/Subscriber"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); function skipUntil(notifier) { return this.lift(new SkipUntilOperator(notifier)); } @@ -5181,70 +6057,47 @@ System.register("rxjs/operator/skipUntil", ["rxjs/Subscriber"], true, function(r 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)); + this.hasValue = false; + this.isInnerStopped = false; + this.add(subscribeToResult_1.subscribeToResult(this, notifier)); } SkipUntilSubscriber.prototype._next = function(value) { - if (this.notificationSubscriber.hasValue) { - this.destination.next(value); + if (this.hasValue) { + _super.prototype._next.call(this, 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; + if (this.isInnerStopped) { + _super.prototype._complete.call(this); } else { - _super.prototype.unsubscribe.call(this); + this.unsubscribe(); } }; - 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); + SkipUntilSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { this.hasValue = true; }; - NotificationSubscriber.prototype._complete = function() { - this.hasCompleted = true; + SkipUntilSubscriber.prototype.notifyComplete = function() { + this.isInnerStopped = true; + if (this.isStopped) { + _super.prototype._complete.call(this); + } }; - return NotificationSubscriber; - })(Subscriber_1.Subscriber); + return SkipUntilSubscriber; + }(OuterSubscriber_1.OuterSubscriber)); global.define = __define; return module.exports; }); -System.register("rxjs/operator/skipWhile", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { +System.register("rxjs/operator/skipWhile", ["rxjs/Subscriber"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -5255,8 +6108,6 @@ System.register("rxjs/operator/skipWhile", ["rxjs/Subscriber", "rxjs/util/tryCat 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)); } @@ -5269,7 +6120,7 @@ System.register("rxjs/operator/skipWhile", ["rxjs/Subscriber", "rxjs/util/tryCat return new SkipWhileSubscriber(subscriber, this.predicate); }; return SkipWhileOperator; - })(); + }()); var SkipWhileSubscriber = (function(_super) { __extends(SkipWhileSubscriber, _super); function SkipWhileSubscriber(destination, predicate) { @@ -5280,33 +6131,36 @@ System.register("rxjs/operator/skipWhile", ["rxjs/Subscriber", "rxjs/util/tryCat } 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) { + this.tryCallPredicate(value); } - if (this.skipping === false) { + if (!this.skipping) { destination.next(value); } }; + SkipWhileSubscriber.prototype.tryCallPredicate = function(value) { + try { + var result = this.predicate(value, this.index++); + this.skipping = Boolean(result); + } catch (err) { + this.destination.error(err); + } + }; return SkipWhileSubscriber; - })(Subscriber_1.Subscriber); + }(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) { +System.register("rxjs/operator/startWith", ["rxjs/observable/ArrayObservable", "rxjs/observable/ScalarObservable", "rxjs/observable/EmptyObservable", "rxjs/operator/concat", "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"); + "use strict"; + var ArrayObservable_1 = require("rxjs/observable/ArrayObservable"); var ScalarObservable_1 = require("rxjs/observable/ScalarObservable"); - var empty_1 = require("rxjs/observable/empty"); - var concat_static_1 = require("rxjs/operator/concat-static"); + var EmptyObservable_1 = require("rxjs/observable/EmptyObservable"); + var concat_1 = require("rxjs/operator/concat"); var isScheduler_1 = require("rxjs/util/isScheduler"); function startWith() { var array = []; @@ -5317,15 +6171,15 @@ System.register("rxjs/operator/startWith", ["rxjs/observable/fromArray", "rxjs/o if (isScheduler_1.isScheduler(scheduler)) { array.pop(); } else { - scheduler = void 0; + scheduler = null; } var len = array.length; if (len === 1) { - return concat_static_1.concat(new ScalarObservable_1.ScalarObservable(array[0], scheduler), this); + return concat_1.concatStatic(new ScalarObservable_1.ScalarObservable(array[0], scheduler), this); } else if (len > 1) { - return concat_static_1.concat(new fromArray_1.ArrayObservable(array, scheduler), this); + return concat_1.concatStatic(new ArrayObservable_1.ArrayObservable(array, scheduler), this); } else { - return concat_static_1.concat(new empty_1.EmptyObservable(scheduler), this); + return concat_1.concatStatic(new EmptyObservable_1.EmptyObservable(scheduler), this); } } exports.startWith = startWith; @@ -5337,6 +6191,7 @@ System.register("rxjs/observable/SubscribeOnObservable", ["rxjs/Observable", "rx var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -5387,13 +6242,13 @@ System.register("rxjs/observable/SubscribeOnObservable", ["rxjs/Observable", "rx var delay = this.delayTime; var source = this.source; var scheduler = this.scheduler; - subscriber.add(scheduler.schedule(SubscribeOnObservable.dispatch, delay, { + return scheduler.schedule(SubscribeOnObservable.dispatch, delay, { source: source, subscriber: subscriber - })); + }); }; return SubscribeOnObservable; - })(Observable_1.Observable); + }(Observable_1.Observable)); exports.SubscribeOnObservable = SubscribeOnObservable; global.define = __define; return module.exports; @@ -5403,6 +6258,7 @@ System.register("rxjs/operator/switch", ["rxjs/OuterSubscriber", "rxjs/util/subs var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -5424,7 +6280,7 @@ System.register("rxjs/operator/switch", ["rxjs/OuterSubscriber", "rxjs/util/subs return new SwitchSubscriber(subscriber); }; return SwitchOperator; - })(); + }()); var SwitchSubscriber = (function(_super) { __extends(SwitchSubscriber, _super); function SwitchSubscriber(destination) { @@ -5451,7 +6307,7 @@ System.register("rxjs/operator/switch", ["rxjs/OuterSubscriber", "rxjs/util/subs this.remove(innerSubscription); } }; - SwitchSubscriber.prototype.notifyNext = function(outerValue, innerValue) { + SwitchSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { this.destination.next(innerValue); }; SwitchSubscriber.prototype.notifyError = function(err) { @@ -5464,15 +6320,16 @@ System.register("rxjs/operator/switch", ["rxjs/OuterSubscriber", "rxjs/util/subs } }; return SwitchSubscriber; - })(OuterSubscriber_1.OuterSubscriber); + }(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) { +System.register("rxjs/operator/switchMap", ["rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -5482,8 +6339,6 @@ System.register("rxjs/operator/switchMap", ["rxjs/util/tryCatch", "rxjs/util/err } 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) { @@ -5499,76 +6354,77 @@ System.register("rxjs/operator/switchMap", ["rxjs/util/tryCatch", "rxjs/util/err 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 result; 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)); + try { + result = this.project(value, index); + } catch (error) { + this.destination.error(error); + return ; + } + this._innerSub(result, value, index); + }; + SwitchMapSubscriber.prototype._innerSub = function(result, value, index) { + 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(); + _super.prototype._complete.call(this); } }; + SwitchMapSubscriber.prototype._unsubscribe = function() { + this.innerSubscription = null; + }; 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(); + if (this.isStopped) { + _super.prototype._complete.call(this); } }; - 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); - } + SwitchMapSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { + if (this.resultSelector) { + this._tryNotifyNext(outerValue, innerValue, outerIndex, innerIndex); } else { - destination.next(innerValue); + this.destination.next(innerValue); } }; + SwitchMapSubscriber.prototype._tryNotifyNext = function(outerValue, innerValue, outerIndex, innerIndex) { + var result; + try { + result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex); + } catch (err) { + this.destination.error(err); + return ; + } + this.destination.next(result); + }; return SwitchMapSubscriber; - })(OuterSubscriber_1.OuterSubscriber); + }(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) { +System.register("rxjs/operator/switchMapTo", ["rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -5578,12 +6434,10 @@ System.register("rxjs/operator/switchMapTo", ["rxjs/util/tryCatch", "rxjs/util/e } 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)); + function switchMapTo(observable, resultSelector) { + return this.lift(new SwitchMapToOperator(observable, resultSelector)); } exports.switchMapTo = switchMapTo; var SwitchMapToOperator = (function() { @@ -5595,62 +6449,63 @@ System.register("rxjs/operator/switchMapTo", ["rxjs/util/tryCatch", "rxjs/util/e 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)); + this.add(this.innerSubscription = subscribeToResult_1.subscribeToResult(this, this.inner, value, this.index++)); }; SwitchMapToSubscriber.prototype._complete = function() { var innerSubscription = this.innerSubscription; - this.hasCompleted = true; if (!innerSubscription || innerSubscription.isUnsubscribed) { - this.destination.complete(); + _super.prototype._complete.call(this); } }; + SwitchMapToSubscriber.prototype._unsubscribe = function() { + this.innerSubscription = null; + }; 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(); + if (this.isStopped) { + _super.prototype._complete.call(this); } }; - SwitchMapToSubscriber.prototype.notifyError = function(err) { - this.destination.error(err); - }; - SwitchMapToSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex) { + SwitchMapToSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { 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); - } + this.tryResultSelector(outerValue, innerValue, outerIndex, innerIndex); } else { destination.next(innerValue); } }; + SwitchMapToSubscriber.prototype.tryResultSelector = function(outerValue, innerValue, outerIndex, innerIndex) { + var _a = this, + resultSelector = _a.resultSelector, + destination = _a.destination; + var result; + try { + result = resultSelector(outerValue, innerValue, outerIndex, innerIndex); + } catch (err) { + destination.error(err); + return ; + } + destination.next(result); + }; return SwitchMapToSubscriber; - })(OuterSubscriber_1.OuterSubscriber); + }(OuterSubscriber_1.OuterSubscriber)); global.define = __define; return module.exports; }); @@ -5659,22 +6514,34 @@ System.register("rxjs/util/ArgumentOutOfRangeError", [], true, function(require, var global = System.global, __define = global.define; global.define = undefined; - var ArgumentOutOfRangeError = (function() { + "use strict"; + 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 ArgumentOutOfRangeError = (function(_super) { + __extends(ArgumentOutOfRangeError, _super); function ArgumentOutOfRangeError() { + _super.call(this, 'argument out of range'); this.name = 'ArgumentOutOfRangeError'; - this.message = 'argument out of range'; } return ArgumentOutOfRangeError; - })(); + }(Error)); exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError; global.define = __define; return module.exports; }); -System.register("rxjs/operator/takeUntil", ["rxjs/Subscriber", "rxjs/util/noop"], true, function(require, exports, module) { +System.register("rxjs/operator/takeLast", ["rxjs/Subscriber", "rxjs/util/ArgumentOutOfRangeError", "rxjs/observable/EmptyObservable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -5685,7 +6552,96 @@ System.register("rxjs/operator/takeUntil", ["rxjs/Subscriber", "rxjs/util/noop"] 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 ArgumentOutOfRangeError_1 = require("rxjs/util/ArgumentOutOfRangeError"); + var EmptyObservable_1 = require("rxjs/observable/EmptyObservable"); + function takeLast(total) { + if (total === 0) { + return new EmptyObservable_1.EmptyObservable(); + } else { + return this.lift(new TakeLastOperator(total)); + } + } + exports.takeLast = takeLast; + var TakeLastOperator = (function() { + function TakeLastOperator(total) { + this.total = total; + if (this.total < 0) { + throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError; + } + } + TakeLastOperator.prototype.call = function(subscriber) { + return new TakeLastSubscriber(subscriber, this.total); + }; + return TakeLastOperator; + }()); + var TakeLastSubscriber = (function(_super) { + __extends(TakeLastSubscriber, _super); + function TakeLastSubscriber(destination, total) { + _super.call(this, destination); + this.total = total; + this.count = 0; + this.index = 0; + this.ring = new Array(total); + } + TakeLastSubscriber.prototype._next = function(value) { + var index = this.index; + var ring = this.ring; + var total = this.total; + var count = this.count; + if (total > 1) { + if (count < total) { + this.count = count + 1; + this.index = index + 1; + } else if (index === 0) { + this.index = ++index; + } else if (index < total) { + this.index = index + 1; + } else { + this.index = index = 0; + } + } else if (count < total) { + this.count = total; + } + ring[index] = value; + }; + TakeLastSubscriber.prototype._complete = function() { + var iter = -1; + var _a = this, + ring = _a.ring, + count = _a.count, + total = _a.total, + destination = _a.destination; + var index = (total === 1 || count < total) ? 0 : this.index - 1; + while (++iter < count) { + if (iter + index === total) { + index = total - iter; + } + destination.next(ring[iter + index]); + } + destination.complete(); + }; + return TakeLastSubscriber; + }(Subscriber_1.Subscriber)); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/takeUntil", ["rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + 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 takeUntil(notifier) { return this.lift(new TakeUntilOperator(notifier)); } @@ -5698,47 +6654,29 @@ System.register("rxjs/operator/takeUntil", ["rxjs/Subscriber", "rxjs/util/noop"] 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)); + this.add(subscribeToResult_1.subscribeToResult(this, notifier)); } - TakeUntilSubscriber.prototype._complete = function() { - this.destination.complete(); - this.notificationSubscriber.unsubscribe(); + TakeUntilSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.complete(); }; + TakeUntilSubscriber.prototype.notifyComplete = function() {}; 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); + }(OuterSubscriber_1.OuterSubscriber)); global.define = __define; return module.exports; }); -System.register("rxjs/operator/takeWhile", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { +System.register("rxjs/operator/takeWhile", ["rxjs/Subscriber"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -5749,8 +6687,6 @@ System.register("rxjs/operator/takeWhile", ["rxjs/Subscriber", "rxjs/util/tryCat 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)); } @@ -5763,7 +6699,7 @@ System.register("rxjs/operator/takeWhile", ["rxjs/Subscriber", "rxjs/util/tryCat return new TakeWhileSubscriber(subscriber, this.predicate); }; return TakeWhileOperator; - })(); + }()); var TakeWhileSubscriber = (function(_super) { __extends(TakeWhileSubscriber, _super); function TakeWhileSubscriber(destination, predicate) { @@ -5773,25 +6709,34 @@ System.register("rxjs/operator/takeWhile", ["rxjs/Subscriber", "rxjs/util/tryCat } 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)) { + var result; + try { + result = this.predicate(value, this.index++); + } catch (err) { + destination.error(err); + return ; + } + this.nextOrComplete(value, result); + }; + TakeWhileSubscriber.prototype.nextOrComplete = function(value, predicateResult) { + var destination = this.destination; + if (Boolean(predicateResult)) { destination.next(value); } else { destination.complete(); } }; return TakeWhileSubscriber; - })(Subscriber_1.Subscriber); + }(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) { +System.register("rxjs/operator/throttle", ["rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -5801,11 +6746,8 @@ System.register("rxjs/operator/throttle", ["rxjs/observable/fromPromise", "rxjs/ } 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"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); function throttle(durationSelector) { return this.lift(new ThrottleOperator(durationSelector)); } @@ -5818,63 +6760,49 @@ System.register("rxjs/operator/throttle", ["rxjs/observable/fromPromise", "rxjs/ return new ThrottleSubscriber(subscriber, this.durationSelector); }; return ThrottleOperator; - })(); + }()); var ThrottleSubscriber = (function(_super) { __extends(ThrottleSubscriber, _super); function ThrottleSubscriber(destination, durationSelector) { _super.call(this, destination); + this.destination = 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); + this.tryDurationSelector(value); } }; - ThrottleSubscriber.prototype._error = function(err) { - this.clearThrottle(); - _super.prototype._error.call(this, err); + ThrottleSubscriber.prototype.tryDurationSelector = function(value) { + var duration = null; + try { + duration = this.durationSelector(value); + } catch (err) { + this.destination.error(err); + return ; + } + this.emitAndThrottle(value, duration); }; - ThrottleSubscriber.prototype._complete = function() { - this.clearThrottle(); - _super.prototype._complete.call(this); + ThrottleSubscriber.prototype.emitAndThrottle = function(value, duration) { + this.add(this.throttled = subscribeToResult_1.subscribeToResult(this, duration)); + this.destination.next(value); }; - ThrottleSubscriber.prototype.clearThrottle = function() { + ThrottleSubscriber.prototype._unsubscribe = function() { var throttled = this.throttled; if (throttled) { - throttled.unsubscribe(); this.remove(throttled); this.throttled = null; + throttled.unsubscribe(); } }; - 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); + ThrottleSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this._unsubscribe(); }; - ThrottleDurationSelectorSubscriber.prototype._complete = function() { - this.parent.clearThrottle(); + ThrottleSubscriber.prototype.notifyComplete = function() { + this._unsubscribe(); }; - return ThrottleDurationSelectorSubscriber; - })(Subscriber_1.Subscriber); + return ThrottleSubscriber; + }(OuterSubscriber_1.OuterSubscriber)); global.define = __define; return module.exports; }); @@ -5883,6 +6811,7 @@ System.register("rxjs/operator/throttleTime", ["rxjs/Subscriber", "rxjs/schedule var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -5910,7 +6839,7 @@ System.register("rxjs/operator/throttleTime", ["rxjs/Subscriber", "rxjs/schedule return new ThrottleTimeSubscriber(subscriber, this.delay, this.scheduler); }; return ThrottleTimeOperator; - })(); + }()); var ThrottleTimeSubscriber = (function(_super) { __extends(ThrottleTimeSubscriber, _super); function ThrottleTimeSubscriber(destination, delay, scheduler) { @@ -5933,7 +6862,7 @@ System.register("rxjs/operator/throttleTime", ["rxjs/Subscriber", "rxjs/schedule } }; return ThrottleTimeSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); function dispatchNext(_a) { var subscriber = _a.subscriber; subscriber.clearThrottle(); @@ -5942,10 +6871,11 @@ System.register("rxjs/operator/throttleTime", ["rxjs/Subscriber", "rxjs/schedule return module.exports; }); -System.register("rxjs/operator/timeout", ["rxjs/Subscriber", "rxjs/scheduler/queue", "rxjs/util/isDate"], true, function(require, exports, module) { +System.register("rxjs/operator/timeout", ["rxjs/scheduler/asap", "rxjs/util/isDate", "rxjs/Subscriber"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -5955,18 +6885,18 @@ System.register("rxjs/operator/timeout", ["rxjs/Subscriber", "rxjs/scheduler/que } 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 asap_1 = require("rxjs/scheduler/asap"); var isDate_1 = require("rxjs/util/isDate"); + var Subscriber_1 = require("rxjs/Subscriber"); function timeout(due, errorToSend, scheduler) { if (errorToSend === void 0) { errorToSend = null; } if (scheduler === void 0) { - scheduler = queue_1.queue; + scheduler = asap_1.asap; } var absoluteTimeout = isDate_1.isDate(due); - var waitFor = absoluteTimeout ? (+due - scheduler.now()) : due; + var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due); return this.lift(new TimeoutOperator(waitFor, absoluteTimeout, errorToSend, scheduler)); } exports.timeout = timeout; @@ -5981,7 +6911,7 @@ System.register("rxjs/operator/timeout", ["rxjs/Subscriber", "rxjs/scheduler/que 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) { @@ -6043,15 +6973,16 @@ System.register("rxjs/operator/timeout", ["rxjs/Subscriber", "rxjs/scheduler/que this.error(this.errorToSend || new Error('timeout')); }; return TimeoutSubscriber; - })(Subscriber_1.Subscriber); + }(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) { +System.register("rxjs/operator/timeoutWith", ["rxjs/scheduler/asap", "rxjs/util/isDate", "rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -6061,16 +6992,16 @@ System.register("rxjs/operator/timeoutWith", ["rxjs/scheduler/queue", "rxjs/util } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; - var queue_1 = require("rxjs/scheduler/queue"); + var asap_1 = require("rxjs/scheduler/asap"); 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; + scheduler = asap_1.asap; } var absoluteTimeout = isDate_1.isDate(due); - var waitFor = absoluteTimeout ? (+due - scheduler.now()) : due; + var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due); return this.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler)); } exports.timeoutWith = timeoutWith; @@ -6085,11 +7016,11 @@ System.register("rxjs/operator/timeoutWith", ["rxjs/scheduler/queue", "rxjs/util 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); + _super.call(this); this.destination = destination; this.absoluteTimeout = absoluteTimeout; this.waitFor = waitFor; @@ -6155,7 +7086,7 @@ System.register("rxjs/operator/timeoutWith", ["rxjs/scheduler/queue", "rxjs/util } }; return TimeoutWithSubscriber; - })(OuterSubscriber_1.OuterSubscriber); + }(OuterSubscriber_1.OuterSubscriber)); global.define = __define; return module.exports; }); @@ -6164,6 +7095,7 @@ System.register("rxjs/operator/toArray", ["rxjs/Subscriber"], true, function(req var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -6184,7 +7116,7 @@ System.register("rxjs/operator/toArray", ["rxjs/Subscriber"], true, function(req return new ToArraySubscriber(subscriber); }; return ToArrayOperator; - })(); + }()); var ToArraySubscriber = (function(_super) { __extends(ToArraySubscriber, _super); function ToArraySubscriber(destination) { @@ -6199,7 +7131,7 @@ System.register("rxjs/operator/toArray", ["rxjs/Subscriber"], true, function(req this.destination.complete(); }; return ToArraySubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); global.define = __define; return module.exports; }); @@ -6208,6 +7140,7 @@ System.register("rxjs/operator/toPromise", ["rxjs/util/root"], true, function(re var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var root_1 = require("rxjs/util/root"); function toPromise(PromiseCtor) { var _this = this; @@ -6237,10 +7170,11 @@ System.register("rxjs/operator/toPromise", ["rxjs/util/root"], true, function(re return module.exports; }); -System.register("rxjs/operator/window", ["rxjs/Subscriber", "rxjs/Subject"], true, function(require, exports, module) { +System.register("rxjs/operator/window", ["rxjs/Subject", "rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -6250,8 +7184,9 @@ System.register("rxjs/operator/window", ["rxjs/Subscriber", "rxjs/Subject"], tru } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; - var Subscriber_1 = require("rxjs/Subscriber"); var Subject_1 = require("rxjs/Subject"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); function window(closingNotifier) { return this.lift(new WindowOperator(closingNotifier)); } @@ -6264,16 +7199,25 @@ System.register("rxjs/operator/window", ["rxjs/Subscriber", "rxjs/Subject"], tru 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.add(subscribeToResult_1.subscribeToResult(this, closingNotifier)); this.openWindow(); } + WindowSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.openWindow(); + }; + WindowSubscriber.prototype.notifyError = function(error, innerSub) { + this._error(error); + }; + WindowSubscriber.prototype.notifyComplete = function(innerSub) { + this._complete(); + }; WindowSubscriber.prototype._next = function(value) { this.window.next(value); }; @@ -6296,24 +7240,7 @@ System.register("rxjs/operator/window", ["rxjs/Subscriber", "rxjs/Subject"], tru 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); + }(OuterSubscriber_1.OuterSubscriber)); global.define = __define; return module.exports; }); @@ -6322,6 +7249,7 @@ System.register("rxjs/operator/windowCount", ["rxjs/Subscriber", "rxjs/Subject"] var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -6349,7 +7277,7 @@ System.register("rxjs/operator/windowCount", ["rxjs/Subscriber", "rxjs/Subject"] return new WindowCountSubscriber(subscriber, this.windowSize, this.startWindowEvery); }; return WindowCountOperator; - })(); + }()); var WindowCountSubscriber = (function(_super) { __extends(WindowCountSubscriber, _super); function WindowCountSubscriber(destination, windowSize, startWindowEvery) { @@ -6398,7 +7326,7 @@ System.register("rxjs/operator/windowCount", ["rxjs/Subscriber", "rxjs/Subject"] this.destination.complete(); }; return WindowCountSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); global.define = __define; return module.exports; }); @@ -6407,6 +7335,7 @@ System.register("rxjs/operator/windowTime", ["rxjs/Subscriber", "rxjs/Subject", var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -6439,7 +7368,7 @@ System.register("rxjs/operator/windowTime", ["rxjs/Subscriber", "rxjs/Subject", 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) { @@ -6478,7 +7407,10 @@ System.register("rxjs/operator/windowTime", ["rxjs/Subscriber", "rxjs/Subject", var windows = this.windows; var len = windows.length; for (var i = 0; i < len; i++) { - windows[i].next(value); + var window_3 = windows[i]; + if (!window_3.isUnsubscribed) { + window_3.next(value); + } } }; WindowTimeSubscriber.prototype._error = function(err) { @@ -6491,7 +7423,10 @@ System.register("rxjs/operator/windowTime", ["rxjs/Subscriber", "rxjs/Subject", WindowTimeSubscriber.prototype._complete = function() { var windows = this.windows; while (windows.length > 0) { - windows.shift().complete(); + var window_4 = windows.shift(); + if (!window_4.isUnsubscribed) { + window_4.complete(); + } } this.destination.complete(); }; @@ -6509,7 +7444,7 @@ System.register("rxjs/operator/windowTime", ["rxjs/Subscriber", "rxjs/Subject", windows.splice(windows.indexOf(window), 1); }; return WindowTimeSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); function dispatchWindowTimeSpanOnly(state) { var subscriber = state.subscriber, windowTimeSpan = state.windowTimeSpan, @@ -6553,10 +7488,11 @@ System.register("rxjs/operator/windowTime", ["rxjs/Subscriber", "rxjs/Subject", 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) { +System.register("rxjs/operator/windowToggle", ["rxjs/Subject", "rxjs/Subscription", "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; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -6566,11 +7502,12 @@ System.register("rxjs/operator/windowToggle", ["rxjs/Subscriber", "rxjs/Subject" } 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"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); function windowToggle(openings, closingSelector) { return this.lift(new WindowToggleOperator(openings, closingSelector)); } @@ -6584,116 +7521,117 @@ System.register("rxjs/operator/windowToggle", ["rxjs/Subscriber", "rxjs/Subject" 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))); + this.add(this.openSubscription = subscribeToResult_1.subscribeToResult(this, openings, openings)); } 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); + if (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.contexts = null; + if (contexts) { + var len = contexts.length; + var index = -1; + while (++index < len) { + var context = contexts[index]; + context.window.error(err); + context.subscription.unsubscribe(); + } } - this.destination.error(err); + _super.prototype._error.call(this, err); }; WindowToggleSubscriber.prototype._complete = function() { var contexts = this.contexts; - while (contexts.length > 0) { - var context = contexts.shift(); - context.window.complete(); - context.subscription.unsubscribe(); + this.contexts = null; + if (contexts) { + var len = contexts.length; + var index = -1; + while (++index < len) { + var context = contexts[index]; + context.window.complete(); + context.subscription.unsubscribe(); + } } - this.destination.complete(); + _super.prototype._complete.call(this); }; - 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); + WindowToggleSubscriber.prototype._unsubscribe = function() { + var contexts = this.contexts; + this.contexts = null; + if (contexts) { + var len = contexts.length; + var index = -1; + while (++index < len) { + var context = contexts[index]; + context.window.unsubscribe(); + context.subscription.unsubscribe(); + } + } + }; + WindowToggleSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { + if (outerValue === this.openings) { + var closingSelector = this.closingSelector; + var closingNotifier = tryCatch_1.tryCatch(closingSelector)(innerValue); + if (closingNotifier === errorObject_1.errorObject) { + return this.error(errorObject_1.errorObject.e); + } else { + 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 innerSubscription = subscribeToResult_1.subscribeToResult(this, closingNotifier, context); + innerSubscription.context = context; + subscription.add(innerSubscription); + this.destination.next(window_1); + } } 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); + this.closeWindow(this.contexts.indexOf(outerValue)); + } + }; + WindowToggleSubscriber.prototype.notifyError = function(err) { + this.error(err); + }; + WindowToggleSubscriber.prototype.notifyComplete = function(inner) { + if (inner !== this.openSubscription) { + this.closeWindow(this.contexts.indexOf(inner.context)); } }; - WindowToggleSubscriber.prototype.closeWindow = function(context) { + WindowToggleSubscriber.prototype.closeWindow = function(index) { + var contexts = this.contexts; + var context = contexts[index]; var window = context.window, subscription = context.subscription; - var contexts = this.contexts; - var destination = this.destination; - contexts.splice(contexts.indexOf(context), 1); + contexts.splice(index, 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); + }(OuterSubscriber_1.OuterSubscriber)); 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) { +System.register("rxjs/operator/windowWhen", ["rxjs/Subject", "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; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -6703,11 +7641,11 @@ System.register("rxjs/operator/windowWhen", ["rxjs/Subscriber", "rxjs/Subject", } 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"); + var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); + var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); function windowWhen(closingSelector) { return this.lift(new WindowOperator(closingSelector)); } @@ -6720,7 +7658,7 @@ System.register("rxjs/operator/windowWhen", ["rxjs/Subscriber", "rxjs/Subject", return new WindowSubscriber(subscriber, this.closingSelector); }; return WindowOperator; - })(); + }()); var WindowSubscriber = (function(_super) { __extends(WindowSubscriber, _super); function WindowSubscriber(destination, closingSelector) { @@ -6729,34 +7667,40 @@ System.register("rxjs/operator/windowWhen", ["rxjs/Subscriber", "rxjs/Subject", this.closingSelector = closingSelector; this.openWindow(); } + WindowSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.openWindow(innerSub); + }; + WindowSubscriber.prototype.notifyError = function(error, innerSub) { + this._error(error); + }; + WindowSubscriber.prototype.notifyComplete = function(innerSub) { + this.openWindow(innerSub); + }; WindowSubscriber.prototype._next = function(value) { this.window.next(value); }; WindowSubscriber.prototype._error = function(err) { this.window.error(err); this.destination.error(err); - this._unsubscribeClosingNotification(); + 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(); + this.unsubscribeClosingNotification(); }; - WindowSubscriber.prototype._unsubscribeClosingNotification = function() { - var closingNotification = this.closingNotification; - if (closingNotification) { - closingNotification.unsubscribe(); + WindowSubscriber.prototype.unsubscribeClosingNotification = function() { + if (this.closingNotification) { + this.closingNotification.unsubscribe(); } }; - WindowSubscriber.prototype.openWindow = function() { - var prevClosingNotification = this.closingNotification; - if (prevClosingNotification) { - this.remove(prevClosingNotification); - prevClosingNotification.unsubscribe(); + WindowSubscriber.prototype.openWindow = function(innerSub) { + if (innerSub === void 0) { + innerSub = null; + } + if (innerSub) { + this.remove(innerSub); + innerSub.unsubscribe(); } var prevWindow = this.window; if (prevWindow) { @@ -6766,43 +7710,25 @@ System.register("rxjs/operator/windowWhen", ["rxjs/Subscriber", "rxjs/Subject", this.destination.next(window); var closingNotifier = tryCatch_1.tryCatch(this.closingSelector)(); if (closingNotifier === errorObject_1.errorObject) { - var err = closingNotifier.e; + var err = errorObject_1.errorObject.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(this.closingNotification = subscribeToResult_1.subscribeToResult(this, closingNotifier)); 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); + }(OuterSubscriber_1.OuterSubscriber)); 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) { +System.register("rxjs/operator/withLatestFrom", ["rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -6812,8 +7738,6 @@ System.register("rxjs/operator/withLatestFrom", ["rxjs/util/tryCatch", "rxjs/uti } 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() { @@ -6838,7 +7762,7 @@ System.register("rxjs/operator/withLatestFrom", ["rxjs/util/tryCatch", "rxjs/uti return new WithLatestFromSubscriber(subscriber, this.observables, this.project); }; return WithLatestFromOperator; - })(); + }()); var WithLatestFromSubscriber = (function(_super) { __extends(WithLatestFromSubscriber, _super); function WithLatestFromSubscriber(destination, observables, project) { @@ -6856,11 +7780,11 @@ System.register("rxjs/operator/withLatestFrom", ["rxjs/util/tryCatch", "rxjs/uti this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i)); } } - WithLatestFromSubscriber.prototype.notifyNext = function(observable, value, observableIndex, index) { - this.values[observableIndex] = value; + WithLatestFromSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.values[outerIndex] = innerValue; var toRespond = this.toRespond; if (toRespond.length > 0) { - var found = toRespond.indexOf(observableIndex); + var found = toRespond.indexOf(outerIndex); if (found !== -1) { toRespond.splice(found, 1); } @@ -6869,124 +7793,52 @@ System.register("rxjs/operator/withLatestFrom", ["rxjs/util/tryCatch", "rxjs/uti 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); - } + var args = [value].concat(this.values); + if (this.project) { + this._tryProject(args); } else { - destination.next(args); + this.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; + WithLatestFromSubscriber.prototype._tryProject = function(args) { + var result; + try { + result = this.project.apply(this, args); + } catch (err) { + this.destination.error(err); + return ; + } + this.destination.next(result); + }; + return WithLatestFromSubscriber; + }(OuterSubscriber_1.OuterSubscriber)); global.define = __define; return module.exports; }); -System.register("rxjs/operator/zipAll", ["rxjs/operator/zip-support"], true, function(require, exports, module) { +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 zip_support_1 = require("rxjs/operator/zip-support"); - function zipAll(project) { - return this.lift(new zip_support_1.ZipOperator(project)); - } - exports.zipAll = zipAll; + "use strict"; + 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/util/SymbolShim", ["rxjs/util/root"], true, function(require, exports, module) { +System.register("rxjs/operator/zipAll", ["rxjs/operator/zip"], 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'; - } - } + "use strict"; + var zip_1 = require("rxjs/operator/zip"); + function zipAll(project) { + return this.lift(new zip_1.ZipOperator(project)); } - exports.ensureObservable = ensureObservable; - exports.SymbolShim = polyfillSymbol(root_1.root); + exports.zipAll = zipAll; global.define = __define; return module.exports; }); @@ -6995,6 +7847,7 @@ System.register("rxjs/util/tryCatch", ["rxjs/util/errorObject"], true, function( var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var errorObject_1 = require("rxjs/util/errorObject"); var tryCatchTarget; function tryCatcher() { @@ -7015,14 +7868,111 @@ System.register("rxjs/util/tryCatch", ["rxjs/util/errorObject"], true, function( return module.exports; }); -System.register("rxjs/util/subscribeToResult", ["rxjs/Observable", "rxjs/util/SymbolShim", "rxjs/InnerSubscriber"], true, function(require, exports, module) { +System.register("rxjs/observable/ArrayObservable", ["rxjs/Observable", "rxjs/observable/ScalarObservable", "rxjs/observable/EmptyObservable", "rxjs/util/isScheduler"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + 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 EmptyObservable_1 = require("rxjs/observable/EmptyObservable"); + 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 = null; + } + 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 EmptyObservable_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) { + return 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/util/subscribeToResult", ["rxjs/util/root", "rxjs/util/isArray", "rxjs/util/isPromise", "rxjs/Observable", "rxjs/util/SymbolShim", "rxjs/InnerSubscriber"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; + var root_1 = require("rxjs/util/root"); + var isArray_1 = require("rxjs/util/isArray"); + var isPromise_1 = require("rxjs/util/isPromise"); 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) { @@ -7037,7 +7987,7 @@ System.register("rxjs/util/subscribeToResult", ["rxjs/Observable", "rxjs/util/Sy return result.subscribe(destination); } } - if (isArray(result)) { + if (isArray_1.isArray(result)) { for (var i = 0, len = result.length; i < len && !destination.isUnsubscribed; i++) { destination.next(result[i]); @@ -7045,16 +7995,16 @@ System.register("rxjs/util/subscribeToResult", ["rxjs/Observable", "rxjs/util/Sy if (!destination.isUnsubscribed) { destination.complete(); } - } else if (typeof result.then === 'function') { - result.then(function(x) { + } else if (isPromise_1.isPromise(result)) { + result.then(function(value) { if (!destination.isUnsubscribed) { - destination.next(x); + destination.next(value); destination.complete(); } }, function(err) { return destination.error(err); }).then(null, function(err) { - setTimeout(function() { + root_1.root.setTimeout(function() { throw err; }); }); @@ -7087,66 +8037,68 @@ System.register("rxjs/util/subscribeToResult", ["rxjs/Observable", "rxjs/util/Sy return module.exports; }); -System.register("rxjs/scheduler/QueueScheduler", ["rxjs/scheduler/QueueAction", "rxjs/scheduler/FutureAction"], true, function(require, exports, module) { +System.register("rxjs/operator/concat", ["rxjs/util/isScheduler", "rxjs/observable/ArrayObservable", "rxjs/operator/mergeAll"], 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; + "use strict"; + var isScheduler_1 = require("rxjs/util/isScheduler"); + var ArrayObservable_1 = require("rxjs/observable/ArrayObservable"); + var mergeAll_1 = require("rxjs/operator/mergeAll"); + function concat() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; } - 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; + return concatStatic.apply(void 0, [this].concat(observables)); + } + exports.concat = concat; + function concatStatic() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i - 0] = arguments[_i]; + } + var scheduler = null; + var args = observables; + if (isScheduler_1.isScheduler(args[observables.length - 1])) { + scheduler = args.pop(); + } + return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new mergeAll_1.MergeAllOperator(1)); + } + exports.concatStatic = concatStatic; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/observable/merge", ["rxjs/Observable", "rxjs/operator/merge"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + var Observable_1 = require("rxjs/Observable"); + var merge_1 = require("rxjs/operator/merge"); + Observable_1.Observable.merge = merge_1.mergeStatic; global.define = __define; return module.exports; }); -System.register("rxjs/add/operator/merge-static", ["rxjs/Observable", "rxjs/operator/merge-static"], true, function(require, exports, module) { +System.register("rxjs/add/observable/race", ["rxjs/Observable", "rxjs/operator/race"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var merge_static_1 = require("rxjs/operator/merge-static"); - Observable_1.Observable.merge = merge_static_1.merge; + var race_1 = require("rxjs/operator/race"); + Observable_1.Observable.race = race_1.raceStatic; 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) { +System.register("rxjs/observable/BoundCallbackObservable", ["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; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -7218,17 +8170,17 @@ System.register("rxjs/observable/bindCallback", ["rxjs/Observable", "rxjs/util/t } return subject.subscribe(subscriber); } else { - subscriber.add(scheduler.schedule(dispatch, 0, { + return scheduler.schedule(dispatch, 0, { source: this, subscriber: subscriber - })); - return subscriber; + }); } }; return BoundCallbackObservable; - })(Observable_1.Observable); + }(Observable_1.Observable)); exports.BoundCallbackObservable = BoundCallbackObservable; function dispatch(state) { + var self = this; var source = state.source, subscriber = state.subscriber; var callbackFunc = source.callbackFunc, @@ -7248,19 +8200,19 @@ System.register("rxjs/observable/bindCallback", ["rxjs/Observable", "rxjs/util/t if (selector) { var result_2 = tryCatch_1.tryCatch(selector).apply(this, innerArgs); if (result_2 === errorObject_1.errorObject) { - subject.add(scheduler.schedule(dispatchError, 0, { + self.add(scheduler.schedule(dispatchError, 0, { err: errorObject_1.errorObject.e, subject: subject })); } else { - subject.add(scheduler.schedule(dispatchNext, 0, { + self.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, { + self.add(scheduler.schedule(dispatchNext, 0, { value: value, subject: subject })); @@ -7272,7 +8224,7 @@ System.register("rxjs/observable/bindCallback", ["rxjs/Observable", "rxjs/util/t subject.error(errorObject_1.errorObject.e); } } - this.add(subject.subscribe(subscriber)); + self.add(subject.subscribe(subscriber)); } function dispatchNext(_a) { var value = _a.value, @@ -7289,21 +8241,35 @@ System.register("rxjs/observable/bindCallback", ["rxjs/Observable", "rxjs/util/t return module.exports; }); -System.register("rxjs/add/observable/defer", ["rxjs/Observable", "rxjs/observable/defer"], true, function(require, exports, module) { +System.register("rxjs/add/observable/bindNodeCallback", ["rxjs/Observable", "rxjs/observable/BoundNodeCallbackObservable"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + var Observable_1 = require("rxjs/Observable"); + var BoundNodeCallbackObservable_1 = require("rxjs/observable/BoundNodeCallbackObservable"); + Observable_1.Observable.bindNodeCallback = BoundNodeCallbackObservable_1.BoundNodeCallbackObservable.create; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/observable/defer", ["rxjs/Observable", "rxjs/observable/DeferObservable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var defer_1 = require("rxjs/observable/defer"); - Observable_1.Observable.defer = defer_1.DeferObservable.create; + var DeferObservable_1 = require("rxjs/observable/DeferObservable"); + Observable_1.Observable.defer = DeferObservable_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) { +System.register("rxjs/observable/ForkJoinObservable", ["rxjs/Observable", "rxjs/Subscriber", "rxjs/observable/PromiseObservable", "rxjs/observable/EmptyObservable", "rxjs/util/isPromise", "rxjs/util/isArray"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -7315,8 +8281,8 @@ System.register("rxjs/observable/forkJoin", ["rxjs/Observable", "rxjs/Subscriber }; 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 PromiseObservable_1 = require("rxjs/observable/PromiseObservable"); + var EmptyObservable_1 = require("rxjs/observable/EmptyObservable"); var isPromise_1 = require("rxjs/util/isPromise"); var isArray_1 = require("rxjs/util/isArray"); var ForkJoinObservable = (function(_super) { @@ -7332,7 +8298,7 @@ System.register("rxjs/observable/forkJoin", ["rxjs/Observable", "rxjs/Subscriber sources[_i - 0] = arguments[_i]; } if (sources === null || arguments.length === 0) { - return new empty_1.EmptyObservable(); + return new EmptyObservable_1.EmptyObservable(); } var resultSelector = null; if (typeof sources[sources.length - 1] === 'function') { @@ -7341,6 +8307,9 @@ System.register("rxjs/observable/forkJoin", ["rxjs/Observable", "rxjs/Subscriber if (sources.length === 1 && isArray_1.isArray(sources[0])) { sources = sources[0]; } + if (sources.length === 0) { + return new EmptyObservable_1.EmptyObservable(); + } return new ForkJoinObservable(sources, resultSelector); }; ForkJoinObservable.prototype._subscribe = function(subscriber) { @@ -7355,13 +8324,13 @@ System.register("rxjs/observable/forkJoin", ["rxjs/Observable", "rxjs/Subscriber for (var i = 0; i < len; i++) { var source = sources[i]; if (isPromise_1.isPromise(source)) { - source = new fromPromise_1.PromiseObservable(source); + source = new PromiseObservable_1.PromiseObservable(source); } source.subscribe(new AllSubscriber(subscriber, i, context)); } }; return ForkJoinObservable; - })(Observable_1.Observable); + }(Observable_1.Observable)); exports.ForkJoinObservable = ForkJoinObservable; var AllSubscriber = (function(_super) { __extends(AllSubscriber, _super); @@ -7393,7 +8362,7 @@ System.register("rxjs/observable/forkJoin", ["rxjs/Observable", "rxjs/Subscriber destination.complete(); }; return AllSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); function hasValue(x) { return x !== null; } @@ -7408,10 +8377,11 @@ System.register("rxjs/observable/forkJoin", ["rxjs/Observable", "rxjs/Subscriber return module.exports; }); -System.register("rxjs/operator/observeOn-support", ["rxjs/Subscriber", "rxjs/Notification"], true, function(require, exports, module) { +System.register("rxjs/operator/observeOn", ["rxjs/Subscriber", "rxjs/Notification"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -7423,10 +8393,17 @@ System.register("rxjs/operator/observeOn-support", ["rxjs/Subscriber", "rxjs/Not }; 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; + function observeOn(scheduler, delay) { + if (delay === void 0) { + delay = 0; + } + return this.lift(new ObserveOnOperator(scheduler, delay)); + } + exports.observeOn = observeOn; + var ObserveOnOperator = (function() { + function ObserveOnOperator(scheduler, delay) { + if (delay === void 0) { + delay = 0; } this.scheduler = scheduler; this.delay = delay; @@ -7435,7 +8412,7 @@ System.register("rxjs/operator/observeOn-support", ["rxjs/Subscriber", "rxjs/Not return new ObserveOnSubscriber(subscriber, this.scheduler, this.delay); }; return ObserveOnOperator; - })(); + }()); exports.ObserveOnOperator = ObserveOnOperator; var ObserveOnSubscriber = (function(_super) { __extends(ObserveOnSubscriber, _super); @@ -7465,7 +8442,7 @@ System.register("rxjs/operator/observeOn-support", ["rxjs/Subscriber", "rxjs/Not this.scheduleMessage(Notification_1.Notification.createComplete()); }; return ObserveOnSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); exports.ObserveOnSubscriber = ObserveOnSubscriber; var ObserveOnMessage = (function() { function ObserveOnMessage(notification, destination) { @@ -7473,37 +8450,40 @@ System.register("rxjs/operator/observeOn-support", ["rxjs/Subscriber", "rxjs/Not 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) { +System.register("rxjs/add/observable/fromEvent", ["rxjs/Observable", "rxjs/observable/FromEventObservable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var fromEvent_1 = require("rxjs/observable/fromEvent"); - Observable_1.Observable.fromEvent = fromEvent_1.FromEventObservable.create; + var FromEventObservable_1 = require("rxjs/observable/FromEventObservable"); + Observable_1.Observable.fromEvent = FromEventObservable_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) { +System.register("rxjs/add/observable/fromEventPattern", ["rxjs/Observable", "rxjs/observable/FromEventPatternObservable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var fromEventPattern_1 = require("rxjs/observable/fromEventPattern"); - Observable_1.Observable.fromEventPattern = fromEventPattern_1.FromEventPatternObservable.create; + var FromEventPatternObservable_1 = require("rxjs/observable/FromEventPatternObservable"); + Observable_1.Observable.fromEventPattern = FromEventPatternObservable_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) { +System.register("rxjs/scheduler/AsapAction", ["rxjs/util/Immediate", "rxjs/scheduler/FutureAction"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -7514,76 +8494,160 @@ System.register("rxjs/scheduler/AsapAction", ["rxjs/util/Immediate", "rxjs/sched 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 FutureAction_1 = require("rxjs/scheduler/FutureAction"); 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; + AsapAction.prototype._schedule = function(state, delay) { + if (delay === void 0) { + delay = 0; + } + if (delay > 0) { + return _super.prototype._schedule.call(this, state, delay); } + this.delay = delay; 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(); + if (!scheduler.scheduledId) { + scheduler.scheduledId = Immediate_1.Immediate.setImmediate(function() { + scheduler.scheduledId = null; + scheduler.flush(); }); } return this; }; - AsapAction.prototype.unsubscribe = function() { - var id = this.id; + AsapAction.prototype._unsubscribe = function() { var scheduler = this.scheduler; - _super.prototype.unsubscribe.call(this); - if (scheduler.actions.length === 0) { + var scheduledId = scheduler.scheduledId, + actions = scheduler.actions; + _super.prototype._unsubscribe.call(this); + if (actions.length === 0) { scheduler.active = false; - scheduler.scheduled = false; - } - if (id) { - this.id = null; - Immediate_1.Immediate.clearImmediate(id); + if (scheduledId != null) { + scheduler.scheduledId = null; + Immediate_1.Immediate.clearImmediate(scheduledId); + } } }; return AsapAction; - })(QueueAction_1.QueueAction); + }(FutureAction_1.FutureAction)); 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) { +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; + "use strict"; + var QueueAction_1 = require("rxjs/scheduler/QueueAction"); + var FutureAction_1 = require("rxjs/scheduler/FutureAction"); + var QueueScheduler = (function() { + function QueueScheduler() { + this.active = false; + this.actions = []; + this.scheduledId = null; + } + QueueScheduler.prototype.now = function() { + return Date.now(); + }; + QueueScheduler.prototype.flush = function() { + if (this.active || this.scheduledId) { + 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/observable/NeverObservable", ["rxjs/Observable", "rxjs/util/noop"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + 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 NeverObservable = (function(_super) { + __extends(NeverObservable, _super); + function NeverObservable() { + _super.call(this); + } + NeverObservable.create = function() { + return new NeverObservable(); + }; + NeverObservable.prototype._subscribe = function(subscriber) { + noop_1.noop(); + }; + return NeverObservable; + }(Observable_1.Observable)); + exports.NeverObservable = NeverObservable; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/observable/range", ["rxjs/Observable", "rxjs/observable/RangeObservable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var never_1 = require("rxjs/observable/never"); - Observable_1.Observable.never = never_1.InfiniteObservable.create; + var RangeObservable_1 = require("rxjs/observable/RangeObservable"); + Observable_1.Observable.range = RangeObservable_1.RangeObservable.create; global.define = __define; return module.exports; }); -System.register("rxjs/add/observable/range", ["rxjs/Observable", "rxjs/observable/range"], true, function(require, exports, module) { +System.register("rxjs/add/observable/throw", ["rxjs/Observable", "rxjs/observable/ErrorObservable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var range_1 = require("rxjs/observable/range"); - Observable_1.Observable.range = range_1.RangeObservable.create; + var ErrorObservable_1 = require("rxjs/observable/ErrorObservable"); + Observable_1.Observable.throw = ErrorObservable_1.ErrorObservable.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) { +System.register("rxjs/observable/TimerObservable", ["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; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -7605,11 +8669,10 @@ System.register("rxjs/observable/timer", ["rxjs/util/isNumeric", "rxjs/Observabl dueTime = 0; } _super.call(this); - this.period = period; - this.scheduler = scheduler; + this.period = -1; this.dueTime = 0; if (isNumeric_1.isNumeric(period)) { - this._period = Number(period) < 1 && 1 || Number(period); + this.period = Number(period) < 1 && 1 || Number(period); } else if (isScheduler_1.isScheduler(period)) { scheduler = period; } @@ -7617,8 +8680,7 @@ System.register("rxjs/observable/timer", ["rxjs/util/isNumeric", "rxjs/Observabl scheduler = asap_1.asap; } this.scheduler = scheduler; - var absoluteDueTime = isDate_1.isDate(dueTime); - this.dueTime = absoluteDueTime ? (+dueTime - this.scheduler.now()) : dueTime; + this.dueTime = isDate_1.isDate(dueTime) ? (+dueTime - this.scheduler.now()) : dueTime; } TimerObservable.create = function(dueTime, period, scheduler) { if (dueTime === void 0) { @@ -7632,59 +8694,41 @@ System.register("rxjs/observable/timer", ["rxjs/util/isNumeric", "rxjs/Observabl subscriber = state.subscriber; var action = this; subscriber.next(index); - if (typeof period === 'undefined') { - subscriber.complete(); - return ; - } else if (subscriber.isUnsubscribed) { + if (subscriber.isUnsubscribed) { return ; + } else if (period === -1) { + return subscriber.complete(); } - 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); - } + 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, { + var _a = this, + period = _a.period, + dueTime = _a.dueTime, + scheduler = _a.scheduler; + return scheduler.schedule(TimerObservable.dispatch, dueTime, { index: index, period: period, subscriber: subscriber - })); + }); }; return TimerObservable; - })(Observable_1.Observable); + }(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) { +System.register("rxjs/add/observable/zip", ["rxjs/Observable", "rxjs/operator/zip"], 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; + "use strict"; + var Observable_1 = require("rxjs/Observable"); + var zip_1 = require("rxjs/operator/zip"); + Observable_1.Observable.zip = zip_1.zipStatic; global.define = __define; return module.exports; }); @@ -7693,6 +8737,7 @@ System.register("rxjs/add/operator/buffer", ["rxjs/Observable", "rxjs/operator/b var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var buffer_1 = require("rxjs/operator/buffer"); Observable_1.Observable.prototype.buffer = buffer_1.buffer; @@ -7704,6 +8749,7 @@ System.register("rxjs/add/operator/bufferCount", ["rxjs/Observable", "rxjs/opera var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var bufferCount_1 = require("rxjs/operator/bufferCount"); Observable_1.Observable.prototype.bufferCount = bufferCount_1.bufferCount; @@ -7715,6 +8761,7 @@ System.register("rxjs/add/operator/bufferTime", ["rxjs/Observable", "rxjs/operat var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var bufferTime_1 = require("rxjs/operator/bufferTime"); Observable_1.Observable.prototype.bufferTime = bufferTime_1.bufferTime; @@ -7726,6 +8773,7 @@ System.register("rxjs/add/operator/bufferToggle", ["rxjs/Observable", "rxjs/oper var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var bufferToggle_1 = require("rxjs/operator/bufferToggle"); Observable_1.Observable.prototype.bufferToggle = bufferToggle_1.bufferToggle; @@ -7737,6 +8785,7 @@ System.register("rxjs/add/operator/bufferWhen", ["rxjs/Observable", "rxjs/operat var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var bufferWhen_1 = require("rxjs/operator/bufferWhen"); Observable_1.Observable.prototype.bufferWhen = bufferWhen_1.bufferWhen; @@ -7744,46 +8793,136 @@ System.register("rxjs/add/operator/bufferWhen", ["rxjs/Observable", "rxjs/operat return module.exports; }); -System.register("rxjs/add/operator/catch", ["rxjs/Observable", "rxjs/operator/catch"], true, function(require, exports, module) { +System.register("rxjs/subject/ReplaySubject", ["rxjs/Subject", "rxjs/scheduler/queue", "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 catch_1 = require("rxjs/operator/catch"); - Observable_1.Observable.prototype.catch = catch_1._catch; + "use strict"; + 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 observeOn_1 = require("rxjs/operator/observeOn"); + 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.scheduler = scheduler; + this.bufferSize = bufferSize < 1 ? 1 : bufferSize; + this._windowTime = windowTime < 1 ? 1 : windowTime; + } + 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 scheduler = this.scheduler; + if (scheduler) { + subscriber.add(subscriber = new observeOn_1.ObserveOnSubscriber(subscriber, scheduler)); + } + var index = -1; + var len = events.length; + while (++index < len && !subscriber.isUnsubscribed) { + 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/add/operator/combineAll", ["rxjs/Observable", "rxjs/operator/combineAll"], true, function(require, exports, module) { +System.register("rxjs/operator/multicast", ["rxjs/observable/ConnectableObservable"], 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; + "use strict"; + 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/combineLatest", ["rxjs/Observable", "rxjs/operator/combineLatest"], true, function(require, exports, module) { +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; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var combineLatest_1 = require("rxjs/operator/combineLatest"); - Observable_1.Observable.prototype.combineLatest = combineLatest_1.combineLatest; + 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/concat", ["rxjs/Observable", "rxjs/operator/concat"], true, function(require, exports, module) { +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; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var concat_1 = require("rxjs/operator/concat"); - Observable_1.Observable.prototype.concat = concat_1.concat; + var combineAll_1 = require("rxjs/operator/combineAll"); + Observable_1.Observable.prototype.combineAll = combineAll_1.combineAll; global.define = __define; return module.exports; }); @@ -7792,6 +8931,7 @@ System.register("rxjs/add/operator/concatAll", ["rxjs/Observable", "rxjs/operato var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var concatAll_1 = require("rxjs/operator/concatAll"); Observable_1.Observable.prototype.concatAll = concatAll_1.concatAll; @@ -7799,26 +8939,28 @@ System.register("rxjs/add/operator/concatAll", ["rxjs/Observable", "rxjs/operato return module.exports; }); -System.register("rxjs/operator/concatMap", ["rxjs/operator/mergeMap-support"], true, function(require, exports, module) { +System.register("rxjs/operator/concatMap", ["rxjs/operator/mergeMap"], 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)); + "use strict"; + var mergeMap_1 = require("rxjs/operator/mergeMap"); + function concatMap(project, resultSelector) { + return this.lift(new mergeMap_1.MergeMapOperator(project, resultSelector, 1)); } exports.concatMap = concatMap; global.define = __define; return module.exports; }); -System.register("rxjs/operator/concatMapTo", ["rxjs/operator/mergeMapTo-support"], true, function(require, exports, module) { +System.register("rxjs/operator/concatMapTo", ["rxjs/operator/mergeMapTo"], 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)); + "use strict"; + var mergeMapTo_1 = require("rxjs/operator/mergeMapTo"); + function concatMapTo(observable, resultSelector) { + return this.lift(new mergeMapTo_1.MergeMapToOperator(observable, resultSelector, 1)); } exports.concatMapTo = concatMapTo; global.define = __define; @@ -7829,6 +8971,7 @@ System.register("rxjs/add/operator/count", ["rxjs/Observable", "rxjs/operator/co var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var count_1 = require("rxjs/operator/count"); Observable_1.Observable.prototype.count = count_1.count; @@ -7840,6 +8983,7 @@ System.register("rxjs/add/operator/dematerialize", ["rxjs/Observable", "rxjs/ope var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var dematerialize_1 = require("rxjs/operator/dematerialize"); Observable_1.Observable.prototype.dematerialize = dematerialize_1.dematerialize; @@ -7851,6 +8995,7 @@ System.register("rxjs/add/operator/debounce", ["rxjs/Observable", "rxjs/operator var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var debounce_1 = require("rxjs/operator/debounce"); Observable_1.Observable.prototype.debounce = debounce_1.debounce; @@ -7862,6 +9007,7 @@ System.register("rxjs/add/operator/debounceTime", ["rxjs/Observable", "rxjs/oper var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var debounceTime_1 = require("rxjs/operator/debounceTime"); Observable_1.Observable.prototype.debounceTime = debounceTime_1.debounceTime; @@ -7873,6 +9019,7 @@ System.register("rxjs/add/operator/defaultIfEmpty", ["rxjs/Observable", "rxjs/op var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var defaultIfEmpty_1 = require("rxjs/operator/defaultIfEmpty"); Observable_1.Observable.prototype.defaultIfEmpty = defaultIfEmpty_1.defaultIfEmpty; @@ -7884,6 +9031,7 @@ System.register("rxjs/add/operator/delay", ["rxjs/Observable", "rxjs/operator/de var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var delay_1 = require("rxjs/operator/delay"); Observable_1.Observable.prototype.delay = delay_1.delay; @@ -7891,10 +9039,23 @@ System.register("rxjs/add/operator/delay", ["rxjs/Observable", "rxjs/operator/de return module.exports; }); +System.register("rxjs/add/operator/delayWhen", ["rxjs/Observable", "rxjs/operator/delayWhen"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + var Observable_1 = require("rxjs/Observable"); + var delayWhen_1 = require("rxjs/operator/delayWhen"); + Observable_1.Observable.prototype.delayWhen = delayWhen_1.delayWhen; + 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; + "use strict"; var Observable_1 = require("rxjs/Observable"); var distinctUntilChanged_1 = require("rxjs/operator/distinctUntilChanged"); Observable_1.Observable.prototype.distinctUntilChanged = distinctUntilChanged_1.distinctUntilChanged; @@ -7906,6 +9067,7 @@ System.register("rxjs/add/operator/do", ["rxjs/Observable", "rxjs/operator/do"], var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var do_1 = require("rxjs/operator/do"); Observable_1.Observable.prototype.do = do_1._do; @@ -7913,22 +9075,14 @@ System.register("rxjs/add/operator/do", ["rxjs/Observable", "rxjs/operator/do"], return module.exports; }); -System.register("rxjs/operator/expand", ["rxjs/operator/expand-support"], true, function(require, exports, module) { +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 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; + "use strict"; + 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; }); @@ -7937,6 +9091,7 @@ System.register("rxjs/add/operator/filter", ["rxjs/Observable", "rxjs/operator/f var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var filter_1 = require("rxjs/operator/filter"); Observable_1.Observable.prototype.filter = filter_1.filter; @@ -7948,6 +9103,7 @@ System.register("rxjs/add/operator/finally", ["rxjs/Observable", "rxjs/operator/ var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var finally_1 = require("rxjs/operator/finally"); Observable_1.Observable.prototype.finally = finally_1._finally; @@ -7955,10 +9111,11 @@ System.register("rxjs/add/operator/finally", ["rxjs/Observable", "rxjs/operator/ return module.exports; }); -System.register("rxjs/operator/first", ["rxjs/Subscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject", "rxjs/util/EmptyError"], true, function(require, exports, module) { +System.register("rxjs/operator/first", ["rxjs/Subscriber", "rxjs/util/EmptyError"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -7969,8 +9126,6 @@ System.register("rxjs/operator/first", ["rxjs/Subscriber", "rxjs/util/tryCatch", 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)); @@ -7987,7 +9142,7 @@ System.register("rxjs/operator/first", ["rxjs/Subscriber", "rxjs/util/tryCatch", 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) { @@ -8000,33 +9155,47 @@ System.register("rxjs/operator/first", ["rxjs/Subscriber", "rxjs/util/tryCatch", 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 (this.predicate) { + this._tryPredicate(value, index); + } else { + this._emit(value, index); } - 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._tryPredicate = function(value, index) { + var result; + try { + result = this.predicate(value, index, this.source); + } catch (err) { + this.destination.error(err); + return ; + } + if (result) { + this._emit(value, index); + } + }; + FirstSubscriber.prototype._emit = function(value, index) { + if (this.resultSelector) { + this._tryResultSelector(value, index); + return ; + } + this._emitFinal(value); + }; + FirstSubscriber.prototype._tryResultSelector = function(value, index) { + var result; + try { + result = this.resultSelector(value, index); + } catch (err) { + this.destination.error(err); + return ; } + this._emitFinal(result); + }; + FirstSubscriber.prototype._emitFinal = function(value) { + var destination = this.destination; + destination.next(value); + destination.complete(); + this.hasCompleted = true; }; FirstSubscriber.prototype._complete = function() { var destination = this.destination; @@ -8038,7 +9207,7 @@ System.register("rxjs/operator/first", ["rxjs/Subscriber", "rxjs/util/tryCatch", } }; return FirstSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); global.define = __define; return module.exports; }); @@ -8047,6 +9216,7 @@ System.register("rxjs/util/Map", ["rxjs/util/root", "rxjs/util/MapPolyfill"], tr var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var root_1 = require("rxjs/util/root"); var MapPolyfill_1 = require("rxjs/util/MapPolyfill"); exports.Map = root_1.root.Map || (function() { @@ -8060,6 +9230,7 @@ System.register("rxjs/add/operator/ignoreElements", ["rxjs/Observable", "rxjs/op var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var ignoreElements_1 = require("rxjs/operator/ignoreElements"); Observable_1.Observable.prototype.ignoreElements = ignoreElements_1.ignoreElements; @@ -8067,134 +9238,99 @@ System.register("rxjs/add/operator/ignoreElements", ["rxjs/Observable", "rxjs/op 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) { +System.register("rxjs/add/operator/inspect", ["rxjs/Observable", "rxjs/operator/inspect"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var map_1 = require("rxjs/operator/map"); - Observable_1.Observable.prototype.map = map_1.map; + var inspect_1 = require("rxjs/operator/inspect"); + Observable_1.Observable.prototype.inspect = inspect_1.inspect; global.define = __define; return module.exports; }); -System.register("rxjs/add/operator/mapTo", ["rxjs/Observable", "rxjs/operator/mapTo"], true, function(require, exports, module) { +System.register("rxjs/add/operator/inspectTime", ["rxjs/Observable", "rxjs/operator/inspectTime"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var mapTo_1 = require("rxjs/operator/mapTo"); - Observable_1.Observable.prototype.mapTo = mapTo_1.mapTo; + var inspectTime_1 = require("rxjs/operator/inspectTime"); + Observable_1.Observable.prototype.inspectTime = inspectTime_1.inspectTime; global.define = __define; return module.exports; }); -System.register("rxjs/add/operator/materialize", ["rxjs/Observable", "rxjs/operator/materialize"], true, function(require, exports, module) { +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; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var materialize_1 = require("rxjs/operator/materialize"); - Observable_1.Observable.prototype.materialize = materialize_1.materialize; + 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/merge", ["rxjs/Observable", "rxjs/operator/merge"], true, function(require, exports, module) { +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; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var merge_1 = require("rxjs/operator/merge"); - Observable_1.Observable.prototype.merge = merge_1.merge; + 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/mergeAll", ["rxjs/Observable", "rxjs/operator/mergeAll"], true, function(require, exports, module) { +System.register("rxjs/add/operator/let", ["rxjs/Observable", "rxjs/operator/let"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var mergeAll_1 = require("rxjs/operator/mergeAll"); - Observable_1.Observable.prototype.mergeAll = mergeAll_1.mergeAll; + var let_1 = require("rxjs/operator/let"); + Observable_1.Observable.prototype.let = let_1.letProto; + Observable_1.Observable.prototype.letBind = let_1.letProto; global.define = __define; return module.exports; }); -System.register("rxjs/add/operator/mergeMap", ["rxjs/Observable", "rxjs/operator/mergeMap"], true, function(require, exports, module) { +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; + "use strict"; 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; + 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/mergeMapTo", ["rxjs/Observable", "rxjs/operator/mergeMapTo"], true, function(require, exports, module) { +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; + "use strict"; 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; + 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/observeOn", ["rxjs/Observable", "rxjs/operator/observeOn"], true, function(require, exports, module) { +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; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var observeOn_1 = require("rxjs/operator/observeOn"); - Observable_1.Observable.prototype.observeOn = observeOn_1.observeOn; + var materialize_1 = require("rxjs/operator/materialize"); + Observable_1.Observable.prototype.materialize = materialize_1.materialize; global.define = __define; return module.exports; }); @@ -8203,6 +9339,7 @@ System.register("rxjs/operator/partition", ["rxjs/util/not", "rxjs/operator/filt var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var not_1 = require("rxjs/util/not"); var filter_1 = require("rxjs/operator/filter"); function partition(predicate, thisArg) { @@ -8213,95 +9350,41 @@ System.register("rxjs/operator/partition", ["rxjs/util/not", "rxjs/operator/filt return module.exports; }); -System.register("rxjs/add/operator/publish", ["rxjs/Observable", "rxjs/operator/publish"], true, function(require, exports, module) { +System.register("rxjs/add/operator/pluck", ["rxjs/Observable", "rxjs/operator/pluck"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var publish_1 = require("rxjs/operator/publish"); - Observable_1.Observable.prototype.publish = publish_1.publish; + var pluck_1 = require("rxjs/operator/pluck"); + Observable_1.Observable.prototype.pluck = pluck_1.pluck; global.define = __define; return module.exports; }); -System.register("rxjs/subject/BehaviorSubject", ["rxjs/Subject", "rxjs/util/throwError", "rxjs/util/ObjectUnsubscribedError"], true, function(require, exports, module) { +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 __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; + "use strict"; + 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/operator/publishReplay", ["rxjs/subject/ReplaySubject", "rxjs/operator/multicast"], true, function(require, exports, module) { +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 ReplaySubject_1 = require("rxjs/subject/ReplaySubject"); + "use strict"; + var BehaviorSubject_1 = require("rxjs/subject/BehaviorSubject"); 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)); + function publishBehavior(value) { + return multicast_1.multicast.call(this, new BehaviorSubject_1.BehaviorSubject(value)); } - exports.publishReplay = publishReplay; + exports.publishBehavior = publishBehavior; global.define = __define; return module.exports; }); @@ -8310,6 +9393,7 @@ System.register("rxjs/add/operator/publishLast", ["rxjs/Observable", "rxjs/opera var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var publishLast_1 = require("rxjs/operator/publishLast"); Observable_1.Observable.prototype.publishLast = publishLast_1.publishLast; @@ -8317,15 +9401,14 @@ System.register("rxjs/add/operator/publishLast", ["rxjs/Observable", "rxjs/opera return module.exports; }); -System.register("rxjs/operator/reduce", ["rxjs/operator/reduce-support"], true, function(require, exports, module) { +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 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; + "use strict"; + 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; }); @@ -8334,6 +9417,7 @@ System.register("rxjs/add/operator/repeat", ["rxjs/Observable", "rxjs/operator/r var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var repeat_1 = require("rxjs/operator/repeat"); Observable_1.Observable.prototype.repeat = repeat_1.repeat; @@ -8345,6 +9429,7 @@ System.register("rxjs/add/operator/retry", ["rxjs/Observable", "rxjs/operator/re var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var retry_1 = require("rxjs/operator/retry"); Observable_1.Observable.prototype.retry = retry_1.retry; @@ -8356,6 +9441,7 @@ System.register("rxjs/add/operator/retryWhen", ["rxjs/Observable", "rxjs/operato var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var retryWhen_1 = require("rxjs/operator/retryWhen"); Observable_1.Observable.prototype.retryWhen = retryWhen_1.retryWhen; @@ -8367,6 +9453,7 @@ System.register("rxjs/add/operator/sample", ["rxjs/Observable", "rxjs/operator/s var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var sample_1 = require("rxjs/operator/sample"); Observable_1.Observable.prototype.sample = sample_1.sample; @@ -8378,6 +9465,7 @@ System.register("rxjs/add/operator/sampleTime", ["rxjs/Observable", "rxjs/operat var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var sampleTime_1 = require("rxjs/operator/sampleTime"); Observable_1.Observable.prototype.sampleTime = sampleTime_1.sampleTime; @@ -8389,6 +9477,7 @@ System.register("rxjs/add/operator/scan", ["rxjs/Observable", "rxjs/operator/sca var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var scan_1 = require("rxjs/operator/scan"); Observable_1.Observable.prototype.scan = scan_1.scan; @@ -8400,6 +9489,7 @@ System.register("rxjs/add/operator/share", ["rxjs/Observable", "rxjs/operator/sh var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var share_1 = require("rxjs/operator/share"); Observable_1.Observable.prototype.share = share_1.share; @@ -8411,6 +9501,7 @@ System.register("rxjs/add/operator/single", ["rxjs/Observable", "rxjs/operator/s var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var single_1 = require("rxjs/operator/single"); Observable_1.Observable.prototype.single = single_1.single; @@ -8422,6 +9513,7 @@ System.register("rxjs/add/operator/skip", ["rxjs/Observable", "rxjs/operator/ski var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var skip_1 = require("rxjs/operator/skip"); Observable_1.Observable.prototype.skip = skip_1.skip; @@ -8433,6 +9525,7 @@ System.register("rxjs/add/operator/skipUntil", ["rxjs/Observable", "rxjs/operato var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var skipUntil_1 = require("rxjs/operator/skipUntil"); Observable_1.Observable.prototype.skipUntil = skipUntil_1.skipUntil; @@ -8444,6 +9537,7 @@ System.register("rxjs/add/operator/skipWhile", ["rxjs/Observable", "rxjs/operato var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var skipWhile_1 = require("rxjs/operator/skipWhile"); Observable_1.Observable.prototype.skipWhile = skipWhile_1.skipWhile; @@ -8455,6 +9549,7 @@ System.register("rxjs/add/operator/startWith", ["rxjs/Observable", "rxjs/operato var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var startWith_1 = require("rxjs/operator/startWith"); Observable_1.Observable.prototype.startWith = startWith_1.startWith; @@ -8466,6 +9561,7 @@ System.register("rxjs/operator/subscribeOn", ["rxjs/observable/SubscribeOnObserv var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var SubscribeOnObservable_1 = require("rxjs/observable/SubscribeOnObservable"); function subscribeOn(scheduler, delay) { if (delay === void 0) { @@ -8482,6 +9578,7 @@ System.register("rxjs/add/operator/switch", ["rxjs/Observable", "rxjs/operator/s var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var switch_1 = require("rxjs/operator/switch"); Observable_1.Observable.prototype.switch = switch_1._switch; @@ -8493,6 +9590,7 @@ System.register("rxjs/add/operator/switchMap", ["rxjs/Observable", "rxjs/operato var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var switchMap_1 = require("rxjs/operator/switchMap"); Observable_1.Observable.prototype.switchMap = switchMap_1.switchMap; @@ -8504,6 +9602,7 @@ System.register("rxjs/add/operator/switchMapTo", ["rxjs/Observable", "rxjs/opera var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var switchMapTo_1 = require("rxjs/operator/switchMapTo"); Observable_1.Observable.prototype.switchMapTo = switchMapTo_1.switchMapTo; @@ -8511,10 +9610,11 @@ System.register("rxjs/add/operator/switchMapTo", ["rxjs/Observable", "rxjs/opera return module.exports; }); -System.register("rxjs/operator/take", ["rxjs/Subscriber", "rxjs/util/ArgumentOutOfRangeError", "rxjs/observable/empty"], true, function(require, exports, module) { +System.register("rxjs/operator/take", ["rxjs/Subscriber", "rxjs/util/ArgumentOutOfRangeError", "rxjs/observable/EmptyObservable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -8526,10 +9626,10 @@ System.register("rxjs/operator/take", ["rxjs/Subscriber", "rxjs/util/ArgumentOut }; var Subscriber_1 = require("rxjs/Subscriber"); var ArgumentOutOfRangeError_1 = require("rxjs/util/ArgumentOutOfRangeError"); - var empty_1 = require("rxjs/observable/empty"); + var EmptyObservable_1 = require("rxjs/observable/EmptyObservable"); function take(total) { if (total === 0) { - return new empty_1.EmptyObservable(); + return new EmptyObservable_1.EmptyObservable(); } else { return this.lift(new TakeOperator(total)); } @@ -8546,7 +9646,7 @@ System.register("rxjs/operator/take", ["rxjs/Subscriber", "rxjs/util/ArgumentOut return new TakeSubscriber(subscriber, this.total); }; return TakeOperator; - })(); + }()); var TakeSubscriber = (function(_super) { __extends(TakeSubscriber, _super); function TakeSubscriber(destination, total) { @@ -8564,7 +9664,19 @@ System.register("rxjs/operator/take", ["rxjs/Subscriber", "rxjs/util/ArgumentOut } }; return TakeSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/operator/takeLast", ["rxjs/Observable", "rxjs/operator/takeLast"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + var Observable_1 = require("rxjs/Observable"); + var takeLast_1 = require("rxjs/operator/takeLast"); + Observable_1.Observable.prototype.takeLast = takeLast_1.takeLast; global.define = __define; return module.exports; }); @@ -8573,6 +9685,7 @@ System.register("rxjs/add/operator/takeUntil", ["rxjs/Observable", "rxjs/operato var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var takeUntil_1 = require("rxjs/operator/takeUntil"); Observable_1.Observable.prototype.takeUntil = takeUntil_1.takeUntil; @@ -8584,6 +9697,7 @@ System.register("rxjs/add/operator/takeWhile", ["rxjs/Observable", "rxjs/operato var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var takeWhile_1 = require("rxjs/operator/takeWhile"); Observable_1.Observable.prototype.takeWhile = takeWhile_1.takeWhile; @@ -8595,6 +9709,7 @@ System.register("rxjs/add/operator/throttle", ["rxjs/Observable", "rxjs/operator var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var throttle_1 = require("rxjs/operator/throttle"); Observable_1.Observable.prototype.throttle = throttle_1.throttle; @@ -8606,6 +9721,7 @@ System.register("rxjs/add/operator/throttleTime", ["rxjs/Observable", "rxjs/oper var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var throttleTime_1 = require("rxjs/operator/throttleTime"); Observable_1.Observable.prototype.throttleTime = throttleTime_1.throttleTime; @@ -8617,6 +9733,7 @@ System.register("rxjs/add/operator/timeout", ["rxjs/Observable", "rxjs/operator/ var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var timeout_1 = require("rxjs/operator/timeout"); Observable_1.Observable.prototype.timeout = timeout_1.timeout; @@ -8628,6 +9745,7 @@ System.register("rxjs/add/operator/timeoutWith", ["rxjs/Observable", "rxjs/opera var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var timeoutWith_1 = require("rxjs/operator/timeoutWith"); Observable_1.Observable.prototype.timeoutWith = timeoutWith_1.timeoutWith; @@ -8639,6 +9757,7 @@ System.register("rxjs/add/operator/toArray", ["rxjs/Observable", "rxjs/operator/ var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var toArray_1 = require("rxjs/operator/toArray"); Observable_1.Observable.prototype.toArray = toArray_1.toArray; @@ -8650,6 +9769,7 @@ System.register("rxjs/add/operator/toPromise", ["rxjs/Observable", "rxjs/operato var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var toPromise_1 = require("rxjs/operator/toPromise"); Observable_1.Observable.prototype.toPromise = toPromise_1.toPromise; @@ -8661,6 +9781,7 @@ System.register("rxjs/add/operator/window", ["rxjs/Observable", "rxjs/operator/w var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var window_1 = require("rxjs/operator/window"); Observable_1.Observable.prototype.window = window_1.window; @@ -8672,6 +9793,7 @@ System.register("rxjs/add/operator/windowCount", ["rxjs/Observable", "rxjs/opera var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var windowCount_1 = require("rxjs/operator/windowCount"); Observable_1.Observable.prototype.windowCount = windowCount_1.windowCount; @@ -8683,6 +9805,7 @@ System.register("rxjs/add/operator/windowTime", ["rxjs/Observable", "rxjs/operat var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var windowTime_1 = require("rxjs/operator/windowTime"); Observable_1.Observable.prototype.windowTime = windowTime_1.windowTime; @@ -8694,6 +9817,7 @@ System.register("rxjs/add/operator/windowToggle", ["rxjs/Observable", "rxjs/oper var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var windowToggle_1 = require("rxjs/operator/windowToggle"); Observable_1.Observable.prototype.windowToggle = windowToggle_1.windowToggle; @@ -8705,6 +9829,7 @@ System.register("rxjs/add/operator/windowWhen", ["rxjs/Observable", "rxjs/operat var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var windowWhen_1 = require("rxjs/operator/windowWhen"); Observable_1.Observable.prototype.windowWhen = windowWhen_1.windowWhen; @@ -8716,6 +9841,7 @@ System.register("rxjs/add/operator/withLatestFrom", ["rxjs/Observable", "rxjs/op var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var withLatestFrom_1 = require("rxjs/operator/withLatestFrom"); Observable_1.Observable.prototype.withLatestFrom = withLatestFrom_1.withLatestFrom; @@ -8723,21 +9849,11 @@ System.register("rxjs/add/operator/withLatestFrom", ["rxjs/Observable", "rxjs/op 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; + "use strict"; var Observable_1 = require("rxjs/Observable"); var zipAll_1 = require("rxjs/operator/zipAll"); Observable_1.Observable.prototype.zipAll = zipAll_1.zipAll; @@ -8745,20 +9861,11 @@ System.register("rxjs/add/operator/zipAll", ["rxjs/Observable", "rxjs/operator/z 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) { +System.register("rxjs/Subscription", ["rxjs/util/isArray", "rxjs/util/isObject", "rxjs/util/isFunction", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -8768,121 +9875,119 @@ System.register("rxjs/observable/ScalarObservable", ["rxjs/Observable", "rxjs/ut } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; - var Observable_1 = require("rxjs/Observable"); + var isArray_1 = require("rxjs/util/isArray"); + var isObject_1 = require("rxjs/util/isObject"); + var isFunction_1 = require("rxjs/util/isFunction"); 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; + var Subscription = (function() { + function Subscription(_unsubscribe) { + this.isUnsubscribed = false; + if (_unsubscribe) { + this._unsubscribe = _unsubscribe; + } } - 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(); + Subscription.prototype.unsubscribe = function() { + var hasErrors = false; + var errors; + if (this.isUnsubscribed) { return ; } - subscriber.next(value); - if (subscriber.isUnsubscribed) { - return ; + this.isUnsubscribed = true; + var _a = this, + _unsubscribe = _a._unsubscribe, + _subscriptions = _a._subscriptions; + this._subscriptions = null; + if (isFunction_1.isFunction(_unsubscribe)) { + var trial = tryCatch_1.tryCatch(_unsubscribe).call(this); + if (trial === errorObject_1.errorObject) { + hasErrors = true; + (errors = errors || []).push(errorObject_1.errorObject.e); + } } - 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(); + if (isArray_1.isArray(_subscriptions)) { + var index = -1; + var len = _subscriptions.length; + while (++index < len) { + var sub = _subscriptions[index]; + if (isObject_1.isObject(sub)) { + var trial = tryCatch_1.tryCatch(sub.unsubscribe).call(sub); + if (trial === errorObject_1.errorObject) { + hasErrors = true; + errors = errors || []; + var err = errorObject_1.errorObject.e; + if (err instanceof UnsubscriptionError) { + errors = errors.concat(err.errors); + } else { + errors.push(err); + } + } + } } } + if (hasErrors) { + throw new UnsubscriptionError(errors); + } }; - 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); + 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 { + (this._subscriptions || (this._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; + var UnsubscriptionError = (function(_super) { + __extends(UnsubscriptionError, _super); + function UnsubscriptionError(errors) { + _super.call(this, 'unsubscriptoin error(s)'); + this.errors = errors; + this.name = 'UnsubscriptionError'; } - }; - 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(); - }; + return UnsubscriptionError; + }(Error)); + exports.UnsubscriptionError = UnsubscriptionError; 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) { +System.register("rxjs/operator/combineLatest", ["rxjs/observable/ArrayObservable", "rxjs/util/isArray", "rxjs/util/isScheduler", "rxjs/OuterSubscriber", "rxjs/util/subscribeToResult"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -8892,10 +9997,46 @@ System.register("rxjs/operator/combineLatest-support", ["rxjs/util/tryCatch", "r } 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 ArrayObservable_1 = require("rxjs/observable/ArrayObservable"); + var isArray_1 = require("rxjs/util/isArray"); + var isScheduler_1 = require("rxjs/util/isScheduler"); var OuterSubscriber_1 = require("rxjs/OuterSubscriber"); var subscribeToResult_1 = require("rxjs/util/subscribeToResult"); + 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 ArrayObservable_1.ArrayObservable(observables).lift(new CombineLatestOperator(project)); + } + exports.combineLatest = combineLatest; + function combineLatestStatic() { + 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 ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new CombineLatestOperator(project)); + } + exports.combineLatestStatic = combineLatestStatic; var CombineLatestOperator = (function() { function CombineLatestOperator(project) { this.project = project; @@ -8904,7 +10045,7 @@ System.register("rxjs/operator/combineLatest-support", ["rxjs/util/tryCatch", "r return new CombineLatestSubscriber(subscriber, this.project); }; return CombineLatestOperator; - })(); + }()); exports.CombineLatestOperator = CombineLatestOperator; var CombineLatestSubscriber = (function(_super) { __extends(CombineLatestSubscriber, _super); @@ -8939,9 +10080,9 @@ System.register("rxjs/operator/combineLatest-support", ["rxjs/util/tryCatch", "r this.destination.complete(); } }; - CombineLatestSubscriber.prototype.notifyNext = function(observable, value, outerIndex, innerIndex) { + CombineLatestSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) { var values = this.values; - values[outerIndex] = value; + values[outerIndex] = innerValue; var toRespond = this.toRespond; if (toRespond.length > 0) { var found = toRespond.indexOf(outerIndex); @@ -8950,63 +10091,71 @@ System.register("rxjs/operator/combineLatest-support", ["rxjs/util/tryCatch", "r } } 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); - } + if (this.project) { + this._tryProject(values); } else { - destination.next(values); + this.destination.next(values); } } }; + CombineLatestSubscriber.prototype._tryProject = function(values) { + var result; + try { + result = this.project.apply(this, values); + } catch (err) { + this.destination.error(err); + return ; + } + this.destination.next(result); + }; return CombineLatestSubscriber; - })(OuterSubscriber_1.OuterSubscriber); + }(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) { +System.register("rxjs/add/observable/concat", ["rxjs/Observable", "rxjs/operator/concat"], 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(); + "use strict"; + var Observable_1 = require("rxjs/Observable"); + var concat_1 = require("rxjs/operator/concat"); + Observable_1.Observable.concat = concat_1.concatStatic; global.define = __define; return module.exports; }); -System.register("rxjs/add/observable/bindCallback", ["rxjs/Observable", "rxjs/observable/bindCallback"], true, function(require, exports, module) { +System.register("rxjs/add/observable/bindCallback", ["rxjs/Observable", "rxjs/observable/BoundCallbackObservable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var bindCallback_1 = require("rxjs/observable/bindCallback"); - Observable_1.Observable.bindCallback = bindCallback_1.BoundCallbackObservable.create; + var BoundCallbackObservable_1 = require("rxjs/observable/BoundCallbackObservable"); + Observable_1.Observable.bindCallback = BoundCallbackObservable_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) { +System.register("rxjs/add/observable/forkJoin", ["rxjs/Observable", "rxjs/observable/ForkJoinObservable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var forkJoin_1 = require("rxjs/observable/forkJoin"); - Observable_1.Observable.forkJoin = forkJoin_1.ForkJoinObservable.create; + var ForkJoinObservable_1 = require("rxjs/observable/ForkJoinObservable"); + Observable_1.Observable.forkJoin = ForkJoinObservable_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) { +System.register("rxjs/observable/FromObservable", ["rxjs/util/isArray", "rxjs/util/isFunction", "rxjs/util/isPromise", "rxjs/util/isScheduler", "rxjs/observable/PromiseObservable", "rxjs/observable/IteratorObservable", "rxjs/observable/ArrayObservable", "rxjs/observable/ArrayLikeObservable", "rxjs/util/SymbolShim", "rxjs/Observable", "rxjs/operator/observeOn"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -9016,14 +10165,20 @@ System.register("rxjs/observable/from", ["rxjs/observable/fromPromise", "rxjs/ob } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; - var fromPromise_1 = require("rxjs/observable/fromPromise"); + var isArray_1 = require("rxjs/util/isArray"); + var isFunction_1 = require("rxjs/util/isFunction"); + var isPromise_1 = require("rxjs/util/isPromise"); + var isScheduler_1 = require("rxjs/util/isScheduler"); + var PromiseObservable_1 = require("rxjs/observable/PromiseObservable"); var IteratorObservable_1 = require("rxjs/observable/IteratorObservable"); - var fromArray_1 = require("rxjs/observable/fromArray"); + var ArrayObservable_1 = require("rxjs/observable/ArrayObservable"); + var ArrayLikeObservable_1 = require("rxjs/observable/ArrayLikeObservable"); 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 observeOn_1 = require("rxjs/operator/observeOn"); + var isArrayLike = (function(x) { + return x && typeof x.length === 'number'; + }); var FromObservable = (function(_super) { __extends(FromObservable, _super); function FromObservable(ish, scheduler) { @@ -9031,46 +10186,54 @@ System.register("rxjs/observable/from", ["rxjs/observable/fromPromise", "rxjs/ob 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) { + FromObservable.create = function(ish, mapFnOrScheduler, thisArg, lastScheduler) { + var scheduler = null; + var mapFn = null; + if (isFunction_1.isFunction(mapFnOrScheduler)) { + scheduler = lastScheduler || null; + mapFn = mapFnOrScheduler; + } else if (isScheduler_1.isScheduler(scheduler)) { + scheduler = mapFnOrScheduler; + } + if (ish != null) { + if (typeof ish[SymbolShim_1.SymbolShim.observable] === 'function') { + if (ish instanceof Observable_1.Observable && !scheduler) { return ish; } return new FromObservable(ish, scheduler); - } else if (typeof ish[SymbolShim_1.SymbolShim.iterator] === 'function') { + } else if (isArray_1.isArray(ish)) { + return new ArrayObservable_1.ArrayObservable(ish, scheduler); + } else if (isPromise_1.isPromise(ish)) { + return new PromiseObservable_1.PromiseObservable(ish, scheduler); + } else if (typeof ish[SymbolShim_1.SymbolShim.iterator] === 'function' || typeof ish === 'string') { return new IteratorObservable_1.IteratorObservable(ish, null, null, scheduler); + } else if (isArrayLike(ish)) { + return new ArrayLikeObservable_1.ArrayLikeObservable(ish, mapFn, thisArg, scheduler); } } - throw new TypeError((typeof ish) + ' is not observable'); + throw new TypeError((ish !== null && typeof ish || ish) + ' is not observable'); }; FromObservable.prototype._subscribe = function(subscriber) { var ish = this.ish; var scheduler = this.scheduler; - if (scheduler === queue_1.queue) { + if (scheduler == null) { 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 ish[SymbolShim_1.SymbolShim.observable]().subscribe(new observeOn_1.ObserveOnSubscriber(subscriber, scheduler, 0)); } }; return FromObservable; - })(Observable_1.Observable); + }(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) { +System.register("rxjs/scheduler/AsapScheduler", ["rxjs/scheduler/AsapAction", "rxjs/scheduler/QueueScheduler"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -9080,75 +10243,88 @@ System.register("rxjs/scheduler/AsapScheduler", ["rxjs/scheduler/QueueScheduler" } 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 QueueScheduler_1 = require("rxjs/scheduler/QueueScheduler"); 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 new AsapAction_1.AsapAction(this, work).schedule(state); }; return AsapScheduler; - })(QueueScheduler_1.QueueScheduler); + }(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) { +System.register("rxjs/add/observable/never", ["rxjs/Observable", "rxjs/observable/NeverObservable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var timer_1 = require("rxjs/observable/timer"); - Observable_1.Observable.timer = timer_1.TimerObservable.create; + var NeverObservable_1 = require("rxjs/observable/NeverObservable"); + Observable_1.Observable.never = NeverObservable_1.NeverObservable.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) { +System.register("rxjs/add/observable/timer", ["rxjs/Observable", "rxjs/observable/TimerObservable"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var zip_static_1 = require("rxjs/operator/zip-static"); - Observable_1.Observable.zip = zip_static_1.zip; + var TimerObservable_1 = require("rxjs/observable/TimerObservable"); + Observable_1.Observable.timer = TimerObservable_1.TimerObservable.create; global.define = __define; return module.exports; }); -System.register("rxjs/add/operator/concatMap", ["rxjs/Observable", "rxjs/operator/concatMap"], true, function(require, exports, module) { +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 Observable_1 = require("rxjs/Observable"); - var concatMap_1 = require("rxjs/operator/concatMap"); - Observable_1.Observable.prototype.concatMap = concatMap_1.concatMap; + "use strict"; + 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/concatMapTo", ["rxjs/Observable", "rxjs/operator/concatMapTo"], true, function(require, exports, module) { +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; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var concatMapTo_1 = require("rxjs/operator/concatMapTo"); - Observable_1.Observable.prototype.concatMapTo = concatMapTo_1.concatMapTo; + 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/expand", ["rxjs/Observable", "rxjs/operator/expand"], true, function(require, exports, module) { +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; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var expand_1 = require("rxjs/operator/expand"); - Observable_1.Observable.prototype.expand = expand_1.expand; + var concatMapTo_1 = require("rxjs/operator/concatMapTo"); + Observable_1.Observable.prototype.concatMapTo = concatMapTo_1.concatMapTo; global.define = __define; return module.exports; }); @@ -9157,6 +10333,7 @@ System.register("rxjs/add/operator/first", ["rxjs/Observable", "rxjs/operator/fi var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var first_1 = require("rxjs/operator/first"); Observable_1.Observable.prototype.first = first_1.first; @@ -9164,10 +10341,11 @@ System.register("rxjs/add/operator/first", ["rxjs/Observable", "rxjs/operator/fi 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) { +System.register("rxjs/operator/groupBy", ["rxjs/Subscriber", "rxjs/Subscription", "rxjs/Observable", "rxjs/Operator", "rxjs/Subject", "rxjs/util/Map", "rxjs/util/FastMap"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -9178,199 +10356,238 @@ System.register("rxjs/operator/groupBy", ["rxjs/Subscriber", "rxjs/Observable", d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Subscriber_1 = require("rxjs/Subscriber"); + var Subscription_1 = require("rxjs/Subscription"); var Observable_1 = require("rxjs/Observable"); + var Operator_1 = require("rxjs/Operator"); 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); + return this.lift(new GroupByOperator(this, keySelector, elementSelector, durationSelector)); } exports.groupBy = groupBy; - var GroupByObservable = (function(_super) { - __extends(GroupByObservable, _super); - function GroupByObservable(source, keySelector, elementSelector, durationSelector) { + var GroupByOperator = (function(_super) { + __extends(GroupByOperator, _super); + function GroupByOperator(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; + GroupByOperator.prototype.call = function(subscriber) { + return new GroupBySubscriber(subscriber, this.keySelector, this.elementSelector, this.durationSelector); }; - return GroupByObservable; - })(Observable_1.Observable); - exports.GroupByObservable = GroupByObservable; + return GroupByOperator; + }(Operator_1.Operator)); var GroupBySubscriber = (function(_super) { __extends(GroupBySubscriber, _super); - function GroupBySubscriber(destination, refCountSubscription, keySelector, elementSelector, durationSelector) { + function GroupBySubscriber(destination, keySelector, elementSelector, durationSelector) { _super.call(this); - this.refCountSubscription = refCountSubscription; this.keySelector = keySelector; this.elementSelector = elementSelector; this.durationSelector = durationSelector; this.groups = null; + this.attemptedToUnsubscribe = false; + this.count = 0; 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._next = function(value) { + var key; + try { + key = this.keySelector(value); + } catch (err) { + this.error(err); + return ; + } + this._group(value, key); + }; + GroupBySubscriber.prototype._group = function(value, key) { + var groups = this.groups; + 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 GroupedObservable(key, group, this); + if (this.durationSelector) { + this._selectDuration(key, group); } + this.destination.next(groupedObservable); + } + if (this.elementSelector) { + this._selectElement(value, group); + } else { + this.tryGroupNext(value, group); + } + }; + GroupBySubscriber.prototype._selectElement = function(value, group) { + var result; + try { + result = this.elementSelector(value); + } catch (err) { + this.error(err); + return ; + } + this.tryGroupNext(result, group); + }; + GroupBySubscriber.prototype._selectDuration = function(key, group) { + var duration; + try { + duration = this.durationSelector(new GroupedObservable(key, group)); + } catch (err) { + this.error(err); + return ; + } + this.add(duration.subscribe(new GroupDurationSubscriber(key, group, this))); + }; + GroupBySubscriber.prototype.tryGroupNext = function(value, group) { + if (!group.isUnsubscribed) { + group.next(value); } }; 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); }); + groups.clear(); } 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); }); + groups.clear(); } this.destination.complete(); }; GroupBySubscriber.prototype.removeGroup = function(key) { this.groups.delete(key); }; + GroupBySubscriber.prototype.unsubscribe = function() { + if (!this.isUnsubscribed && !this.attemptedToUnsubscribe) { + this.attemptedToUnsubscribe = true; + if (this.count === 0) { + _super.prototype.unsubscribe.call(this); + } + } + }; return GroupBySubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); var GroupDurationSubscriber = (function(_super) { __extends(GroupDurationSubscriber, _super); function GroupDurationSubscriber(key, group, parent) { - _super.call(this, null); + _super.call(this); this.key = key; this.group = group; this.parent = parent; } GroupDurationSubscriber.prototype._next = function(value) { - this.group.complete(); - this.parent.removeGroup(this.key); + this.tryComplete(); }; GroupDurationSubscriber.prototype._error = function(err) { - this.group.error(err); - this.parent.removeGroup(this.key); + this.tryError(err); }; GroupDurationSubscriber.prototype._complete = function() { - this.group.complete(); + this.tryComplete(); + }; + GroupDurationSubscriber.prototype.tryError = function(err) { + var group = this.group; + if (!group.isUnsubscribed) { + group.error(err); + } + this.parent.removeGroup(this.key); + }; + GroupDurationSubscriber.prototype.tryComplete = function() { + var group = this.group; + if (!group.isUnsubscribed) { + group.complete(); + } this.parent.removeGroup(this.key); }; return GroupDurationSubscriber; - })(Subscriber_1.Subscriber); + }(Subscriber_1.Subscriber)); + 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(); + var _a = this, + refCountSubscription = _a.refCountSubscription, + groupSubject = _a.groupSubject; + if (refCountSubscription && !refCountSubscription.isUnsubscribed) { + subscription.add(new InnerRefCountSubscription(refCountSubscription)); + } + subscription.add(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() { + var parent = this.parent; + if (!parent.isUnsubscribed && !this.isUnsubscribed) { + _super.prototype.unsubscribe.call(this); + parent.count -= 1; + if (parent.count === 0 && parent.attemptedToUnsubscribe) { + parent.unsubscribe(); + } + } + }; + return InnerRefCountSubscription; + }(Subscription_1.Subscription)); global.define = __define; return module.exports; }); -System.register("rxjs/add/operator/multicast", ["rxjs/Observable", "rxjs/operator/multicast"], true, function(require, exports, module) { +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; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var multicast_1 = require("rxjs/operator/multicast"); - Observable_1.Observable.prototype.multicast = multicast_1.multicast; + var partition_1 = require("rxjs/operator/partition"); + Observable_1.Observable.prototype.partition = partition_1.partition; global.define = __define; return module.exports; }); -System.register("rxjs/add/operator/partition", ["rxjs/Observable", "rxjs/operator/partition"], true, function(require, exports, module) { +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; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var partition_1 = require("rxjs/operator/partition"); - Observable_1.Observable.prototype.partition = partition_1.partition; + var publishBehavior_1 = require("rxjs/operator/publishBehavior"); + Observable_1.Observable.prototype.publishBehavior = publishBehavior_1.publishBehavior; 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) { +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; + "use strict"; var Observable_1 = require("rxjs/Observable"); var subscribeOn_1 = require("rxjs/operator/subscribeOn"); Observable_1.Observable.prototype.subscribeOn = subscribeOn_1.subscribeOn; @@ -9382,6 +10599,7 @@ System.register("rxjs/add/operator/take", ["rxjs/Observable", "rxjs/operator/tak var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var Observable_1 = require("rxjs/Observable"); var take_1 = require("rxjs/operator/take"); Observable_1.Observable.prototype.take = take_1.take; @@ -9389,10 +10607,11 @@ System.register("rxjs/add/operator/take", ["rxjs/Observable", "rxjs/operator/tak 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) { +System.register("rxjs/Subscriber", ["rxjs/util/isFunction", "rxjs/Subscription", "rxjs/symbol/rxSubscriber", "rxjs/Observer"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -9402,418 +10621,279 @@ System.register("rxjs/Subscriber", ["rxjs/util/noop", "rxjs/util/throwError", "r } 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 isFunction_1 = require("rxjs/util/isFunction"); var Subscription_1 = require("rxjs/Subscription"); var rxSubscriber_1 = require("rxjs/symbol/rxSubscriber"); + var Observer_1 = require("rxjs/Observer"); var Subscriber = (function(_super) { __extends(Subscriber, _super); - function Subscriber(destination) { + function Subscriber(destinationOrNext, error, complete) { _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; + this.syncErrorValue = null; + this.syncErrorThrown = false; + this.syncErrorThrowable = false; + this.isStopped = false; + switch (arguments.length) { + case 0: + this.destination = Observer_1.empty; + break; + case 1: + if (!destinationOrNext) { + this.destination = Observer_1.empty; + break; + } + if (typeof destinationOrNext === 'object') { + if (destinationOrNext instanceof Subscriber) { + this.destination = destinationOrNext; + } else { + this.syncErrorThrowable = true; + this.destination = new SafeSubscriber(this, destinationOrNext); + } + break; + } + default: + this.syncErrorThrowable = true; + this.destination = new SafeSubscriber(this, destinationOrNext, error, complete); + break; } } - 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; + var subscriber = new Subscriber(next, error, complete); + subscriber.syncErrorThrowable = false; 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) { + if (!this.isStopped) { this._next(value); } }; Subscriber.prototype.error = function(err) { - if (!this.isUnsubscribed) { + if (!this.isStopped) { + this.isStopped = true; this._error(err); - this.unsubscribe(); } }; Subscriber.prototype.complete = function() { - if (!this.isUnsubscribed) { + if (!this.isStopped) { + this.isStopped = true; 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) { + Subscriber.prototype.unsubscribe = function() { + if (this.isUnsubscribed) { return ; } - state.index = index + 1; - this.schedule(state); + this.isStopped = true; + _super.prototype.unsubscribe.call(this); }; - 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(); - } + Subscriber.prototype._next = function(value) { + this.destination.next(value); }; - 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; + Subscriber.prototype._error = function(err) { + this.destination.error(err); + this.unsubscribe(); }; - Observable.prototype[SymbolShim_1.SymbolShim.observable] = function() { + Subscriber.prototype._complete = function() { + this.destination.complete(); + this.unsubscribe(); + }; + Subscriber.prototype[rxSubscriber_1.rxSubscriber] = 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); + return Subscriber; + }(Subscription_1.Subscription)); + exports.Subscriber = Subscriber; + var SafeSubscriber = (function(_super) { + __extends(SafeSubscriber, _super); + function SafeSubscriber(_parent, observerOrNext, error, complete) { + _super.call(this); + this._parent = _parent; + var next; + var context = this; + if (isFunction_1.isFunction(observerOrNext)) { + next = observerOrNext; + } else if (observerOrNext) { + context = observerOrNext; + next = observerOrNext.next; + error = observerOrNext.error; + complete = observerOrNext.complete; + } + this._context = context; + this._next = next; + this._error = error; + this._complete = complete; + } + SafeSubscriber.prototype.next = function(value) { + if (!this.isStopped && this._next) { + var _parent = this._parent; + if (!_parent.syncErrorThrowable) { + this.__tryOrUnsub(this._next, value); + } else if (this.__tryOrSetError(_parent, this._next, value)) { + this.unsubscribe(); } - } 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; + SafeSubscriber.prototype.error = function(err) { + if (!this.isStopped) { + var _parent = this._parent; + if (this._error) { + if (!_parent.syncErrorThrowable) { + this.__tryOrUnsub(this._error, err); + this.unsubscribe(); + } else { + this.__tryOrSetError(_parent, this._error, err); + this.unsubscribe(); + } + } else if (!_parent.syncErrorThrowable) { + this.unsubscribe(); + throw err; + } else { + _parent.syncErrorValue = err; + _parent.syncErrorThrown = true; + this.unsubscribe(); } } - if (!PromiseCtor) { - throw new Error('no Promise impl found'); + }; + SafeSubscriber.prototype.complete = function() { + if (!this.isStopped) { + var _parent = this._parent; + if (this._complete) { + if (!_parent.syncErrorThrowable) { + this.__tryOrUnsub(this._complete); + this.unsubscribe(); + } else { + this.__tryOrSetError(_parent, this._complete); + this.unsubscribe(); + } + } else { + this.unsubscribe(); + } } - 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; + }; + SafeSubscriber.prototype.__tryOrUnsub = function(fn, value) { + try { + fn.call(this._context, value); + } catch (err) { + this.unsubscribe(); + throw err; } - 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)); + SafeSubscriber.prototype.__tryOrSetError = function(parent, fn, value) { + try { + fn.call(this._context, value); + } catch (err) { + parent.syncErrorValue = err; + parent.syncErrorThrown = true; + return true; + } + return false; }; - Observable.create = function(subscribe) { - return new Observable(subscribe); + SafeSubscriber.prototype._unsubscribe = function() { + var _parent = this._parent; + this._context = null; + this._parent = null; + _parent.unsubscribe(); }; - return Observable; - })(); - exports.Observable = Observable; + return SafeSubscriber; + }(Subscriber)); 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) { +System.register("rxjs/add/observable/combineLatest", ["rxjs/Observable", "rxjs/operator/combineLatest"], 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(); + "use strict"; + var Observable_1 = require("rxjs/Observable"); + var combineLatest_1 = require("rxjs/operator/combineLatest"); + Observable_1.Observable.combineLatest = combineLatest_1.combineLatestStatic; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/observable/from", ["rxjs/Observable", "rxjs/observable/FromObservable"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + var Observable_1 = require("rxjs/Observable"); + var FromObservable_1 = require("rxjs/observable/FromObservable"); + Observable_1.Observable.from = FromObservable_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; + "use strict"; + var AsapScheduler_1 = require("rxjs/scheduler/AsapScheduler"); + exports.asap = new AsapScheduler_1.AsapScheduler(); + global.define = __define; + return module.exports; +}); + +System.register("rxjs/operator/cache", ["rxjs/operator/publishReplay"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + var publishReplay_1 = require("rxjs/operator/publishReplay"); + function cache(bufferSize, windowTime, scheduler) { + if (bufferSize === void 0) { + bufferSize = Number.POSITIVE_INFINITY; } - if (observables.length === 1 && isArray_1.isArray(observables[0])) { - observables = observables[0]; + if (windowTime === void 0) { + windowTime = Number.POSITIVE_INFINITY; } - return new fromArray_1.ArrayObservable(observables, scheduler).lift(new combineLatest_support_1.CombineLatestOperator(project)); + return publishReplay_1.publishReplay.call(this, bufferSize, windowTime, scheduler).refCount(); } - exports.combineLatest = combineLatest; + exports.cache = cache; global.define = __define; return module.exports; }); -System.register("rxjs/add/operator/concat-static", ["rxjs/Observable", "rxjs/operator/concat-static"], true, function(require, exports, module) { +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; + "use strict"; var Observable_1 = require("rxjs/Observable"); - var concat_static_1 = require("rxjs/operator/concat-static"); - Observable_1.Observable.concat = concat_static_1.concat; + var groupBy_1 = require("rxjs/operator/groupBy"); + Observable_1.Observable.prototype.groupBy = groupBy_1.groupBy; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/util/toSubscriber", ["rxjs/Subscriber", "rxjs/symbol/rxSubscriber"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + var Subscriber_1 = require("rxjs/Subscriber"); + var rxSubscriber_1 = require("rxjs/symbol/rxSubscriber"); + function toSubscriber(nextOrObserver, error, complete) { + if (nextOrObserver && typeof nextOrObserver === 'object') { + if (nextOrObserver instanceof Subscriber_1.Subscriber) { + return nextOrObserver; + } else if (typeof nextOrObserver[rxSubscriber_1.rxSubscriber] === 'function') { + return nextOrObserver[rxSubscriber_1.rxSubscriber](); + } + } + return new Subscriber_1.Subscriber(nextOrObserver, error, complete); + } + exports.toSubscriber = toSubscriber; global.define = __define; return module.exports; }); -System.register("rxjs/observable/interval", ["rxjs/util/isNumeric", "rxjs/Observable", "rxjs/scheduler/asap"], true, function(require, exports, module) { +System.register("rxjs/observable/IntervalObservable", ["rxjs/util/isNumeric", "rxjs/Observable", "rxjs/scheduler/asap"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -9876,16 +10956,117 @@ System.register("rxjs/observable/interval", ["rxjs/util/isNumeric", "rxjs/Observ })); }; return IntervalObservable; - })(Observable_1.Observable); + }(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) { +System.register("rxjs/add/operator/cache", ["rxjs/Observable", "rxjs/operator/cache"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + var Observable_1 = require("rxjs/Observable"); + var cache_1 = require("rxjs/operator/cache"); + Observable_1.Observable.prototype.cache = cache_1.cache; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/Observable", ["rxjs/util/root", "rxjs/util/SymbolShim", "rxjs/util/toSubscriber", "rxjs/util/tryCatch", "rxjs/util/errorObject"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + var root_1 = require("rxjs/util/root"); + var SymbolShim_1 = require("rxjs/util/SymbolShim"); + var toSubscriber_1 = require("rxjs/util/toSubscriber"); + var tryCatch_1 = require("rxjs/util/tryCatch"); + var errorObject_1 = require("rxjs/util/errorObject"); + 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.subscribe = function(observerOrNext, error, complete) { + var operator = this.operator; + var subscriber = toSubscriber_1.toSubscriber(observerOrNext, error, complete); + if (operator) { + subscriber.add(this._subscribe(operator.call(subscriber))); + } else { + subscriber.add(this._subscribe(subscriber)); + } + if (subscriber.syncErrorThrowable) { + subscriber.syncErrorThrowable = false; + if (subscriber.syncErrorThrown) { + throw subscriber.syncErrorValue; + } + } + 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 source = this; + return new PromiseCtor(function(resolve, reject) { + source.subscribe(function(value) { + var result = tryCatch_1.tryCatch(next).call(thisArg, value); + if (result === errorObject_1.errorObject) { + reject(errorObject_1.errorObject.e); + } + }, reject, resolve); + }); + }; + Observable.prototype._subscribe = function(subscriber) { + return this.source.subscribe(subscriber); + }; + Observable.prototype[SymbolShim_1.SymbolShim.observable] = function() { + return this; + }; + Observable.create = function(subscribe) { + return new Observable(subscribe); + }; + return Observable; + }()); + exports.Observable = Observable; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/add/observable/interval", ["rxjs/Observable", "rxjs/observable/IntervalObservable"], true, function(require, exports, module) { + var global = System.global, + __define = global.define; + global.define = undefined; + "use strict"; + var Observable_1 = require("rxjs/Observable"); + var IntervalObservable_1 = require("rxjs/observable/IntervalObservable"); + Observable_1.Observable.interval = IntervalObservable_1.IntervalObservable.create; + global.define = __define; + return module.exports; +}); + +System.register("rxjs/Subject", ["rxjs/Observable", "rxjs/Subscriber", "rxjs/Subscription", "rxjs/subject/SubjectSubscription", "rxjs/symbol/rxSubscriber", "rxjs/util/throwError", "rxjs/util/ObjectUnsubscribedError"], true, function(require, exports, module) { var global = System.global, __define = global.define; global.define = undefined; + "use strict"; var __extends = (this && this.__extends) || function(d, b) { for (var p in b) if (b.hasOwnProperty(p)) @@ -9900,98 +11081,109 @@ System.register("rxjs/Subject", ["rxjs/Observable", "rxjs/Subscriber", "rxjs/Sub 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 throwError_1 = require("rxjs/util/throwError"); + var ObjectUnsubscribedError_1 = require("rxjs/util/ObjectUnsubscribedError"); var Subject = (function(_super) { __extends(Subject, _super); - function Subject() { - _super.apply(this, arguments); + function Subject(destination, source) { + _super.call(this); + this.destination = destination; + this.source = source; this.observers = []; this.isUnsubscribed = false; + this.isStopped = false; + this.hasErrored = false; this.dispatching = false; - this.errorSignal = false; - this.completeSignal = false; + this.hasCompleted = 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); + var subject = new Subject(this.destination || this, 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); + Subscription_1.Subscription.prototype.add.call(this, subscription); }; Subject.prototype.remove = function(subscription) { - subscriptionRemove.call(this, subscription); + Subscription_1.Subscription.prototype.remove.call(this, subscription); }; Subject.prototype.unsubscribe = function() { - this.observers = void 0; - subscriptionUnsubscribe.call(this); + Subscription_1.Subscription.prototype.unsubscribe.call(this); + }; + Subject.prototype._subscribe = function(subscriber) { + if (this.source) { + return this.source.subscribe(subscriber); + } else { + if (subscriber.isUnsubscribed) { + return ; + } else if (this.hasErrored) { + return subscriber.error(this.errorValue); + } else if (this.hasCompleted) { + return subscriber.complete(); + } + this.throwIfUnsubscribed(); + var subscription = new SubjectSubscription_1.SubjectSubscription(this, subscriber); + this.observers.push(subscriber); + return subscription; + } + }; + Subject.prototype._unsubscribe = function() { + this.source = null; + this.isStopped = true; + this.observers = null; + this.destination = null; }; Subject.prototype.next = function(value) { - if (this.isUnsubscribed) { + this.throwIfUnsubscribed(); + if (this.isStopped) { return ; } this.dispatching = true; this._next(value); this.dispatching = false; - if (this.errorSignal) { - this.error(this.errorInstance); - } else if (this.completeSignal) { - this.complete(); + if (this.hasErrored) { + this._error(this.errorValue); + } else if (this.hasCompleted) { + this._complete(); } }; Subject.prototype.error = function(err) { - if (this.isUnsubscribed || this.completeSignal) { + this.throwIfUnsubscribed(); + if (this.isStopped) { return ; } - this.errorSignal = true; - this.errorInstance = err; + this.isStopped = true; + this.hasErrored = true; + this.errorValue = err; if (this.dispatching) { return ; } this._error(err); - this.unsubscribe(); }; Subject.prototype.complete = function() { - if (this.isUnsubscribed || this.errorSignal) { + this.throwIfUnsubscribed(); + if (this.isStopped) { return ; } - this.completeSignal = true; + this.isStopped = true; + this.hasCompleted = true; if (this.dispatching) { return ; } this._complete(); - this.unsubscribe(); + }; + Subject.prototype.asObservable = function() { + var observable = new SubjectObservable(this); + return observable; }; Subject.prototype._next = function(value) { + if (this.destination) { + this.destination.next(value); + } else { + this._finalNext(value); + } + }; + Subject.prototype._finalNext = function(value) { var index = -1; var observers = this.observers.slice(0); var len = observers.length; @@ -10000,99 +11192,88 @@ System.register("rxjs/Subject", ["rxjs/Observable", "rxjs/Subscriber", "rxjs/Sub } }; Subject.prototype._error = function(err) { + if (this.destination) { + this.destination.error(err); + } else { + this._finalError(err); + } + }; + Subject.prototype._finalError = function(err) { var index = -1; var observers = this.observers; - var len = observers.length; - this.observers = void 0; + this.observers = null; this.isUnsubscribed = true; - while (++index < len) { - observers[index].error(err); + if (observers) { + var len = observers.length; + while (++index < len) { + observers[index].error(err); + } } this.isUnsubscribed = false; + this.unsubscribe(); }; Subject.prototype._complete = function() { + if (this.destination) { + this.destination.complete(); + } else { + this._finalComplete(); + } + }; + Subject.prototype._finalComplete = function() { var index = -1; var observers = this.observers; - var len = observers.length; - this.observers = void 0; + this.observers = null; this.isUnsubscribed = true; - while (++index < len) { - observers[index].complete(); + if (observers) { + var len = observers.length; + while (++index < len) { + observers[index].complete(); + } } this.isUnsubscribed = false; + this.unsubscribe(); + }; + Subject.prototype.throwIfUnsubscribed = function() { + if (this.isUnsubscribed) { + throwError_1.throwError(new ObjectUnsubscribedError_1.ObjectUnsubscribedError()); + } + }; + Subject.prototype[rxSubscriber_1.rxSubscriber] = function() { + return new Subscriber_1.Subscriber(this); + }; + Subject.create = function(destination, source) { + return new Subject(destination, source); }; return Subject; - })(Observable_1.Observable); + }(Observable_1.Observable)); exports.Subject = Subject; - var BidirectionalSubject = (function(_super) { - __extends(BidirectionalSubject, _super); - function BidirectionalSubject(source, destination) { + var SubjectObservable = (function(_super) { + __extends(SubjectObservable, _super); + function SubjectObservable(source) { _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; + return SubjectObservable; + }(Observable_1.Observable)); 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) { +System.register("rxjs/Rx", ["rxjs/Subject", "rxjs/Observable", "rxjs/add/observable/combineLatest", "rxjs/add/observable/concat", "rxjs/add/observable/merge", "rxjs/add/observable/race", "rxjs/add/observable/bindCallback", "rxjs/add/observable/bindNodeCallback", "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/observable/zip", "rxjs/add/operator/buffer", "rxjs/add/operator/bufferCount", "rxjs/add/operator/bufferTime", "rxjs/add/operator/bufferToggle", "rxjs/add/operator/bufferWhen", "rxjs/add/operator/cache", "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/delayWhen", "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/inspect", "rxjs/add/operator/inspectTime", "rxjs/add/operator/every", "rxjs/add/operator/last", "rxjs/add/operator/let", "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/pluck", "rxjs/add/operator/publish", "rxjs/add/operator/publishBehavior", "rxjs/add/operator/publishReplay", "rxjs/add/operator/publishLast", "rxjs/add/operator/race", "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/takeLast", "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/Operator", "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; + "use strict"; 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/combineLatest"); + require("rxjs/add/observable/concat"); + require("rxjs/add/observable/merge"); + require("rxjs/add/observable/race"); require("rxjs/add/observable/bindCallback"); + require("rxjs/add/observable/bindNodeCallback"); require("rxjs/add/observable/defer"); require("rxjs/add/observable/empty"); require("rxjs/add/observable/forkJoin"); @@ -10106,12 +11287,13 @@ System.register("rxjs/Rx", ["rxjs/Subject", "rxjs/Observable", "rxjs/add/operato require("rxjs/add/observable/range"); require("rxjs/add/observable/throw"); require("rxjs/add/observable/timer"); - require("rxjs/add/operator/zip-static"); + require("rxjs/add/observable/zip"); 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/cache"); require("rxjs/add/operator/catch"); require("rxjs/add/operator/combineAll"); require("rxjs/add/operator/combineLatest"); @@ -10125,6 +11307,7 @@ System.register("rxjs/Rx", ["rxjs/Subject", "rxjs/Observable", "rxjs/add/operato require("rxjs/add/operator/debounceTime"); require("rxjs/add/operator/defaultIfEmpty"); require("rxjs/add/operator/delay"); + require("rxjs/add/operator/delayWhen"); require("rxjs/add/operator/distinctUntilChanged"); require("rxjs/add/operator/do"); require("rxjs/add/operator/expand"); @@ -10133,8 +11316,11 @@ System.register("rxjs/Rx", ["rxjs/Subject", "rxjs/Observable", "rxjs/add/operato require("rxjs/add/operator/first"); require("rxjs/add/operator/groupBy"); require("rxjs/add/operator/ignoreElements"); + require("rxjs/add/operator/inspect"); + require("rxjs/add/operator/inspectTime"); require("rxjs/add/operator/every"); require("rxjs/add/operator/last"); + require("rxjs/add/operator/let"); require("rxjs/add/operator/map"); require("rxjs/add/operator/mapTo"); require("rxjs/add/operator/materialize"); @@ -10145,10 +11331,12 @@ System.register("rxjs/Rx", ["rxjs/Subject", "rxjs/Observable", "rxjs/add/operato require("rxjs/add/operator/multicast"); require("rxjs/add/operator/observeOn"); require("rxjs/add/operator/partition"); + require("rxjs/add/operator/pluck"); require("rxjs/add/operator/publish"); require("rxjs/add/operator/publishBehavior"); require("rxjs/add/operator/publishReplay"); require("rxjs/add/operator/publishLast"); + require("rxjs/add/operator/race"); require("rxjs/add/operator/reduce"); require("rxjs/add/operator/repeat"); require("rxjs/add/operator/retry"); @@ -10167,6 +11355,7 @@ System.register("rxjs/Rx", ["rxjs/Subject", "rxjs/Observable", "rxjs/add/operato require("rxjs/add/operator/switchMap"); require("rxjs/add/operator/switchMapTo"); require("rxjs/add/operator/take"); + require("rxjs/add/operator/takeLast"); require("rxjs/add/operator/takeUntil"); require("rxjs/add/operator/takeWhile"); require("rxjs/add/operator/throttle"); @@ -10183,8 +11372,11 @@ System.register("rxjs/Rx", ["rxjs/Subject", "rxjs/Observable", "rxjs/add/operato require("rxjs/add/operator/withLatestFrom"); require("rxjs/add/operator/zip"); require("rxjs/add/operator/zipAll"); + var Operator_1 = require("rxjs/Operator"); + exports.Operator = Operator_1.Operator; var Subscription_1 = require("rxjs/Subscription"); exports.Subscription = Subscription_1.Subscription; + exports.UnsubscriptionError = Subscription_1.UnsubscriptionError; var Subscriber_1 = require("rxjs/Subscriber"); exports.Subscriber = Subscriber_1.Subscriber; var AsyncSubject_1 = require("rxjs/subject/AsyncSubject"); @@ -10216,3 +11408,4 @@ System.register("rxjs/Rx", ["rxjs/Subject", "rxjs/Observable", "rxjs/add/operato 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 index b055c60e1..632a76e49 100644 --- a/testapp/ng2/lib/systemjs/dist/system-polyfills.js +++ b/testapp/ng2/lib/systemjs/dist/system-polyfills.js @@ -1,5 +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;n=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&&"[object process]"===Object.prototype.toString.call(process)}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.message)?t.stack||t.message: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 U(t)?t:new e(j,new g(v(t)))}function r(t){return new e(j,new g(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(M,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=A,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=O();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()}(); +!function(){function e(){!function(e){function t(e,t){return e instanceof Error?e.message=e.message+"\n "+t:e+="\n "+t,e}function n(e,n,r){try{new Function(e).call(r)}catch(a){throw t(a,"Evaluating "+n)}}function r(){}function a(t){this._loader={loaderObj:this,loads:[],modules:{},importPromises:{},moduleRecords:{}},T(this,"global",{get:function(){return e}})}function o(){a.call(this),this.paths={}}function s(e,t){var n,r="",a=0;for(var o in e){var s=o.split("*");if(s.length>2)throw new TypeError("Only one wildcard in a path is permitted");if(1==s.length){if(t==o)return e[o];if(t.substr(0,o.length-1)==o.substr(0,o.length-1)&&(t.lengtho.length?"/"+t.substr(o.length):"")}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];return"string"==typeof n&&(l=l.replace("*",n)),l}function i(){}function l(){o.call(this),q.call(this)}function u(){}function d(e,t){l.prototype[e]=t(l.prototype[e]||function(){})}function c(e){q=e(q||function(){})}function f(e){for(var t=[],n=[],r=0,a=e.length;a>r;r++){var o=I.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(N){var n;for(var r in e)(n=Object.getOwnPropertyDescriptor(e,r))&&T(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,T(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&&null!==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 b(){if(Z[this.baseURL])return Z[this.baseURL];"/"!=this.baseURL[this.baseURL.length-1]&&(this.baseURL+="/");var e=new A(this.baseURL,L);return this.baseURL=e.href,Z[this.baseURL]=e}function y(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 x(e){this.set("@system-env",this.newModule({browser:O,node:!!this._nodeRequire,production:e}))}function w(e){if("."!=e[0]&&"/"!=e[0]&&!e.match(X)){var t=y(this.map,e);if(t)return this.map[t]+e.substr(t.length)}return e}function S(e){var t=e.match(K);return t&&"System.register"==e.substr(t[0].length,15)}function E(){return{name:null,deps:null,originalIndices:null,declare:null,execute:null,executingRequire:!1,declarative:!1,normalizedDeps:null,groupIndex:null,evaluated:!1,module:null,esModule:null,esmExports:!1}}function j(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 _(e){return(e.negate?"~":"")+e.module+(e.prop?"|"+e.prop:"")}function k(e,t,n){return this["import"](e.module,t).then(function(t){if(e.prop?t=v(e.prop,t):"object"==typeof t&&t+""=="Module"&&(t=t["default"]),n&&"boolean"!=typeof t)throw new TypeError("Condition "+_(e)+" did not resolve to a boolean.");return e.negate?!t:t})}function P(e,t){var n=e.match(Q);if(!n)return Promise.resolve(e);var r=j(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(Q,"#{"+_(r)+"}")}):k.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(Q,n)})}function R(e,t){var n=e.lastIndexOf("#?");if(-1==n)return Promise.resolve(e);var r=j(e.substr(n+2));return this.builder?this.normalize(r.module,t).then(function(t){return r.module=t,e.substr(0,n)+"#?"+_(r)}):k.call(this,r,t,!0).then(function(t){return t?e.substr(0,n):"@empty"})}var M="undefined"==typeof window&&"undefined"!=typeof self&&"undefined"!=typeof importScripts,O="undefined"!=typeof window&&"undefined"!=typeof document,z="undefined"!=typeof process&&"undefined"!=typeof process.platform&&!!process.platform.match(/^win/);e.console||(e.console={assert:function(){}});var T,I=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",{})&&(T=Object.defineProperty)}catch(e){T=function(e,t,n){try{e[t]=n.value||n.get.call(e)}catch(r){}}}}();var L;if("undefined"!=typeof document&&document.getElementsByTagName){if(L=document.baseURI,!L){var F=document.getElementsByTagName("base");L=F[0]&&F[0].href||window.location.href}L=L.split("#")[0].split("?")[0],L=L.substr(0,L.lastIndexOf("/")+1)}else if("undefined"!=typeof process&&process.cwd)L="file://"+(z?"/":"")+process.cwd()+"/",z&&(L=L.replace(/\\/g,"/"));else{if("undefined"==typeof location)throw new TypeError("No environment baseURI");L=e.location.href}var A=e.URLPolyfill||e.URL;T(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&&i.linkSets[0].loads[0].name==i.name))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{x(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==I.call(a.loaderObj.failed,n)&&a.loaderObj.failed.push(n);var c=I.call(n.linkSets,e);if(n.linkSets.splice(c,1),0==n.linkSets.length){var f=I.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=I.call(e.loads,t);-1!=r&&e.loads.splice(r,1);for(var a=0,o=t.linkSets.length;o>a;a++)r=I.call(t.linkSets[a].loads,t),-1!=r&&t.linkSets[a].loads.splice(r,1);t.linkSets.splice(0,t.linkSets.length)}function b(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 y(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 x(e,t){var n=e.loader;if(e.loads.length)for(var r=e.loads.concat([]),a=0;aa&&(n=o,a=r));return n}function t(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 n(e,t,n,r,a,o){if(!a||"/"==a[a.length-1]||o||t.defaultExtension===!1)return a;if(a.match(Q))return a;var s=!1;if(t.meta&&p(t.meta,a,function(e,t,n){return 0==n||e.lastIndexOf("*")!=e.length-1?s=!0:void 0}),!s&&e.meta&&p(e.meta,n+"/"+r+a,function(e,t,n){return 0==n||e.lastIndexOf("*")!=e.length-1?s=!0:void 0}),s)return a;var i="."+(t.defaultExtension||"js");return a.substr(a.length-i.length)!=i?a+i:a}function r(e,r,o,s,i){if(!s){if(!r.main)return o+(e.defaultJSExtensions?".js":"");s="./"==r.main.substr(0,2)?r.main.substr(2):r.main}var l=t(r);if(r.map){var u="./"+s,d=y(r.map,u);if(d||(u="./"+n(e,r,o,l,s,i),u!="./"+s&&(d=y(r.map,u))),d)return a(e,r,o,l,d,u,i)}return o+"/"+l+n(e,r,o,l,s,i)}function a(e,t,r,a,o,s,i){var l=t.map[o];if("string"!=typeof l&&(l=o=s),"."==l)l=r;else if("./"==l.substr(0,2))return r+"/"+a+n(e,t,r,a,l.substr(2)+s.substr(o.length),i);return e.normalizeSync(l+s.substr(o.length),r+"/")}function o(e,r,a,o,s){if(!o){if(!r.main)return Promise.resolve(a+(e.defaultJSExtensions?".js":""));o="./"==r.main.substr(0,2)?r.main.substr(2):r.main}var l,u,d=t(r);return r.map&&(l="./"+o,u=y(r.map,l),u||(l="./"+n(e,r,a,d,o,s),l!="./"+o&&(u=y(r.map,l)))),(u?i(e,r,a,d,u,l,s):Promise.resolve()).then(function(t){return t?Promise.resolve(t):Promise.resolve(a+"/"+d+n(e,r,a,d,o,s))})}function s(e,t,r,a,o,s,i,l){if("."==s)s=r;else if("./"==s.substr(0,2))return Promise.resolve(r+"/"+a+n(e,t,r,a,s.substr(2)+i.substr(o.length),l)).then(function(t){return P.call(e,t,r+"/")});return e.normalize(s+i.substr(o.length),r+"/")}function i(e,t,n,r,a,o,i){var l=t.map[a];return"string"==typeof l?s(e,t,n,r,a,l,o,i):e.builder?Promise.resolve(n+"/#:"+o):e["import"](t.map["@env"]||"@system-env",n).then(function(e){for(var t in l){var n="~"==t[0],r=v(n?t.substr(1):t,e);if(!n&&r||n&&!r)return l[t]}}).then(function(l){return l?s(e,t,n,r,a,l,o,i):void 0})}function u(e){var t=e.lastIndexOf("*"),n=Math.max(t+1,e.lastIndexOf("/"));return{length:n,regEx:new RegExp("^("+e.substr(0,n).replace(/\*/g,"[^\\/]+")+")(\\/|$)"),wildcard:-1!=t}}function f(e,t){for(var n,r,a=!1,o=0;od&&(d=n),h(u,t,n&&d>n)}),u.alias&&"./"==u.alias.substr(0,2)&&(u.alias=o+u.alias.substr(1)),u.loader&&"./"==u.loader.substr(0,2)&&(u.loader=o+u.loader.substr(1)),h(r.metadata,u)}}return n})}})}(),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=I.call(o.dependencies,s);o.setters[l](i)}}return s.locked=!1,t},{id:t.name});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 b=h[g];s.setters[b]&&s.setters[b](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==I.call(n,i)&&(r.defined[i]?u(i,n,r):r.get(i))}a.evaluated||(a.evaluated=!0,a.module.execute.call(e))}}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=E();r.name=e&&(this.decanonicalize||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=E();a.name=e&&(this.decanonicalize||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={}}}),T(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)}}),d("fetch",function(e){return function(t){return this.defined[t.name]?(t.metadata.format="defined",""):(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&&S(t.source))&&(t.metadata.format="register"),e})}}),d("instantiate",function(e){return function(t){"detect"==t.metadata.format&&(t.metadata.format=void 0),e.call(this,t);var r,a=this;if(a.defined[t.name])r=a.defined[t.name],r.declarative||(r.deps=r.deps.concat(t.metadata.deps));else if(t.metadata.entry)r=t.metadata.entry,r.deps=r.deps.concat(t.metadata.deps);else if(!(a.builder&&t.metadata.bundle||"register"!=t.metadata.format&&"esm"!=t.metadata.format&&"es6"!=t.metadata.format)){if("undefined"!=typeof B&&B.call(a,t),!t.metadata.entry&&!t.metadata.bundle)throw new Error(t.name+" detected as "+t.metadata.format+" but didn't execute.");r=t.metadata.entry,r&&t.metadata.deps&&(r.deps=r.deps.concat(t.metadata.deps))}r||(r=E(),r.deps=t.metadata.deps,r.execute=function(){}),a.defined[t.name]=r;var o=f(r.deps);r.deps=o.names,r.originalIndices=o.indices,r.name=t.name,r.esmExports=t.metadata.esmExports!==!1;for(var s=[],i=0,l=r.deps.length;l>i;i++)s.push(Promise.resolve(a.normalize(r.deps[i],t.name)));return Promise.all(s).then(function(e){return r.normalizedDeps=e,{deps:r.deps,execute:function(){return n(t.name,a),u(t.name,[],a),a.defined[t.name]=void 0,a.newModule(r.declarative?r.module.exports:r.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&&s.transpiler!==!1&&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){if(s.builder)return a;throw new TypeError("Unable to dynamically transpile ES module as SystemJS.transpiler set to false.")}return s._loader.loadedTranspiler=s._loader.loadedTranspiler||!1,s.pluginLoader&&(s.pluginLoader._loader.loadedTranspiler=s._loader.loadedTranspiler||!1),(s._loader.transpilerPromise||(s._loader.transpilerPromise=Promise.resolve(e["typescript"==s.transpiler?"ts":s.transpiler]||(s.pluginLoader||s)["import"](s.transpiler)))).then(function(e){return s._loader.loadedTranspilerRuntime=!0,e.translate?e==o.metadata.loaderModule?o.source:("string"==typeof o.metadata.sourceMap&&(o.metadata.sourceMap=JSON.parse(o.metadata.sourceMap)),Promise.resolve(e.translate.call(s,o)).then(function(e){var t=o.metadata.sourceMap;if(t&&"object"==typeof t){var n=o.name.split("!")[0];t.file=n+"!transpiled",(!t.sources||t.sources.length<=1)&&(t.sources=[n])}return"esm"==o.metadata.format&&!s.builder&&S(e)&&(o.metadata.format="register"),e})):(s.builder&&(o.metadata.originalSource=o.source),U.call(s,o).then(function(e){return o.metadata.sourceMap=void 0,e}))})}if(s.transpiler===!1)return a;if(s._loader.loadedTranspiler!==!1||"traceur"!=s.transpiler&&"typescript"!=s.transpiler&&"babel"!=s.transpiler||o.name!=s.normalizeSync(s.transpiler)||(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._loader.loadedTranspiler=!0),s._loader.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._loader.loadedTranspilerRuntime=!0),("register"==o.metadata.format||o.metadata.bundle)&&s._loader.loadedTranspilerRuntime!==!0){if(!e.$traceurRuntime&&o.source.match(n))return s._loader.loadedTranspilerRuntime=s._loader.loadedTranspilerRuntime||!1,s["import"]("traceur-runtime").then(function(){return a});if(!e.babelHelpers&&o.source.match(r))return s._loader.loadedTranspilerRuntime=s._loader.loadedTranspilerRuntime||!1,s["import"]("babel/external-helpers").then(function(){return a})}return a})}})}();var Y="undefined"!=typeof self?"self":"global";d("fetch",function(e){return function(t){return t.metadata.exports&&!t.metadata.format&&(t.metadata.format="global"),e.call(this,t)}}),d("instantiate",function(e){return function(t){var n=this;if(t.metadata.format||(t.metadata.format="global"),"global"==t.metadata.format&&!t.metadata.registered){var r=E();t.metadata.entry=r,r.deps=[];for(var a in t.metadata.globals){var o=t.metadata.globals[a];o&&r.deps.push(o)}r.execute=function(e,r,a){var o;if(t.metadata.globals){o={};for(var s in t.metadata.globals)t.metadata.globals[s]&&(o[s]=e(t.metadata.globals[s]))}var i=t.metadata.exports;i&&(t.source+="\n"+Y+'["'+i+'"] = '+i+";");var l=n.get("@@global-helpers").prepareGlobal(a.id,i,o);return B.call(n,t),l()}}return e.call(this,t)}}),d("reduceRegister_",function(t){return function(n,r){if(r||!n.metadata.exports)return t.call(this,n,r);n.metadata.format="global";var a=n.metadata.entry=E();a.deps=n.metadata.deps;var o=v(n.metadata.exports,e);a.execute=function(){return o}}}),c(function(t){return function(){function n(t){if(Object.keys)Object.keys(e).forEach(t);else for(var n in e)s.call(e,n)&&t(n)}function r(t){n(function(n){if(-1==I.call(i,n)){try{var r=e[n]}catch(a){i.push(n)}t(n,r)}})}var a=this;t.call(a);var o,s=Object.prototype.hasOwnProperty,i=["_g","sessionStorage","localStorage","clipboardData","frames","frameElement","external","mozAnimationStartTime","webkitStorageInfo","webkitIndexedDB","mozInnerScreenY","mozInnerScreenX"];a.set("@@global-helpers",a.newModule({prepareGlobal:function(t,n,a){var s=e.define;e.define=void 0,e.exports=void 0,e.module&&e.module.exports&&(e.module=void 0);var i;if(a){i={};for(var l in a)i[l]=e[l],e[l]=a[l]}return n||(o={},r(function(e,t){o[e]=t})),function(){var t;if(n)t=v(n,e);else{var a,l,u={};r(function(e,t){o[e]!==t&&"undefined"!=typeof t&&(u[e]=t,"undefined"!=typeof a?l||a===t||(l=!0):a=t)}),t=l?u:a}if(i)for(var d in i)e[d]=i[d];return e.define=s,t}}}))}}),function(){function t(e){function t(e,t){for(var n=0;nt.index)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)||l.push([n.index,n.index+n[0].length])}for(;n=r.exec(e);)if(!t(i,n)&&!t(l,n)){var u=n[1].substr(1,n[1].length-2);if(u.match(/"|'/))continue;"/"==u[u.length-1]&&(u=u.substr(0,u.length-1)),s.push(u)}return s}var n=/(?:^\uFEFF?|[^$_a-zA-Z\xA0-\uFFFF.])(exports\s*(\[['"]|\.)|module(\.exports|\['exports'\]|\["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;d("instantiate",function(a){return function(o){var s=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 i=o.metadata.deps,l=o.metadata.cjsRequireDetection===!1?[]:t(o.source);for(var u in o.metadata.globals)o.metadata.globals[u]&&l.push(o.metadata.globals[u]);var d=E();o.metadata.entry=d,d.deps=l,d.executingRequire=!0,d.execute=function(t,n,r){function a(e){return"/"==e[e.length-1]&&(e=e.substr(0,e.length-1)),t.apply(this,arguments)}for(var l=0;l1;)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 index f8e546dcb..a483a0620 100644 --- a/testapp/ng2/lib/typescript/lib/typescript.js +++ b/testapp/ng2/lib/typescript/lib/typescript.js @@ -13,6 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ +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) { // token > SyntaxKind.Identifer => token is a keyword @@ -163,180 +168,183 @@ var ts; SyntaxKind[SyntaxKind["SymbolKeyword"] = 131] = "SymbolKeyword"; SyntaxKind[SyntaxKind["TypeKeyword"] = 132] = "TypeKeyword"; SyntaxKind[SyntaxKind["FromKeyword"] = 133] = "FromKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 134] = "OfKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 134] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 135] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 135] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 136] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 136] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 137] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 137] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 138] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 139] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 138] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 139] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 140] = "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"; + SyntaxKind[SyntaxKind["PropertySignature"] = 141] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 142] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 143] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 144] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 145] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 146] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 147] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 148] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 149] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 150] = "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"; + SyntaxKind[SyntaxKind["TypePredicate"] = 151] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 152] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 153] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 154] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 155] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 156] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 157] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 158] = "TupleType"; + SyntaxKind[SyntaxKind["UnionType"] = 159] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 160] = "IntersectionType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 161] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 162] = "ThisType"; + SyntaxKind[SyntaxKind["StringLiteralType"] = 163] = "StringLiteralType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 161] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 162] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 163] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 164] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 165] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 166] = "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"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 167] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 168] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 169] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 170] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 171] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 172] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 173] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 174] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 175] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 176] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 177] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 178] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 179] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 180] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 181] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 182] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 183] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 184] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 185] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 186] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 187] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElementExpression"] = 188] = "SpreadElementExpression"; + SyntaxKind[SyntaxKind["ClassExpression"] = 189] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 190] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 191] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 192] = "AsExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 190] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 191] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 193] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 194] = "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"; + SyntaxKind[SyntaxKind["Block"] = 195] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 196] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 197] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 198] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 199] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 200] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 201] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 202] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 203] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 204] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 205] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 206] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 207] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 208] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 209] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 210] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 211] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 212] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 213] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 214] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 215] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 216] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 217] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 218] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 219] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 220] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 221] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 222] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 223] = "CaseBlock"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 224] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 225] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 226] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 227] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 228] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 229] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 230] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 231] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 232] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 233] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 234] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 232] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 235] = "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"; + SyntaxKind[SyntaxKind["JsxElement"] = 236] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 237] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 238] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxText"] = 239] = "JsxText"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 240] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 241] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 242] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 243] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 241] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 242] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 243] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 244] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 244] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 245] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 246] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 247] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 245] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 246] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 248] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 249] = "ShorthandPropertyAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 247] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 250] = "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"; + SyntaxKind[SyntaxKind["SourceFile"] = 251] = "SourceFile"; + // JSDoc nodes + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 252] = "JSDocTypeExpression"; + // The * type + SyntaxKind[SyntaxKind["JSDocAllType"] = 253] = "JSDocAllType"; + // The ? type + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 254] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocArrayType"] = 255] = "JSDocArrayType"; + SyntaxKind[SyntaxKind["JSDocUnionType"] = 256] = "JSDocUnionType"; + SyntaxKind[SyntaxKind["JSDocTupleType"] = 257] = "JSDocTupleType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 258] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 259] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocRecordType"] = 260] = "JSDocRecordType"; + SyntaxKind[SyntaxKind["JSDocRecordMember"] = 261] = "JSDocRecordMember"; + SyntaxKind[SyntaxKind["JSDocTypeReference"] = 262] = "JSDocTypeReference"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 263] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 264] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 265] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocConstructorType"] = 266] = "JSDocConstructorType"; + SyntaxKind[SyntaxKind["JSDocThisType"] = 267] = "JSDocThisType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 268] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 269] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 270] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 271] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 272] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 273] = "JSDocTemplateTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 271] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 274] = "SyntaxList"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 272] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 275] = "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["LastKeyword"] = 135] = "LastKeyword"; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 106] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 114] = "LastFutureReservedWord"; SyntaxKind[SyntaxKind["FirstTypeNode"] = 151] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 160] = "LastTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 163] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 15] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 68] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 134] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 135] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; @@ -345,31 +353,41 @@ var ts; SyntaxKind[SyntaxKind["LastTemplateToken"] = 14] = "LastTemplateToken"; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 25] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 68] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 135] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstNode"] = 136] = "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"; + NodeFlags[NodeFlags["None"] = 0] = "None"; + NodeFlags[NodeFlags["Export"] = 2] = "Export"; + NodeFlags[NodeFlags["Ambient"] = 4] = "Ambient"; + NodeFlags[NodeFlags["Public"] = 8] = "Public"; + NodeFlags[NodeFlags["Private"] = 16] = "Private"; + NodeFlags[NodeFlags["Protected"] = 32] = "Protected"; + NodeFlags[NodeFlags["Static"] = 64] = "Static"; + NodeFlags[NodeFlags["Abstract"] = 128] = "Abstract"; + NodeFlags[NodeFlags["Async"] = 256] = "Async"; + NodeFlags[NodeFlags["Default"] = 512] = "Default"; + NodeFlags[NodeFlags["MultiLine"] = 1024] = "MultiLine"; + NodeFlags[NodeFlags["Synthetic"] = 2048] = "Synthetic"; + NodeFlags[NodeFlags["DeclarationFile"] = 4096] = "DeclarationFile"; + NodeFlags[NodeFlags["Let"] = 8192] = "Let"; + NodeFlags[NodeFlags["Const"] = 16384] = "Const"; + NodeFlags[NodeFlags["OctalLiteral"] = 32768] = "OctalLiteral"; + NodeFlags[NodeFlags["Namespace"] = 65536] = "Namespace"; + NodeFlags[NodeFlags["ExportContext"] = 131072] = "ExportContext"; + NodeFlags[NodeFlags["ContainsThis"] = 262144] = "ContainsThis"; + NodeFlags[NodeFlags["HasImplicitReturn"] = 524288] = "HasImplicitReturn"; + NodeFlags[NodeFlags["HasExplicitReturn"] = 1048576] = "HasExplicitReturn"; + NodeFlags[NodeFlags["GlobalAugmentation"] = 2097152] = "GlobalAugmentation"; + NodeFlags[NodeFlags["HasClassExtends"] = 4194304] = "HasClassExtends"; + NodeFlags[NodeFlags["HasDecorators"] = 8388608] = "HasDecorators"; + NodeFlags[NodeFlags["HasParamDecorators"] = 16777216] = "HasParamDecorators"; + NodeFlags[NodeFlags["HasAsyncFunctions"] = 33554432] = "HasAsyncFunctions"; + NodeFlags[NodeFlags["Modifier"] = 1022] = "Modifier"; + NodeFlags[NodeFlags["AccessibilityModifier"] = 56] = "AccessibilityModifier"; + NodeFlags[NodeFlags["BlockScoped"] = 24576] = "BlockScoped"; + NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 1572864] = "ReachabilityCheckFlags"; + NodeFlags[NodeFlags["EmitHelperFlags"] = 62914560] = "EmitHelperFlags"; })(ts.NodeFlags || (ts.NodeFlags = {})); var NodeFlags = ts.NodeFlags; /* @internal */ @@ -404,10 +422,14 @@ var ts; var ParserContextFlags = ts.ParserContextFlags; (function (JsxFlags) { JsxFlags[JsxFlags["None"] = 0] = "None"; + /** An element from a named property of the JSX.IntrinsicElements interface */ JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement"; + /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement"; - JsxFlags[JsxFlags["ClassElement"] = 4] = "ClassElement"; - JsxFlags[JsxFlags["UnknownElement"] = 8] = "UnknownElement"; + /** An element backed by a class, class-like, or function value */ + JsxFlags[JsxFlags["ValueElement"] = 4] = "ValueElement"; + /** Element resolution failed */ + JsxFlags[JsxFlags["UnknownElement"] = 16] = "UnknownElement"; JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement"; })(ts.JsxFlags || (ts.JsxFlags = {})); var JsxFlags = ts.JsxFlags; @@ -422,7 +444,7 @@ var ts; function OperationCanceledException() { } return OperationCanceledException; - })(); + }()); ts.OperationCanceledException = OperationCanceledException; /** Return code used by getEmitOutput function to indicate status of the function */ (function (ExitStatus) { @@ -468,6 +490,11 @@ var ts; SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; })(ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); var SymbolAccessibility = ts.SymbolAccessibility; + (function (TypePredicateKind) { + TypePredicateKind[TypePredicateKind["This"] = 0] = "This"; + TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier"; + })(ts.TypePredicateKind || (ts.TypePredicateKind = {})); + var TypePredicateKind = ts.TypePredicateKind; /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator * metadata */ /* @internal */ @@ -569,20 +596,21 @@ var ts; 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"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; + NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "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["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; + NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; })(ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var NodeCheckFlags = ts.NodeCheckFlags; (function (TypeFlags) { @@ -617,6 +645,7 @@ var ts; TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 8388608] = "ContainsAnyFunctionType"; TypeFlags[TypeFlags["ESSymbol"] = 16777216] = "ESSymbol"; TypeFlags[TypeFlags["ThisType"] = 33554432] = "ThisType"; + TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 67108864] = "ObjectLiteralPatternWithComputedProperties"; /* @internal */ TypeFlags[TypeFlags["Intrinsic"] = 16777343] = "Intrinsic"; /* @internal */ @@ -642,6 +671,19 @@ var ts; IndexKind[IndexKind["Number"] = 1] = "Number"; })(ts.IndexKind || (ts.IndexKind = {})); var IndexKind = ts.IndexKind; + /* @internal */ + (function (SpecialPropertyAssignmentKind) { + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + /// exports.name = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + /// module.exports = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + /// className.prototype.name = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + /// this.name = expr + SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + })(ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + var SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; @@ -688,6 +730,12 @@ var ts; })(ts.LanguageVariant || (ts.LanguageVariant = {})); var LanguageVariant = ts.LanguageVariant; /* @internal */ + (function (DiagnosticStyle) { + DiagnosticStyle[DiagnosticStyle["Simple"] = 0] = "Simple"; + DiagnosticStyle[DiagnosticStyle["Pretty"] = 1] = "Pretty"; + })(ts.DiagnosticStyle || (ts.DiagnosticStyle = {})); + var DiagnosticStyle = ts.DiagnosticStyle; + /* @internal */ (function (CharacterCodes) { CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; @@ -836,40 +884,50 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(ts.Ternary || (ts.Ternary = {})); var Ternary = ts.Ternary; - function createFileMap(getCanonicalFileName) { + function createFileMap(keyMapper) { var files = {}; return { get: get, set: set, contains: contains, remove: remove, - clear: clear, - forEachValue: forEachValueInMap + forEachValue: forEachValueInMap, + clear: clear }; - function set(fileName, value) { - files[normalizeKey(fileName)] = value; - } - function get(fileName) { - return files[normalizeKey(fileName)]; + function forEachValueInMap(f) { + for (var key in files) { + f(key, files[key]); + } } - function contains(fileName) { - return hasProperty(files, normalizeKey(fileName)); + // path should already be well-formed so it does not need to be normalized + function get(path) { + return files[toKey(path)]; } - function remove(fileName) { - var key = normalizeKey(fileName); - delete files[key]; + function set(path, value) { + files[toKey(path)] = value; } - function forEachValueInMap(f) { - forEachValue(files, f); + function contains(path) { + return hasProperty(files, toKey(path)); } - function normalizeKey(key) { - return getCanonicalFileName(normalizeSlashes(key)); + function remove(path) { + var key = toKey(path); + delete files[key]; } function clear() { files = {}; } + function toKey(path) { + return keyMapper ? keyMapper(path) : path; + } } ts.createFileMap = createFileMap; + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; (function (Comparison) { Comparison[Comparison["LessThan"] = -1] = "LessThan"; Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; @@ -895,8 +953,8 @@ var ts; ts.forEach = forEach; function contains(array, value) { if (array) { - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { + var v = array_1[_i]; if (v === value) { return true; } @@ -919,8 +977,8 @@ var ts; function countWhere(array, predicate) { var count = 0; if (array) { - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; if (predicate(v)) { count++; } @@ -933,8 +991,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0; _i < array.length; _i++) { - var item = array[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var item = array_3[_i]; if (f(item)) { result.push(item); } @@ -947,8 +1005,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var v = array_4[_i]; result.push(f(v)); } } @@ -967,8 +1025,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0; _i < array.length; _i++) { - var item = array[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var item = array_5[_i]; if (!contains(result, item)) { result.push(item); } @@ -979,8 +1037,8 @@ var ts; ts.deduplicate = deduplicate; function sum(array, prop) { var result = 0; - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var v = array_6[_i]; result += v[prop]; } return result; @@ -988,8 +1046,8 @@ var ts; ts.sum = sum; function addRange(to, from) { if (to && from) { - for (var _i = 0; _i < from.length; _i++) { - var v = from[_i]; + for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { + var v = from_1[_i]; to.push(v); } } @@ -1046,9 +1104,11 @@ var ts; var count = array.length; if (count > 0) { var pos = 0; - var result = arguments.length <= 2 ? array[pos++] : initial; + var result = arguments.length <= 2 ? array[pos] : initial; + pos++; while (pos < count) { - result = f(result, array[pos++]); + result = f(result, array[pos]); + pos++; } return result; } @@ -1060,9 +1120,11 @@ var ts; if (array) { var pos = array.length - 1; if (pos >= 0) { - var result = arguments.length <= 2 ? array[pos--] : initial; + var result = arguments.length <= 2 ? array[pos] : initial; + pos--; while (pos >= 0) { - result = f(result, array[pos--]); + result = f(result, array[pos]); + pos--; } return result; } @@ -1155,6 +1217,32 @@ var ts; return result; } ts.arrayToMap = arrayToMap; + /** + * Reduce the properties of a map. + * + * @param map The map to reduce + * @param callback An aggregation function that is called for each entry in the map + * @param initial The initial value for the reduction. + */ + function reduceProperties(map, callback, initial) { + var result = initial; + if (map) { + for (var key in map) { + if (hasProperty(map, key)) { + result = callback(result, map[key], String(key)); + } + } + } + return result; + } + ts.reduceProperties = reduceProperties; + /** + * Tests whether a value is an array. + */ + function isArray(value) { + return Array.isArray ? Array.isArray(value) : value instanceof Array; + } + ts.isArray = isArray; function memoize(callback) { var value; return function () { @@ -1172,9 +1260,9 @@ var ts; } ts.localizedDiagnosticMessages = undefined; function getLocaleSpecificMessage(message) { - return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message] - ? ts.localizedDiagnosticMessages[message] - : message; + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] + ? ts.localizedDiagnosticMessages[message.key] + : message.message; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createFileDiagnostic(file, start, length, message) { @@ -1185,7 +1273,7 @@ var ts; 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); + var text = getLocaleSpecificMessage(message); if (arguments.length > 4) { text = formatStringFromArgs(text, arguments, 4); } @@ -1200,7 +1288,7 @@ var ts; } ts.createFileDiagnostic = createFileDiagnostic; function createCompilerDiagnostic(message) { - var text = getLocaleSpecificMessage(message.key); + var text = getLocaleSpecificMessage(message); if (arguments.length > 1) { text = formatStringFromArgs(text, arguments, 1); } @@ -1215,7 +1303,7 @@ var ts; } ts.createCompilerDiagnostic = createCompilerDiagnostic; function chainDiagnosticMessages(details, message) { - var text = getLocaleSpecificMessage(message.key); + var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { text = formatStringFromArgs(text, arguments, 2); } @@ -1339,8 +1427,8 @@ var ts; 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]; + for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) { + var part = parts_1[_i]; if (part !== ".") { if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { normalized.pop(); @@ -1455,7 +1543,8 @@ var ts; directoryComponents.length--; } // Find the component that differs - for (var joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { + var joinStartIndex; + for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) { break; } @@ -1480,7 +1569,7 @@ var ts; } ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; function getBaseFileName(path) { - if (!path) { + if (path === undefined) { return undefined; } var i = path.lastIndexOf(ts.directorySeparator); @@ -1508,19 +1597,19 @@ var ts; /** * 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) { + ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; + ts.supportedJavascriptExtensions = [".js", ".jsx"]; + var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + function getSupportedExtensions(options) { + return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + ts.getSupportedExtensions = getSupportedExtensions; + function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; } - for (var _i = 0; _i < ts.supportedExtensions.length; _i++) { - var extension = ts.supportedExtensions[_i]; + for (var _i = 0, _a = getSupportedExtensions(compilerOptions); _i < _a.length; _i++) { + var extension = _a[_i]; if (fileExtensionIs(fileName, extension)) { return true; } @@ -1530,8 +1619,8 @@ var ts; 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]; + for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { + var ext = extensionsToRemove_1[_i]; if (fileExtensionIs(path, ext)) { return path.substr(0, path.length - ext.length); } @@ -1539,22 +1628,6 @@ var ts; 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; @@ -1565,19 +1638,16 @@ var ts; } function Signature(checker) { } + function Node(kind, pos, end) { + this.kind = kind; + this.pos = pos; + this.end = end; + this.flags = 0 /* None */; + this.parent = undefined; + } ts.objectAllocator = { - getNodeConstructor: function (kind) { - function Node() { - } - Node.prototype = { - kind: kind, - pos: -1, - end: -1, - flags: 0, - parent: undefined - }; - return Node; - }, + getNodeConstructor: function () { return Node; }, + getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, getSignatureConstructor: function () { return Signature; } @@ -1602,25 +1672,33 @@ var ts; if (verboseDebugInfo) { verboseDebugString = "\r\nVerbose Debug Information: " + verboseDebugInfo(); } + debugger; throw new Error("Debug Failure. False expression: " + (message || "") + verboseDebugString); } } Debug.assert = assert; function fail(message) { - Debug.assert(false, message); + Debug.assert(/*expression*/ 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]); + for (var _i = 0, list_1 = list; _i < list_1.length; _i++) { + var e = list_1[_i]; + if (e !== item) { + copiedList.push(e); } } return copiedList; } ts.copyListRemovingItem = copyListRemovingItem; + function createGetCanonicalFileName(useCaseSensitivefileNames) { + return useCaseSensitivefileNames + ? (function (fileName) { return fileName; }) + : (function (fileName) { return fileName.toLowerCase(); }); + } + ts.createGetCanonicalFileName = createGetCanonicalFileName; })(ts || (ts = {})); /// var ts; @@ -1707,16 +1785,16 @@ var ts; 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]; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var current = files_1[_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]; + for (var _a = 0, subfolders_1 = subfolders; _a < subfolders_1.length; _a++) { + var current = subfolders_1[_a]; var name_2 = ts.combinePaths(path, current); if (!ts.contains(exclude, getCanonicalPath(name_2))) { visitDirectory(name_2); @@ -1769,7 +1847,7 @@ var ts; 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) { + function createPollingWatchedFileSet(interval, chunkSize) { if (interval === void 0) { interval = 2500; } if (chunkSize === void 0) { chunkSize = 30; } var watchedFiles = []; @@ -1783,13 +1861,13 @@ var ts; if (!watchedFile) { return; } - _fs.stat(watchedFile.fileName, function (err, stats) { + _fs.stat(watchedFile.filePath, function (err, stats) { if (err) { - watchedFile.callback(watchedFile.fileName); + watchedFile.callback(watchedFile.filePath); } else if (watchedFile.mtime.getTime() !== stats.mtime.getTime()) { - watchedFile.mtime = getModifiedTime(watchedFile.fileName); - watchedFile.callback(watchedFile.fileName, watchedFile.mtime.getTime() === 0); + watchedFile.mtime = getModifiedTime(watchedFile.filePath); + watchedFile.callback(watchedFile.filePath, watchedFile.mtime.getTime() === 0); } }); } @@ -1815,11 +1893,11 @@ var ts; nextFileToCheck = nextToCheck; }, interval); } - function addFile(fileName, callback) { + function addFile(filePath, callback) { var file = { - fileName: fileName, + filePath: filePath, callback: callback, - mtime: getModifiedTime(fileName) + mtime: getModifiedTime(filePath) }; watchedFiles.push(file); if (watchedFiles.length === 1) { @@ -1838,10 +1916,82 @@ var ts; removeFile: removeFile }; } + function createWatchedFileSet() { + var dirWatchers = ts.createFileMap(); + // One file can have multiple watchers + var fileWatcherCallbacks = ts.createFileMap(); + return { addFile: addFile, removeFile: removeFile }; + function reduceDirWatcherRefCountForFile(filePath) { + var dirPath = ts.getDirectoryPath(filePath); + if (dirWatchers.contains(dirPath)) { + var watcher = dirWatchers.get(dirPath); + watcher.referenceCount -= 1; + if (watcher.referenceCount <= 0) { + watcher.close(); + dirWatchers.remove(dirPath); + } + } + } + function addDirWatcher(dirPath) { + if (dirWatchers.contains(dirPath)) { + var watcher_1 = dirWatchers.get(dirPath); + watcher_1.referenceCount += 1; + return; + } + var watcher = _fs.watch(dirPath, { persistent: true }, function (eventName, relativeFileName) { return fileEventHandler(eventName, relativeFileName, dirPath); }); + watcher.referenceCount = 1; + dirWatchers.set(dirPath, watcher); + return; + } + function addFileWatcherCallback(filePath, callback) { + if (fileWatcherCallbacks.contains(filePath)) { + fileWatcherCallbacks.get(filePath).push(callback); + } + else { + fileWatcherCallbacks.set(filePath, [callback]); + } + } + function addFile(filePath, callback) { + addFileWatcherCallback(filePath, callback); + addDirWatcher(ts.getDirectoryPath(filePath)); + return { filePath: filePath, callback: callback }; + } + function removeFile(watchedFile) { + removeFileWatcherCallback(watchedFile.filePath, watchedFile.callback); + reduceDirWatcherRefCountForFile(watchedFile.filePath); + } + function removeFileWatcherCallback(filePath, callback) { + if (fileWatcherCallbacks.contains(filePath)) { + var newCallbacks = ts.copyListRemovingItem(callback, fileWatcherCallbacks.get(filePath)); + if (newCallbacks.length === 0) { + fileWatcherCallbacks.remove(filePath); + } + else { + fileWatcherCallbacks.set(filePath, newCallbacks); + } + } + } + /** + * @param watcherPath is the path from which the watcher is triggered. + */ + function fileEventHandler(eventName, relativeFileName, baseDirPath) { + // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" + var filePath = typeof relativeFileName !== "string" + ? undefined + : ts.toPath(relativeFileName, baseDirPath, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)); + // Some applications save a working file via rename operations + if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks.contains(filePath)) { + for (var _i = 0, _a = fileWatcherCallbacks.get(filePath); _i < _a.length; _i++) { + var fileCallback = _a[_i]; + fileCallback(filePath); + } + } + } + } // 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 + // 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 @@ -1851,6 +2001,7 @@ var ts; // 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 pollingWatchedFileSet = createPollingWatchedFileSet(); var watchedFileSet = createWatchedFileSet(); function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; @@ -1891,10 +2042,19 @@ var ts; if (writeByteOrderMark) { data = "\uFEFF" + data; } - _fs.writeFileSync(fileName, data, "utf8"); + var fd; + try { + fd = _fs.openSync(fileName, "w"); + _fs.writeSync(fd, data, undefined, "utf8"); + } + finally { + if (fd !== undefined) { + _fs.closeSync(fd); + } + } } function getCanonicalPath(path) { - return useCaseSensitiveFileNames ? path.toLowerCase() : path; + return useCaseSensitiveFileNames ? path : path.toLowerCase(); } function readDirectory(path, extension, exclude) { var result = []; @@ -1904,8 +2064,8 @@ var ts; function visitDirectory(path) { var files = _fs.readdirSync(path || ".").sort(); var directories = []; - for (var _i = 0; _i < files.length; _i++) { - var current = files[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var current = files_2[_i]; var name_3 = ts.combinePaths(path, current); if (!ts.contains(exclude, getCanonicalPath(name_3))) { var stat = _fs.statSync(name_3); @@ -1919,8 +2079,8 @@ var ts; } } } - for (var _a = 0; _a < directories.length; _a++) { - var current = directories[_a]; + for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { + var current = directories_1[_a]; visitDirectory(current); } } @@ -1930,32 +2090,32 @@ var ts; 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; - } + process.stdout.write(s); }, readFile: readFile, writeFile: writeFile, - watchFile: function (fileName, callback) { + watchFile: function (filePath, 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); + var watchSet = isNode4OrLater() ? watchedFileSet : pollingWatchedFileSet; + var watchedFile = watchSet.addFile(filePath, callback); return { - close: function () { return watchedFileSet.removeFile(watchedFile); } + close: function () { return watchSet.removeFile(watchedFile); } }; }, watchDirectory: function (path, callback, recursive) { - // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows + // 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) { + var options; + if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { + options = { persistent: true, recursive: !!recursive }; + } + else { + options = { persistent: true }; + } + return _fs.watch(path, options, 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") @@ -1998,6 +2158,33 @@ var ts; } }; } + function getChakraSystem() { + return { + newLine: ChakraHost.newLine || "\r\n", + args: ChakraHost.args, + useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, + write: ChakraHost.echo, + readFile: function (path, encoding) { + // encoding is automatically handled by the implementation in ChakraHost + return ChakraHost.readFile(path); + }, + writeFile: function (path, data, writeByteOrderMark) { + // If a BOM is required, emit one + if (writeByteOrderMark) { + data = "\uFEFF" + data; + } + ChakraHost.writeFile(path, data); + }, + resolvePath: ChakraHost.resolvePath, + fileExists: ChakraHost.fileExists, + directoryExists: ChakraHost.directoryExists, + createDirectory: ChakraHost.createDirectory, + getExecutingFilePath: function () { return ChakraHost.executingFile; }, + getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, + readDirectory: ChakraHost.readDirectory, + exit: ChakraHost.quit + }; + } if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { return getWScriptSystem(); } @@ -2006,6 +2193,9 @@ var ts; // process.browser check excludes webpack and browserify return getNodeSystem(); } + else if (typeof ChakraHost !== "undefined") { + return getChakraSystem(); + } else { return undefined; // Unsupported host } @@ -2017,622 +2207,669 @@ var ts; 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." } + Unterminated_string_literal: { code: 1002, category: ts.DiagnosticCategory.Error, key: "Unterminated_string_literal_1002", message: "Unterminated string literal." }, + Identifier_expected: { code: 1003, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_1003", message: "Identifier expected." }, + _0_expected: { code: 1005, category: ts.DiagnosticCategory.Error, key: "_0_expected_1005", message: "'{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_1006", message: "A file cannot have a reference to itself." }, + Trailing_comma_not_allowed: { code: 1009, category: ts.DiagnosticCategory.Error, key: "Trailing_comma_not_allowed_1009", message: "Trailing comma not allowed." }, + Asterisk_Slash_expected: { code: 1010, category: ts.DiagnosticCategory.Error, key: "Asterisk_Slash_expected_1010", message: "'*/' expected." }, + Unexpected_token: { code: 1012, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_1012", message: "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_1014", message: "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_1015", message: "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_1016", message: "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_1017", message: "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_1018", message: "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_1019", message: "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_1020", message: "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_1021", message: "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_1022", message: "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_1023", message: "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_1028", message: "Accessibility modifier already seen." }, + _0_modifier_must_precede_1_modifier: { code: 1029, category: ts.DiagnosticCategory.Error, key: "_0_modifier_must_precede_1_modifier_1029", message: "'{0}' modifier must precede '{1}' modifier." }, + _0_modifier_already_seen: { code: 1030, category: ts.DiagnosticCategory.Error, key: "_0_modifier_already_seen_1030", message: "'{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_1031", message: "'{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_1034", message: "'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_1035", message: "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_1036", message: "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_1038", message: "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_1039", message: "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_1040", message: "'{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_1041", message: "'{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_1042", message: "'{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_1043", message: "'{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_1044", message: "'{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_1045", message: "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_1046", message: "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_1047", message: "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_1048", message: "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_1049", message: "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_1051", message: "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_1052", message: "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_1053", message: "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_1054", message: "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_1055", message: "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_1056", message: "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_1057", message: "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_1058", message: "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_1059", message: "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_1060", message: "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_1061", message: "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_1062", message: "{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_1063", message: "An export assignment cannot be used in a namespace." }, + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: { code: 1064, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", message: "The return type of an async function or method must be the global Promise type." }, + 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_1066", message: "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_1068", message: "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_1079", message: "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_1084", message: "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_1085", message: "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_1086", message: "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_1089", message: "'{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_1090", message: "'{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_1091", message: "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_1092", message: "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_1093", message: "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_1094", message: "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_1095", message: "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_1096", message: "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_1097", message: "'{0}' list cannot be empty." }, + Type_parameter_list_cannot_be_empty: { code: 1098, category: ts.DiagnosticCategory.Error, key: "Type_parameter_list_cannot_be_empty_1098", message: "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_1099", message: "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_1100", message: "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_1101", message: "'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_1102", message: "'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_1104", message: "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_1105", message: "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_1107", message: "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_1108", message: "A 'return' statement can only be used within a function body." }, + Expression_expected: { code: 1109, category: ts.DiagnosticCategory.Error, key: "Expression_expected_1109", message: "Expression expected." }, + Type_expected: { code: 1110, category: ts.DiagnosticCategory.Error, key: "Type_expected_1110", message: "Type expected." }, + A_class_member_cannot_be_declared_optional: { code: 1112, category: ts.DiagnosticCategory.Error, key: "A_class_member_cannot_be_declared_optional_1112", message: "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_1113", message: "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_1114", message: "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_1115", message: "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_1116", message: "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_1117", message: "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_Slashset_accessors_with_the_same_name_1118", message: "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_1119", message: "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_1120", message: "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_1121", message: "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_1122", message: "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_1123", message: "Variable declaration list cannot be empty." }, + Digit_expected: { code: 1124, category: ts.DiagnosticCategory.Error, key: "Digit_expected_1124", message: "Digit expected." }, + Hexadecimal_digit_expected: { code: 1125, category: ts.DiagnosticCategory.Error, key: "Hexadecimal_digit_expected_1125", message: "Hexadecimal digit expected." }, + Unexpected_end_of_text: { code: 1126, category: ts.DiagnosticCategory.Error, key: "Unexpected_end_of_text_1126", message: "Unexpected end of text." }, + Invalid_character: { code: 1127, category: ts.DiagnosticCategory.Error, key: "Invalid_character_1127", message: "Invalid character." }, + Declaration_or_statement_expected: { code: 1128, category: ts.DiagnosticCategory.Error, key: "Declaration_or_statement_expected_1128", message: "Declaration or statement expected." }, + Statement_expected: { code: 1129, category: ts.DiagnosticCategory.Error, key: "Statement_expected_1129", message: "Statement expected." }, + case_or_default_expected: { code: 1130, category: ts.DiagnosticCategory.Error, key: "case_or_default_expected_1130", message: "'case' or 'default' expected." }, + Property_or_signature_expected: { code: 1131, category: ts.DiagnosticCategory.Error, key: "Property_or_signature_expected_1131", message: "Property or signature expected." }, + Enum_member_expected: { code: 1132, category: ts.DiagnosticCategory.Error, key: "Enum_member_expected_1132", message: "Enum member expected." }, + Variable_declaration_expected: { code: 1134, category: ts.DiagnosticCategory.Error, key: "Variable_declaration_expected_1134", message: "Variable declaration expected." }, + Argument_expression_expected: { code: 1135, category: ts.DiagnosticCategory.Error, key: "Argument_expression_expected_1135", message: "Argument expression expected." }, + Property_assignment_expected: { code: 1136, category: ts.DiagnosticCategory.Error, key: "Property_assignment_expected_1136", message: "Property assignment expected." }, + Expression_or_comma_expected: { code: 1137, category: ts.DiagnosticCategory.Error, key: "Expression_or_comma_expected_1137", message: "Expression or comma expected." }, + Parameter_declaration_expected: { code: 1138, category: ts.DiagnosticCategory.Error, key: "Parameter_declaration_expected_1138", message: "Parameter declaration expected." }, + Type_parameter_declaration_expected: { code: 1139, category: ts.DiagnosticCategory.Error, key: "Type_parameter_declaration_expected_1139", message: "Type parameter declaration expected." }, + Type_argument_expected: { code: 1140, category: ts.DiagnosticCategory.Error, key: "Type_argument_expected_1140", message: "Type argument expected." }, + String_literal_expected: { code: 1141, category: ts.DiagnosticCategory.Error, key: "String_literal_expected_1141", message: "String literal expected." }, + Line_break_not_permitted_here: { code: 1142, category: ts.DiagnosticCategory.Error, key: "Line_break_not_permitted_here_1142", message: "Line break not permitted here." }, + or_expected: { code: 1144, category: ts.DiagnosticCategory.Error, key: "or_expected_1144", message: "'{' or ';' expected." }, + Modifiers_not_permitted_on_index_signature_members: { code: 1145, category: ts.DiagnosticCategory.Error, key: "Modifiers_not_permitted_on_index_signature_members_1145", message: "Modifiers not permitted on index signature members." }, + Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "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_1147", message: "Import declarations in a namespace cannot reference a module." }, + Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting__1148", message: "Cannot compile modules unless the '--module' flag is provided with a valid module type. Consider setting the 'module' compiler option in a 'tsconfig.json' file." }, + 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_1149", message: "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_T_instead_1150", message: "'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_1155", message: "'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_1156", message: "'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_1157", message: "'let' declarations can only be declared inside a block." }, + Unterminated_template_literal: { code: 1160, category: ts.DiagnosticCategory.Error, key: "Unterminated_template_literal_1160", message: "Unterminated template literal." }, + Unterminated_regular_expression_literal: { code: 1161, category: ts.DiagnosticCategory.Error, key: "Unterminated_regular_expression_literal_1161", message: "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_1162", message: "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_1163", message: "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_1164", message: "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_1165", message: "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_1166", message: "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_1168", message: "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_1169", message: "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_1170", message: "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_1171", message: "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_1172", message: "'extends' clause already seen." }, + extends_clause_must_precede_implements_clause: { code: 1173, category: ts.DiagnosticCategory.Error, key: "extends_clause_must_precede_implements_clause_1173", message: "'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_1174", message: "Classes can only extend a single class." }, + implements_clause_already_seen: { code: 1175, category: ts.DiagnosticCategory.Error, key: "implements_clause_already_seen_1175", message: "'implements' clause already seen." }, + Interface_declaration_cannot_have_implements_clause: { code: 1176, category: ts.DiagnosticCategory.Error, key: "Interface_declaration_cannot_have_implements_clause_1176", message: "Interface declaration cannot have 'implements' clause." }, + Binary_digit_expected: { code: 1177, category: ts.DiagnosticCategory.Error, key: "Binary_digit_expected_1177", message: "Binary digit expected." }, + Octal_digit_expected: { code: 1178, category: ts.DiagnosticCategory.Error, key: "Octal_digit_expected_1178", message: "Octal digit expected." }, + Unexpected_token_expected: { code: 1179, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_expected_1179", message: "Unexpected token. '{' expected." }, + Property_destructuring_pattern_expected: { code: 1180, category: ts.DiagnosticCategory.Error, key: "Property_destructuring_pattern_expected_1180", message: "Property destructuring pattern expected." }, + Array_element_destructuring_pattern_expected: { code: 1181, category: ts.DiagnosticCategory.Error, key: "Array_element_destructuring_pattern_expected_1181", message: "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_1182", message: "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_1183", message: "An implementation cannot be declared in ambient contexts." }, + Modifiers_cannot_appear_here: { code: 1184, category: ts.DiagnosticCategory.Error, key: "Modifiers_cannot_appear_here_1184", message: "Modifiers cannot appear here." }, + Merge_conflict_marker_encountered: { code: 1185, category: ts.DiagnosticCategory.Error, key: "Merge_conflict_marker_encountered_1185", message: "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_1186", message: "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_1187", message: "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_1188", message: "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_1189", message: "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_1190", message: "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_1191", message: "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_1192", message: "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_1193", message: "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_1194", message: "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_1195", message: "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_1196", message: "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_1197", message: "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_1198", message: "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_1199", message: "Unterminated Unicode escape sequence." }, + Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "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_Asterisk__1202", message: "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_o_1203", message: "Export assignment cannot be used when targeting ECMAScript 6 modules. Consider using 'export default' or another module format instead." }, + Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower: { code: 1204, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower_1204", message: "Cannot compile modules into 'es2015' when targeting 'ES5' or lower." }, + Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "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_Slashset_accessors_of_the_same_name_1207", message: "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_1208", message: "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_1209", message: "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_1210", message: "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_1211", message: "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_1212", message: "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_stric_1213", message: "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_1214", message: "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_1215", message: "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_1218", message: "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_Set_the_experimentalDecorators_option_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_Set_t_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option 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_1220", message: "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_1221", message: "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_1222", message: "An overload signature cannot be declared as a generator." }, + _0_tag_already_specified: { code: 1223, category: ts.DiagnosticCategory.Error, key: "_0_tag_already_specified_1223", message: "'{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_1224", message: "Signature '{0}' must have a type predicate." }, + Cannot_find_parameter_0: { code: 1225, category: ts.DiagnosticCategory.Error, key: "Cannot_find_parameter_0_1225", message: "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_1226", message: "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_1227", message: "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_1228", message: "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_1229", message: "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_1230", message: "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_1231", message: "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_1232", message: "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_1233", message: "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_1234", message: "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_1235", message: "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_1236", message: "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_1237", message: "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_1238", message: "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_1239", message: "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_1240", message: "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_1241", message: "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_1242", message: "'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_1243", message: "'{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_1244", message: "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_1245", message: "Method '{0}' cannot have an implementation because it is marked abstract." }, + An_interface_property_cannot_have_an_initializer: { code: 1246, category: ts.DiagnosticCategory.Error, key: "An_interface_property_cannot_have_an_initializer_1246", message: "An interface property cannot have an initializer." }, + A_type_literal_property_cannot_have_an_initializer: { code: 1247, category: ts.DiagnosticCategory.Error, key: "A_type_literal_property_cannot_have_an_initializer_1247", message: "A type literal property cannot have an initializer." }, + A_class_member_cannot_have_the_0_keyword: { code: 1248, category: ts.DiagnosticCategory.Error, key: "A_class_member_cannot_have_the_0_keyword_1248", message: "A class member cannot have the '{0}' keyword." }, + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: { code: 1249, category: ts.DiagnosticCategory.Error, key: "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", message: "A decorator can only decorate a method implementation, not an overload." }, + 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_1300", message: "'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_1308", message: "'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_1311", message: "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_1312", message: "'=' can only be used in an object literal property inside a destructuring assignment." }, + The_body_of_an_if_statement_cannot_be_the_empty_statement: { code: 1313, category: ts.DiagnosticCategory.Error, key: "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", message: "The body of an 'if' statement cannot be the empty statement." }, + Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "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_2301", message: "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_2302", message: "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_2303", message: "Circular definition of import alias '{0}'." }, + Cannot_find_name_0: { code: 2304, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_2304", message: "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_2305", message: "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_2306", message: "File '{0}' is not a module." }, + Cannot_find_module_0: { code: 2307, category: ts.DiagnosticCategory.Error, key: "Cannot_find_module_0_2307", message: "Cannot find module '{0}'." }, + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: { code: 2308, category: ts.DiagnosticCategory.Error, key: "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", message: "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity." }, + 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_2309", message: "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_2310", message: "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_2311", message: "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_2312", message: "An interface may only extend a class or another interface." }, + Type_parameter_0_has_a_circular_constraint: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_has_a_circular_constraint_2313", message: "Type parameter '{0}' has a circular constraint." }, + Generic_type_0_requires_1_type_argument_s: { code: 2314, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_1_type_argument_s_2314", message: "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_2315", message: "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_2316", message: "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_2317", message: "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_2318", message: "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_2319", message: "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_2320", message: "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_2321", message: "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_2322", message: "Type '{0}' is not assignable to type '{1}'." }, + Cannot_redeclare_exported_variable_0: { code: 2323, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_exported_variable_0_2323", message: "Cannot redeclare exported variable '{0}'." }, + Property_0_is_missing_in_type_1: { code: 2324, category: ts.DiagnosticCategory.Error, key: "Property_0_is_missing_in_type_1_2324", message: "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_2325", message: "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_2326", message: "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_2327", message: "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_2328", message: "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_2329", message: "Index signature is missing in type '{0}'." }, + Index_signatures_are_incompatible: { code: 2330, category: ts.DiagnosticCategory.Error, key: "Index_signatures_are_incompatible_2330", message: "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_2331", message: "'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_2332", message: "'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_2333", message: "'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_2334", message: "'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_2335", message: "'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_2336", message: "'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_2337", message: "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_der_2338", message: "'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_2339", message: "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_2340", message: "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_2341", message: "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_2342", message: "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_2344", message: "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_2345", message: "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_2346", message: "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_2347", message: "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_2348", message: "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_2349", message: "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_2350", message: "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_2351", message: "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_2352", message: "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_2353", message: "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_2354", message: "No best common type exists among return expressions." }, + A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, + 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_2356", message: "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_2357", message: "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_paramete_2358", message: "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_F_2359", message: "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_2360", message: "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_2361", message: "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_2362", message: "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_2363", message: "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_2364", message: "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_2365", message: "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_2368", message: "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_2369", message: "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_2370", message: "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_2371", message: "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_2372", message: "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_2373", message: "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_2374", message: "Duplicate string index signature." }, + Duplicate_number_index_signature: { code: 2375, category: ts.DiagnosticCategory.Error, key: "Duplicate_number_index_signature_2375", message: "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_proper_2376", message: "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_2377", message: "Constructors for derived classes must contain a 'super' call." }, + A_get_accessor_must_return_a_value: { code: 2378, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_must_return_a_value_2378", message: "A 'get' accessor must return a value." }, + 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_2379", message: "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_2380", message: "'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_2381", message: "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_2382", message: "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_2383", message: "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_2384", message: "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_2385", message: "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_2386", message: "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_2387", message: "Function overload must be static." }, + Function_overload_must_not_be_static: { code: 2388, category: ts.DiagnosticCategory.Error, key: "Function_overload_must_not_be_static_2388", message: "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_2389", message: "Function implementation name must be '{0}'." }, + Constructor_implementation_is_missing: { code: 2390, category: ts.DiagnosticCategory.Error, key: "Constructor_implementation_is_missing_2390", message: "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_2391", message: "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_2392", message: "Multiple constructor implementations are not allowed." }, + Duplicate_function_implementation: { code: 2393, category: ts.DiagnosticCategory.Error, key: "Duplicate_function_implementation_2393", message: "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_2394", message: "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_2395", message: "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_2396", message: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." }, + Declaration_name_conflicts_with_built_in_global_identifier_0: { code: 2397, category: ts.DiagnosticCategory.Error, key: "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", message: "Declaration name conflicts with built-in global identifier '{0}'." }, + 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_2399", message: "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_2400", message: "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_2401", message: "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_2402", message: "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_t_2403", message: "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_2404", message: "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_2405", message: "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_2406", message: "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_2407", message: "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_2408", message: "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_2409", message: "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_2410", message: "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_2411", message: "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_2412", message: "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_2413", message: "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_2414", message: "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_2415", message: "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_2417", message: "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_2419", message: "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_2420", message: "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_2422", message: "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_access_2423", message: "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_proper_2424", message: "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_functi_2425", message: "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_functi_2426", message: "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_2427", message: "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_2428", message: "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_2430", message: "Interface '{0}' incorrectly extends interface '{1}'." }, + Enum_name_cannot_be_0: { code: 2431, category: ts.DiagnosticCategory.Error, key: "Enum_name_cannot_be_0_2431", message: "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_enu_2432", message: "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_merg_2433", message: "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_2434", message: "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_2435", message: "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_2436", message: "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_2437", message: "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_2438", message: "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_relati_2439", message: "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_2440", message: "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_2441", message: "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_2442", message: "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_2443", message: "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_2444", message: "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_2445", message: "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_2446", message: "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_2447", message: "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_2448", message: "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_2449", message: "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_2450", message: "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_2451", message: "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_2452", message: "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_typ_2453", message: "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_2455", message: "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_2456", message: "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_2457", message: "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_2458", message: "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_2459", message: "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_2460", message: "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_2461", message: "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_2462", message: "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_2463", message: "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_2464", message: "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_2465", message: "'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_2466", message: "'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_2467", message: "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_2468", message: "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_2469", message: "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_2470", message: "'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_2471", message: "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_2472", message: "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_2473", message: "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_2474", message: "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_im_2475", message: "'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_2476", message: "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_2477", message: "'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_2478", message: "'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_2479", message: "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_2480", message: "'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_2481", message: "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_2483", message: "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_2484", message: "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_2485", message: "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_2486", message: "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_2487", message: "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_2488", message: "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_2489", message: "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_2490", message: "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_2491", message: "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_2492", message: "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_2493", message: "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_2494", message: "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_2495", message: "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_stand_2496", message: "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_2497", message: "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_Asterisk_2498", message: "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_Slashqualified_name_with_optional_type_arguments_2499", message: "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_Slashqualified_name_with_optional_type_arguments_2500", message: "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_2501", message: "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_2502", message: "'{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_2503", message: "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_2504", message: "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_2505", message: "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_2506", message: "'{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_2507", message: "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_2508", message: "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_2509", message: "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_2510", message: "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_2511", message: "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_2512", message: "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_2513", message: "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_2514", message: "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_2515", message: "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_2516", message: "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_2517", message: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, + 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_2520", message: "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_2521", message: "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_2522", message: "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_2523", message: "'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_2524", message: "'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_2525", message: "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_2526", message: "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_2527", message: "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_2528", message: "A module cannot have multiple default exports." }, + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: { code: 2529, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", message: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions." }, + JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union 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_2601", message: "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_2602", message: "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_2603", message: "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_2604", message: "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_2605", message: "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_2606", message: "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_2607", message: "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_2608", message: "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_2650", message: "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_memb_2651", message: "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_d_2652", message: "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_2653", message: "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_pack_2654", message: "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_2656", message: "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition." }, + JSX_expressions_must_have_one_parent_element: { code: 2657, category: ts.DiagnosticCategory.Error, key: "JSX_expressions_must_have_one_parent_element_2657", message: "JSX expressions must have one parent element" }, + Type_0_provides_no_match_for_the_signature_1: { code: 2658, category: ts.DiagnosticCategory.Error, key: "Type_0_provides_no_match_for_the_signature_1_2658", message: "Type '{0}' provides no match for the signature '{1}'" }, + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: { code: 2659, category: ts.DiagnosticCategory.Error, key: "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", message: "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher." }, + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: { code: 2660, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", message: "'super' can only be referenced in members of derived classes or object literal expressions." }, + Cannot_re_export_name_that_is_not_defined_in_the_module: { code: 2661, category: ts.DiagnosticCategory.Error, key: "Cannot_re_export_name_that_is_not_defined_in_the_module_2661", message: "Cannot re-export name that is not defined in the module." }, + Cannot_find_name_0_Did_you_mean_the_static_member_1_0: { code: 2662, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", message: "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?" }, + Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: { code: 2663, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", message: "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?" }, + Invalid_module_name_in_augmentation_module_0_cannot_be_found: { code: 2664, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", message: "Invalid module name in augmentation, module '{0}' cannot be found." }, + Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope: { code: 2665, category: ts.DiagnosticCategory.Error, key: "Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope_2665", message: "Module augmentation cannot introduce new names in the top level scope." }, + Exports_and_export_assignments_are_not_permitted_in_module_augmentations: { code: 2666, category: ts.DiagnosticCategory.Error, key: "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", message: "Exports and export assignments are not permitted in module augmentations." }, + Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: { code: 2667, category: ts.DiagnosticCategory.Error, key: "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", message: "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module." }, + export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: { code: 2668, category: ts.DiagnosticCategory.Error, key: "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", message: "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible." }, + Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: { code: 2669, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", message: "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations." }, + Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: { code: 2670, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", message: "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context." }, + Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: { code: 2671, category: ts.DiagnosticCategory.Error, key: "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", message: "Cannot augment module '{0}' because it resolves to a non-module entity." }, + Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "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_4002", message: "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_4004", message: "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_4006", message: "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_4008", message: "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_4010", message: "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_4012", message: "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_4014", message: "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_4016", message: "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_4019", message: "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_4020", message: "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_4022", message: "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_4023", message: "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_4024", message: "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_4025", message: "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__4026", message: "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_4027", message: "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_4028", message: "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_name_4029", message: "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_4030", message: "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_4031", message: "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_4032", message: "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_4033", message: "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_4034", message: "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_4035", message: "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_4036", message: "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_4037", message: "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_externa_4038", message: "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_4039", message: "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_4040", message: "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_modul_4041", message: "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_4042", message: "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_4043", message: "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_mod_4044", message: "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_4045", message: "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_4046", message: "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_4047", message: "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_4048", message: "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_4049", message: "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__4050", message: "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_4051", message: "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_4052", message: "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_c_4053", message: "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_4054", message: "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_4055", message: "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_4056", message: "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_4057", message: "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_4058", message: "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_4059", message: "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_4060", message: "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_can_4061", message: "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_4062", message: "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_4063", message: "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_mod_4064", message: "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_4065", message: "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_4066", message: "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_4067", message: "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__4068", message: "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_4069", message: "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_4070", message: "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_c_4071", message: "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_4072", message: "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_4073", message: "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_4074", message: "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_4075", message: "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_4076", message: "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_4077", message: "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_4078", message: "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_4081", message: "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_4082", message: "Default export of the module has or is using private name '{0}'." }, + 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_5001", message: "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_5009", message: "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_Colon_1_5012", message: "Cannot read file '{0}': {1}" }, + Unsupported_file_encoding: { code: 5013, category: ts.DiagnosticCategory.Error, key: "Unsupported_file_encoding_5013", message: "Unsupported file encoding." }, + Failed_to_parse_file_0_Colon_1: { code: 5014, category: ts.DiagnosticCategory.Error, key: "Failed_to_parse_file_0_Colon_1_5014", message: "Failed to parse file '{0}': {1}." }, + Unknown_compiler_option_0: { code: 5023, category: ts.DiagnosticCategory.Error, key: "Unknown_compiler_option_0_5023", message: "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_5024", message: "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_Colon_1_5033", message: "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_5042", message: "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_ES2015_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_ES_5047", message: "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' 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_prov_5051", message: "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_5052", message: "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_5053", message: "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_Colon_0_5054", message: "A 'tsconfig.json' file is already defined at: '{0}'." }, + Cannot_write_file_0_because_it_would_overwrite_input_file: { code: 5055, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", message: "Cannot write file '{0}' because it would overwrite input file." }, + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: { code: 5056, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", message: "Cannot write file '{0}' because it would be overwritten by multiple input files." }, + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: { code: 5057, category: ts.DiagnosticCategory.Error, key: "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", message: "Cannot find a tsconfig.json file at the specified directory: '{0}'" }, + The_specified_path_does_not_exist_Colon_0: { code: 5058, category: ts.DiagnosticCategory.Error, key: "The_specified_path_does_not_exist_Colon_0_5058", message: "The specified path does not exist: '{0}'" }, + Invalide_value_for_reactNamespace_0_is_not_a_valid_identifier: { code: 5059, category: ts.DiagnosticCategory.Error, key: "Invalide_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", message: "Invalide value for '--reactNamespace'. '{0}' is not a valid identifier." }, + Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, + Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "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_6003", message: "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_6004", message: "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_6005", message: "Watch input files." }, + Redirect_output_structure_to_the_directory: { code: 6006, category: ts.DiagnosticCategory.Message, key: "Redirect_output_structure_to_the_directory_6006", message: "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_6007", message: "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_6008", message: "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_6009", message: "Do not emit comments to output." }, + Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015' (experimental)" }, + Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'" }, + Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, + Print_the_compiler_s_version: { code: 6019, category: ts.DiagnosticCategory.Message, key: "Print_the_compiler_s_version_6019", message: "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_6020", message: "Compile the project in the given directory." }, + Syntax_Colon_0: { code: 6023, category: ts.DiagnosticCategory.Message, key: "Syntax_Colon_0_6023", message: "Syntax: {0}" }, + options: { code: 6024, category: ts.DiagnosticCategory.Message, key: "options_6024", message: "options" }, + file: { code: 6025, category: ts.DiagnosticCategory.Message, key: "file_6025", message: "file" }, + Examples_Colon_0: { code: 6026, category: ts.DiagnosticCategory.Message, key: "Examples_Colon_0_6026", message: "Examples: {0}" }, + Options_Colon: { code: 6027, category: ts.DiagnosticCategory.Message, key: "Options_Colon_6027", message: "Options:" }, + Version_0: { code: 6029, category: ts.DiagnosticCategory.Message, key: "Version_0_6029", message: "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_6030", message: "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_6032", message: "File change detected. Starting incremental compilation..." }, + KIND: { code: 6034, category: ts.DiagnosticCategory.Message, key: "KIND_6034", message: "KIND" }, + FILE: { code: 6035, category: ts.DiagnosticCategory.Message, key: "FILE_6035", message: "FILE" }, + VERSION: { code: 6036, category: ts.DiagnosticCategory.Message, key: "VERSION_6036", message: "VERSION" }, + LOCATION: { code: 6037, category: ts.DiagnosticCategory.Message, key: "LOCATION_6037", message: "LOCATION" }, + DIRECTORY: { code: 6038, category: ts.DiagnosticCategory.Message, key: "DIRECTORY_6038", message: "DIRECTORY" }, + Compilation_complete_Watching_for_file_changes: { code: 6042, category: ts.DiagnosticCategory.Message, key: "Compilation_complete_Watching_for_file_changes_6042", message: "Compilation complete. Watching for file changes." }, + Generates_corresponding_map_file: { code: 6043, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_map_file_6043", message: "Generates corresponding '.map' file." }, + Compiler_option_0_expects_an_argument: { code: 6044, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_expects_an_argument_6044", message: "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_6045", message: "Unterminated quoted string in response file '{0}'." }, + Argument_for_module_option_must_be_commonjs_amd_system_umd_es2015_or_none: { code: 6046, category: ts.DiagnosticCategory.Error, key: "Argument_for_module_option_must_be_commonjs_amd_system_umd_es2015_or_none_6046", message: "Argument for '--module' option must be 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'none'." }, + Argument_for_target_option_must_be_ES3_ES5_or_ES2015: { code: 6047, category: ts.DiagnosticCategory.Error, key: "Argument_for_target_option_must_be_ES3_ES5_or_ES2015_6047", message: "Argument for '--target' option must be 'ES3', 'ES5', or 'ES2015'." }, + 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_language_or_language_territory_For_example_0_or_1_6048", message: "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_6049", message: "Unsupported locale '{0}'." }, + Unable_to_open_file_0: { code: 6050, category: ts.DiagnosticCategory.Error, key: "Unable_to_open_file_0_6050", message: "Unable to open file '{0}'." }, + Corrupted_locale_file_0: { code: 6051, category: ts.DiagnosticCategory.Error, key: "Corrupted_locale_file_0_6051", message: "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_6052", message: "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_6053", message: "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_6054", message: "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_6055", message: "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_6056", message: "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_outDi_6058", message: "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_6059", message: "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_Colon_CRLF_dos_or_LF_unix_6060", message: "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_6061", message: "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_6062", message: "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_6063", message: "Argument for '--moduleResolution' option must be 'node' or 'classic'." }, + Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_decorators_6065", message: "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_6066", message: "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_6068", message: "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_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", message: "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_6070", message: "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_6071", message: "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_6072", message: "Suppress excess property checks for object literals." }, + Stylize_errors_and_messages_using_color_and_context_experimental: { code: 6073, category: ts.DiagnosticCategory.Message, key: "Stylize_errors_and_messages_using_color_and_context_experimental_6073", message: "Stylize errors and messages using color and context. (experimental)" }, + Do_not_report_errors_on_unused_labels: { code: 6074, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unused_labels_6074", message: "Do not report errors on unused labels." }, + Report_error_when_not_all_code_paths_in_function_return_a_value: { code: 6075, category: ts.DiagnosticCategory.Message, key: "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", message: "Report error when not all code paths in function return a value." }, + Report_errors_for_fallthrough_cases_in_switch_statement: { code: 6076, category: ts.DiagnosticCategory.Message, key: "Report_errors_for_fallthrough_cases_in_switch_statement_6076", message: "Report errors for fallthrough cases in switch statement." }, + Do_not_report_errors_on_unreachable_code: { code: 6077, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unreachable_code_6077", message: "Do not report errors on unreachable code." }, + Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." }, + Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "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_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." }, + Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." }, + Allow_javascript_files_to_be_compiled: { code: 6083, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6083", message: "Allow javascript files to be compiled." }, + Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit: { code: 6084, category: ts.DiagnosticCategory.Message, key: "Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit_6084", message: "Specifies the object invoked for createElement and __spread when targeting 'react' JSX emit" }, + Do_not_emit_use_strict_directives_in_module_output: { code: 6112, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_use_strict_directives_in_module_output_6112", message: "Do not emit 'use strict' directives in module output." }, + Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "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_7006", message: "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_7008", message: "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_7009", message: "'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_7010", message: "'{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_7011", message: "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_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, + Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, + 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_7016", message: "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_7017", message: "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_7018", message: "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_7019", message: "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_7020", message: "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__7022", message: "'{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_reference_7023", message: "'{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_ref_7024", message: "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_typ_7025", message: "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_7026", message: "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists" }, + Unreachable_code_detected: { code: 7027, category: ts.DiagnosticCategory.Error, key: "Unreachable_code_detected_7027", message: "Unreachable code detected." }, + Unused_label: { code: 7028, category: ts.DiagnosticCategory.Error, key: "Unused_label_7028", message: "Unused label." }, + Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, + Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, + You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "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_8001", message: "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_8002", message: "'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_8003", message: "'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_8004", message: "'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_8005", message: "'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_8006", message: "'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_8007", message: "'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_8008", message: "'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_8009", message: "'{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_8010", message: "'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_8011", message: "'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_8012", message: "'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_8014", message: "'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_8015", message: "'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_8016", message: "'type assertion expressions' 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_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "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_9003", message: "'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_17000", message: "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_17001", message: "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_17002", message: "Expected corresponding JSX closing tag for '{0}'." }, + JSX_attribute_expected: { code: 17003, category: ts.DiagnosticCategory.Error, key: "JSX_attribute_expected_17003", message: "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_17004", message: "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_17005", message: "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_ex_17006", message: "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_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, + JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, + super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." } }; })(ts || (ts = {})); /// @@ -2689,6 +2926,7 @@ var ts; "protected": 111 /* ProtectedKeyword */, "public": 112 /* PublicKeyword */, "require": 127 /* RequireKeyword */, + "global": 134 /* GlobalKeyword */, "return": 94 /* ReturnKeyword */, "set": 129 /* SetKeyword */, "static": 113 /* StaticKeyword */, @@ -2709,7 +2947,7 @@ var ts; "yield": 114 /* YieldKeyword */, "async": 118 /* AsyncKeyword */, "await": 119 /* AwaitKeyword */, - "of": 134 /* OfKeyword */, + "of": 135 /* OfKeyword */, "{": 15 /* OpenBraceToken */, "}": 16 /* CloseBraceToken */, "(": 17 /* OpenParenToken */, @@ -2872,7 +3110,8 @@ var ts; var pos = 0; var lineStart = 0; while (pos < text.length) { - var ch = text.charCodeAt(pos++); + var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 13 /* carriageReturn */: if (text.charCodeAt(pos) === 10 /* lineFeed */) { @@ -3006,6 +3245,11 @@ var ts; ts.couldStartTrivia = couldStartTrivia; /* @internal */ function skipTrivia(text, pos, stopAfterLineBreak) { + // Using ! with a greater than test is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + if (!(pos >= 0)) { + return pos; + } // Keep in sync with couldStartTrivia while (true) { var ch = text.charCodeAt(pos); @@ -3144,7 +3388,7 @@ var ts; function getCommentRanges(text, pos, trailing) { var result; var collecting = trailing || pos === 0; - while (true) { + while (pos < text.length) { var ch = text.charCodeAt(pos); switch (ch) { case 13 /* carriageReturn */: @@ -3213,6 +3457,7 @@ var ts; } return result; } + return result; } function getLeadingCommentRanges(text, pos) { return getCommentRanges(text, pos, /*trailing*/ false); @@ -3241,6 +3486,19 @@ var ts; ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); } ts.isIdentifierPart = isIdentifierPart; + /* @internal */ + function isIdentifier(name, languageVersion) { + if (!isIdentifierStart(name.charCodeAt(0), languageVersion)) { + return false; + } + for (var i = 1, n = name.length; i < n; i++) { + if (!isIdentifierPart(name.charCodeAt(i), languageVersion)) { + return false; + } + } + return true; + } + ts.isIdentifier = isIdentifier; // 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 */; } @@ -3276,6 +3534,7 @@ var ts; scanJsxIdentifier: scanJsxIdentifier, reScanJsxToken: reScanJsxToken, scanJsxToken: scanJsxToken, + scanJSDocToken: scanJSDocToken, scan: scan, setText: setText, setScriptTarget: setScriptTarget, @@ -3283,7 +3542,8 @@ var ts; setOnError: setOnError, setTextPos: setTextPos, tryScan: tryScan, - lookAhead: lookAhead + lookAhead: lookAhead, + scanRange: scanRange }; function error(message, length) { if (onError) { @@ -3314,7 +3574,7 @@ var ts; error(ts.Diagnostics.Digit_expected); } } - return +(text.substring(start, end)); + return "" + +(text.substring(start, end)); } function scanOctalDigits() { var start = pos; @@ -3363,7 +3623,8 @@ var ts; return value; } function scanString() { - var quote = text.charCodeAt(pos++); + var quote = text.charCodeAt(pos); + pos++; var result = ""; var start = pos; while (true) { @@ -3459,7 +3720,8 @@ var ts; error(ts.Diagnostics.Unexpected_end_of_text); return ""; } - var ch = text.charCodeAt(pos++); + var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 48 /* _0 */: return "\0"; @@ -3686,7 +3948,8 @@ var ts; } return pos += 2, token = 31 /* ExclamationEqualsToken */; } - return pos++, token = 49 /* ExclamationToken */; + pos++; + return token = 49 /* ExclamationToken */; case 34 /* doubleQuote */: case 39 /* singleQuote */: tokenValue = scanString(); @@ -3697,7 +3960,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 62 /* PercentEqualsToken */; } - return pos++, token = 40 /* PercentToken */; + pos++; + return token = 40 /* PercentToken */; case 38 /* ampersand */: if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { return pos += 2, token = 51 /* AmpersandAmpersandToken */; @@ -3705,11 +3969,14 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 66 /* AmpersandEqualsToken */; } - return pos++, token = 46 /* AmpersandToken */; + pos++; + return token = 46 /* AmpersandToken */; case 40 /* openParen */: - return pos++, token = 17 /* OpenParenToken */; + pos++; + return token = 17 /* OpenParenToken */; case 41 /* closeParen */: - return pos++, token = 18 /* CloseParenToken */; + pos++; + return token = 18 /* CloseParenToken */; case 42 /* asterisk */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 59 /* AsteriskEqualsToken */; @@ -3720,7 +3987,8 @@ var ts; } return pos += 2, token = 38 /* AsteriskAsteriskToken */; } - return pos++, token = 37 /* AsteriskToken */; + pos++; + return token = 37 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { return pos += 2, token = 41 /* PlusPlusToken */; @@ -3728,9 +3996,11 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 57 /* PlusEqualsToken */; } - return pos++, token = 35 /* PlusToken */; + pos++; + return token = 35 /* PlusToken */; case 44 /* comma */: - return pos++, token = 24 /* CommaToken */; + pos++; + return token = 24 /* CommaToken */; case 45 /* minus */: if (text.charCodeAt(pos + 1) === 45 /* minus */) { return pos += 2, token = 42 /* MinusMinusToken */; @@ -3738,16 +4008,18 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 58 /* MinusEqualsToken */; } - return pos++, token = 36 /* MinusToken */; + pos++; + return token = 36 /* MinusToken */; case 46 /* dot */: if (isDigit(text.charCodeAt(pos + 1))) { - tokenValue = "" + scanNumber(); + 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 */; + pos++; + return token = 21 /* DotToken */; case 47 /* slash */: // Single-line comment if (text.charCodeAt(pos + 1) === 47 /* slash */) { @@ -3795,7 +4067,8 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 61 /* SlashEqualsToken */; } - return pos++, token = 39 /* SlashToken */; + pos++; + return token = 39 /* SlashToken */; case 48 /* _0 */: if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { pos += 2; @@ -3844,12 +4117,14 @@ var ts; case 55 /* _7 */: case 56 /* _8 */: case 57 /* _9 */: - tokenValue = "" + scanNumber(); + tokenValue = scanNumber(); return token = 8 /* NumericLiteral */; case 58 /* colon */: - return pos++, token = 54 /* ColonToken */; + pos++; + return token = 54 /* ColonToken */; case 59 /* semicolon */: - return pos++, token = 23 /* SemicolonToken */; + pos++; + return token = 23 /* SemicolonToken */; case 60 /* lessThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3874,7 +4149,8 @@ var ts; text.charCodeAt(pos + 2) !== 42 /* asterisk */) { return pos += 2, token = 26 /* LessThanSlashToken */; } - return pos++, token = 25 /* LessThanToken */; + pos++; + return token = 25 /* LessThanToken */; case 61 /* equals */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3894,7 +4170,8 @@ var ts; if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { return pos += 2, token = 34 /* EqualsGreaterThanToken */; } - return pos++, token = 56 /* EqualsToken */; + pos++; + return token = 56 /* EqualsToken */; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { pos = scanConflictMarkerTrivia(text, pos, error); @@ -3905,20 +4182,26 @@ var ts; return token = 7 /* ConflictMarkerTrivia */; } } - return pos++, token = 27 /* GreaterThanToken */; + pos++; + return token = 27 /* GreaterThanToken */; case 63 /* question */: - return pos++, token = 53 /* QuestionToken */; + pos++; + return token = 53 /* QuestionToken */; case 91 /* openBracket */: - return pos++, token = 19 /* OpenBracketToken */; + pos++; + return token = 19 /* OpenBracketToken */; case 93 /* closeBracket */: - return pos++, token = 20 /* CloseBracketToken */; + pos++; + return token = 20 /* CloseBracketToken */; case 94 /* caret */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 68 /* CaretEqualsToken */; } - return pos++, token = 48 /* CaretToken */; + pos++; + return token = 48 /* CaretToken */; case 123 /* openBrace */: - return pos++, token = 15 /* OpenBraceToken */; + pos++; + return token = 15 /* OpenBraceToken */; case 124 /* bar */: if (text.charCodeAt(pos + 1) === 124 /* bar */) { return pos += 2, token = 52 /* BarBarToken */; @@ -3926,13 +4209,17 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 67 /* BarEqualsToken */; } - return pos++, token = 47 /* BarToken */; + pos++; + return token = 47 /* BarToken */; case 125 /* closeBrace */: - return pos++, token = 16 /* CloseBraceToken */; + pos++; + return token = 16 /* CloseBraceToken */; case 126 /* tilde */: - return pos++, token = 50 /* TildeToken */; + pos++; + return token = 50 /* TildeToken */; case 64 /* at */: - return pos++, token = 55 /* AtToken */; + pos++; + return token = 55 /* AtToken */; case 92 /* backslash */: var cookedChar = peekUnicodeEscape(); if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) { @@ -3941,7 +4228,8 @@ var ts; return token = getIdentifierToken(); } error(ts.Diagnostics.Invalid_character); - return pos++, token = 0 /* Unknown */; + pos++; + return token = 0 /* Unknown */; default: if (isIdentifierStart(ch, languageVersion)) { pos++; @@ -3963,7 +4251,8 @@ var ts; continue; } error(ts.Diagnostics.Invalid_character); - return pos++, token = 0 /* Unknown */; + pos++; + return token = 0 /* Unknown */; } } } @@ -3979,10 +4268,12 @@ var ts; if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 64 /* GreaterThanGreaterThanEqualsToken */; } - return pos++, token = 44 /* GreaterThanGreaterThanToken */; + pos++; + return token = 44 /* GreaterThanGreaterThanToken */; } if (text.charCodeAt(pos) === 61 /* equals */) { - return pos++, token = 29 /* GreaterThanEqualsToken */; + pos++; + return token = 29 /* GreaterThanEqualsToken */; } } return token; @@ -4074,7 +4365,7 @@ var ts; break; } } - return token = 236 /* JsxText */; + return token = 239 /* JsxText */; } // Scans a JSX identifier; these differ from normal identifiers in that // they allow dashes @@ -4094,6 +4385,55 @@ var ts; } return token; } + function scanJSDocToken() { + if (pos >= end) { + return token = 1 /* EndOfFileToken */; + } + startPos = pos; + // Eat leading whitespace + var ch = text.charCodeAt(pos); + while (pos < end) { + ch = text.charCodeAt(pos); + if (isWhiteSpace(ch)) { + pos++; + } + else { + break; + } + } + tokenPos = pos; + switch (ch) { + case 64 /* at */: + return pos += 1, token = 55 /* AtToken */; + case 10 /* lineFeed */: + case 13 /* carriageReturn */: + return pos += 1, token = 4 /* NewLineTrivia */; + case 42 /* asterisk */: + return pos += 1, token = 37 /* AsteriskToken */; + case 123 /* openBrace */: + return pos += 1, token = 15 /* OpenBraceToken */; + case 125 /* closeBrace */: + return pos += 1, token = 16 /* CloseBraceToken */; + case 91 /* openBracket */: + return pos += 1, token = 19 /* OpenBracketToken */; + case 93 /* closeBracket */: + return pos += 1, token = 20 /* CloseBracketToken */; + case 61 /* equals */: + return pos += 1, token = 56 /* EqualsToken */; + case 44 /* comma */: + return pos += 1, token = 24 /* CommaToken */; + } + if (isIdentifierStart(ch, 2 /* Latest */)) { + pos++; + while (isIdentifierPart(text.charCodeAt(pos), 2 /* Latest */) && pos < end) { + pos++; + } + return token = 69 /* Identifier */; + } + else { + return pos += 1, token = 0 /* Unknown */; + } + } function speculationHelper(callback, isLookahead) { var savePos = pos; var saveStartPos = startPos; @@ -4114,11 +4454,34 @@ var ts; } return result; } + function scanRange(start, length, callback) { + var saveEnd = end; + var savePos = pos; + var saveStartPos = startPos; + var saveTokenPos = tokenPos; + var saveToken = token; + var savePrecedingLineBreak = precedingLineBreak; + var saveTokenValue = tokenValue; + var saveHasExtendedUnicodeEscape = hasExtendedUnicodeEscape; + var saveTokenIsUnterminated = tokenIsUnterminated; + setText(text, start, length); + var result = callback(); + end = saveEnd; + pos = savePos; + startPos = saveStartPos; + tokenPos = saveTokenPos; + token = saveToken; + precedingLineBreak = savePrecedingLineBreak; + tokenValue = saveTokenValue; + hasExtendedUnicodeEscape = saveHasExtendedUnicodeEscape; + tokenIsUnterminated = saveTokenIsUnterminated; + return result; + } function lookAhead(callback) { - return speculationHelper(callback, /*isLookahead:*/ true); + return speculationHelper(callback, /*isLookahead*/ true); } function tryScan(callback) { - return speculationHelper(callback, /*isLookahead:*/ false); + return speculationHelper(callback, /*isLookahead*/ false); } function setText(newText, start, length) { text = newText || ""; @@ -4148,2963 +4511,2376 @@ var ts; } 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; + function getDeclarationOfKind(symbol, kind) { + var declarations = symbol.declarations; + if (declarations) { + for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) { + var declaration = declarations_1[_i]; + if (declaration.kind === kind) { + return declaration; } - }); - return state; - } - else if (node.kind === 218 /* ModuleDeclaration */) { - return getModuleInstanceState(node.body); + } } - else { - return 1 /* Instantiated */; + 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_1 = ""; + var writeText = function (text) { return str_1 += text; }; + return { + string: function () { return str_1; }, + 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_1 += " "; }, + increaseIndent: function () { }, + decreaseIndent: function () { }, + clear: function () { return str_1 = ""; }, + trackSymbol: function () { }, + reportInaccessibleThisError: function () { } + }; } + return stringWriters.pop(); } - 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.getSingleLineStringWriter = getSingleLineStringWriter; + function releaseStringWriter(writer) { + writer.clear(); + stringWriters.push(writer); } - 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); + ts.releaseStringWriter = releaseStringWriter; + function getFullWidth(node) { + return node.end - node.pos; + } + ts.getFullWidth = getFullWidth; + function arrayIsEqualTo(array1, array2, equaler) { + if (!array1 || !array2) { + return array1 === array2; } - 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; - } + if (array1.length !== array2.length) { + return false; } - // 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; + for (var i = 0; i < array1.length; i++) { + var equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; + if (!equals) { + return false; } } - function getDisplayName(node) { - return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node); + 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 = {}; } - /** - * 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"); + 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 */; } - addDeclarationToSymbol(symbol, node, includes); - symbol.parent = parent; - return symbol; + // 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 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); - } - } + } + function getSourceFileOfNode(node) { + while (node && node.kind !== 251 /* SourceFile */) { + node = node.parent; } - // 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; + return node; + } + ts.getSourceFileOfNode = getSourceFileOfNode; + function isStatementWithLocals(node) { + switch (node.kind) { + case 195 /* Block */: + case 223 /* CaseBlock */: + case 202 /* ForStatement */: + case 203 /* ForInStatement */: + case 204 /* ForOfStatement */: + return true; } - 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; + return false; + } + ts.isStatementWithLocals = isStatementWithLocals; + 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; } - function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { - // Just call this directly so that the return type of this function stays "void". - declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); + 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; } - 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); - } + 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); } - 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); + 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 ""; } - function declareSourceFileMember(node, symbolFlags, symbolExcludes) { - return ts.isExternalModule(file) - ? declareModuleMember(node, symbolFlags, symbolExcludes) - : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); + 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 ""; } - function isAmbientContext(node) { - while (node) { - if (node.flags & 2 /* Ambient */) { - return true; - } - node = node.parent; - } + 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) & 24576 /* BlockScoped */) !== 0 || + isCatchClauseVariableDeclaration(declaration); + } + ts.isBlockOrCatchScoped = isBlockOrCatchScoped; + function isAmbientModule(node) { + return node && node.kind === 221 /* ModuleDeclaration */ && + (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); + } + ts.isAmbientModule = isAmbientModule; + function isBlockScopedContainerTopLevel(node) { + return node.kind === 251 /* SourceFile */ || + node.kind === 221 /* ModuleDeclaration */ || + isFunctionLike(node) || + isFunctionBlock(node); + } + ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; + function isGlobalScopeAugmentation(module) { + return !!(module.flags & 2097152 /* GlobalAugmentation */); + } + ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; + function isExternalModuleAugmentation(node) { + // external module augmentation is a ambient module declaration that is either: + // - defined in the top level scope and source file is an external module + // - defined inside ambient module declaration located in the top level scope and source file not an external module + if (!node || !isAmbientModule(node)) { 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; + switch (node.parent.kind) { + case 251 /* SourceFile */: + return isExternalModule(node.parent); + case 222 /* ModuleBlock */: + return isAmbientModule(node.parent.parent) && !isExternalModule(node.parent.parent.parent); } - 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 */; + return false; + } + ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + // 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; } - else { - node.flags &= ~262144 /* ExportContext */; + switch (current.kind) { + case 251 /* SourceFile */: + case 223 /* CaseBlock */: + case 247 /* CatchClause */: + case 221 /* ModuleDeclaration */: + case 202 /* ForStatement */: + case 203 /* ForInStatement */: + case 204 /* ForOfStatement */: + return current; + case 195 /* 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; } - 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; - } - } + } + ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; + function isCatchClauseVariableDeclaration(declaration) { + return declaration && + declaration.kind === 214 /* VariableDeclaration */ && + declaration.parent && + declaration.parent.kind === 247 /* 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 251 /* 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 214 /* VariableDeclaration */: + case 166 /* BindingElement */: + case 217 /* ClassDeclaration */: + case 189 /* ClassExpression */: + case 218 /* InterfaceDeclaration */: + case 221 /* ModuleDeclaration */: + case 220 /* EnumDeclaration */: + case 250 /* EnumMember */: + case 216 /* FunctionDeclaration */: + case 176 /* FunctionExpression */: + case 144 /* MethodDeclaration */: + case 219 /* TypeAliasDeclaration */: + errorNode = node.name; + break; } - 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; + 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); } - 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)); - } + 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 isExternalOrCommonJsModule(file) { + return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; + } + ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; + function isDeclarationFile(file) { + return (file.flags & 4096 /* DeclarationFile */) !== 0; + } + ts.isDeclarationFile = isDeclarationFile; + function isConstEnumDeclaration(node) { + return node.kind === 220 /* EnumDeclaration */ && isConst(node); + } + ts.isConstEnumDeclaration = isConstEnumDeclaration; + function walkUpBindingElementsAndPatterns(node) { + while (node && (node.kind === 166 /* 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 === 214 /* VariableDeclaration */) { + node = node.parent; + } + if (node && node.kind === 215 /* VariableDeclarationList */) { + flags |= node.flags; + node = node.parent; + } + if (node && node.kind === 196 /* VariableStatement */) { + flags |= node.flags; + } + return flags; + } + ts.getCombinedNodeFlags = getCombinedNodeFlags; + function isConst(node) { + return !!(getCombinedNodeFlags(node) & 16384 /* Const */); + } + ts.isConst = isConst; + function isLet(node) { + return !!(getCombinedNodeFlags(node) & 8192 /* Let */); + } + ts.isLet = isLet; + function isSuperCallExpression(n) { + return n.kind === 171 /* CallExpression */ && n.expression.kind === 95 /* SuperKeyword */; + } + ts.isSuperCallExpression = isSuperCallExpression; + function isPrologueDirective(node) { + return node.kind === 198 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; + } + ts.isPrologueDirective = isPrologueDirective; + function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { + return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos); + } + ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; + function getLeadingCommentRangesOfNodeFromText(node, text) { + return ts.getLeadingCommentRanges(text, node.pos); + } + ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText; + function getJsDocComments(node, sourceFileOfNode) { + return getJsDocCommentsFromText(node, sourceFileOfNode.text); + } + ts.getJsDocComments = getJsDocComments; + function getJsDocCommentsFromText(node, text) { + var commentRanges = (node.kind === 139 /* Parameter */ || node.kind === 138 /* TypeParameter */) ? + ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : + getLeadingCommentRangesOfNodeFromText(node, text); + return ts.filter(commentRanges, isJsDocComment); + function isJsDocComment(comment) { + // True if the comment starts with '/**' but not if it is '/**/' + return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 3) !== 47 /* slash */; + } + } + ts.getJsDocCommentsFromText = getJsDocCommentsFromText; + ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; + ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; + function isTypeNode(node) { + if (151 /* FirstTypeNode */ <= node.kind && node.kind <= 163 /* 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 !== 180 /* VoidExpression */; + case 191 /* 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 === 136 /* QualifiedName */ && node.parent.right === node) { + node = node.parent; + } + else if (node.parent.kind === 169 /* 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 === 136 /* QualifiedName */ || node.kind === 169 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isTypeNode'."); + case 136 /* QualifiedName */: + case 169 /* PropertyAccessExpression */: + case 97 /* ThisKeyword */: + var parent_1 = node.parent; + if (parent_1.kind === 155 /* 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 <= 163 /* LastTypeNode */) { + return true; + } + switch (parent_1.kind) { + case 191 /* ExpressionWithTypeArguments */: + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); + case 138 /* TypeParameter */: + return node === parent_1.constraint; + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: + case 139 /* Parameter */: + case 214 /* VariableDeclaration */: + return node === parent_1.type; + case 216 /* FunctionDeclaration */: + case 176 /* FunctionExpression */: + case 177 /* ArrowFunction */: + case 145 /* Constructor */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + return node === parent_1.type; + case 148 /* CallSignature */: + case 149 /* ConstructSignature */: + case 150 /* IndexSignature */: + return node === parent_1.type; + case 174 /* TypeAssertionExpression */: + return node === parent_1.type; + case 171 /* CallExpression */: + case 172 /* NewExpression */: + return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; + case 173 /* TaggedTemplateExpression */: + // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. + return false; } - } - return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object"); } - function bindAnonymousDeclaration(node, symbolFlags, name) { - var symbol = createSymbol(symbolFlags, name); - addDeclarationToSymbol(symbol, node, symbolFlags); + 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 207 /* ReturnStatement */: + return visitor(node); + case 223 /* CaseBlock */: + case 195 /* Block */: + case 199 /* IfStatement */: + case 200 /* DoStatement */: + case 201 /* WhileStatement */: + case 202 /* ForStatement */: + case 203 /* ForInStatement */: + case 204 /* ForOfStatement */: + case 208 /* WithStatement */: + case 209 /* SwitchStatement */: + case 244 /* CaseClause */: + case 245 /* DefaultClause */: + case 210 /* LabeledStatement */: + case 212 /* TryStatement */: + case 247 /* CatchClause */: + return ts.forEachChild(node, traverse); + } } - 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; + } + ts.forEachReturnStatement = forEachReturnStatement; + function forEachYieldExpression(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 187 /* YieldExpression */: + visitor(node); + var operand = node.expression; + if (operand) { + traverse(operand); } - // fall through. + case 220 /* EnumDeclaration */: + case 218 /* InterfaceDeclaration */: + case 221 /* ModuleDeclaration */: + case 219 /* TypeAliasDeclaration */: + case 217 /* ClassDeclaration */: + case 189 /* 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 (!blockScopeContainer.locals) { - blockScopeContainer.locals = {}; - addToContainerChain(blockScopeContainer); + if (isFunctionLike(node)) { + var name_5 = node.name; + if (name_5 && name_5.kind === 137 /* 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); } - 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))); - } + } + ts.forEachYieldExpression = forEachYieldExpression; + function isVariableLike(node) { + if (node) { + switch (node.kind) { + case 166 /* BindingElement */: + case 250 /* EnumMember */: + case 139 /* Parameter */: + case 248 /* PropertyAssignment */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: + case 249 /* ShorthandPropertyAssignment */: + case 214 /* VariableDeclaration */: + return true; } } - 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; + return false; + } + ts.isVariableLike = isVariableLike; + function isAccessor(node) { + return node && (node.kind === 146 /* GetAccessor */ || node.kind === 147 /* SetAccessor */); + } + ts.isAccessor = isAccessor; + function isClassLike(node) { + return node && (node.kind === 217 /* ClassDeclaration */ || node.kind === 189 /* ClassExpression */); + } + ts.isClassLike = isClassLike; + function isFunctionLike(node) { + return node && isFunctionLikeKind(node.kind); + } + ts.isFunctionLike = isFunctionLike; + function isFunctionLikeKind(kind) { + switch (kind) { + case 145 /* Constructor */: + case 176 /* FunctionExpression */: + case 216 /* FunctionDeclaration */: + case 177 /* ArrowFunction */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 148 /* CallSignature */: + case 149 /* ConstructSignature */: + case 150 /* IndexSignature */: + case 153 /* FunctionType */: + case 154 /* ConstructorType */: + return true; } - 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); - } + } + ts.isFunctionLikeKind = isFunctionLikeKind; + function introducesArgumentsExoticObject(node) { + switch (node.kind) { + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 145 /* Constructor */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 216 /* FunctionDeclaration */: + case 176 /* FunctionExpression */: + return true; } - 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); - } + return false; + } + ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; + function isIterationStatement(node, lookInLabeledStatements) { + switch (node.kind) { + case 202 /* ForStatement */: + case 203 /* ForInStatement */: + case 204 /* ForOfStatement */: + case 200 /* DoStatement */: + case 201 /* WhileStatement */: + return true; + case 210 /* LabeledStatement */: + return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } - 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)); + return false; + } + ts.isIterationStatement = isIterationStatement; + function isFunctionBlock(node) { + return node && node.kind === 195 /* Block */ && isFunctionLike(node.parent); + } + ts.isFunctionBlock = isFunctionBlock; + function isObjectLiteralMethod(node) { + return node && node.kind === 144 /* MethodDeclaration */ && node.parent.kind === 168 /* ObjectLiteralExpression */; + } + ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isIdentifierTypePredicate(predicate) { + return predicate && predicate.kind === 1 /* Identifier */; + } + ts.isIdentifierTypePredicate = isIdentifierTypePredicate; + function isThisTypePredicate(predicate) { + return predicate && predicate.kind === 0 /* This */; + } + ts.isThisTypePredicate = isThisTypePredicate; + function getContainingFunction(node) { + while (true) { + node = node.parent; + if (!node || isFunctionLike(node)) { + return node; } } - 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)); - } + } + ts.getContainingFunction = getContainingFunction; + function getContainingClass(node) { + while (true) { + node = node.parent; + if (!node || isClassLike(node)) { + return node; } } - 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; + } + ts.getContainingClass = getContainingClass; + function getThisContainer(node, includeArrowFunctions) { + while (true) { + node = node.parent; + if (!node) { + return undefined; } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + switch (node.kind) { + case 137 /* 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 140 /* Decorator */: + // Decorators are always applied outside of the body of a class or method. + if (node.parent.kind === 139 /* 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 177 /* ArrowFunction */: + if (!includeArrowFunctions) { + continue; + } + // Fall through + case 216 /* FunctionDeclaration */: + case 176 /* FunctionExpression */: + case 221 /* ModuleDeclaration */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 145 /* Constructor */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 148 /* CallSignature */: + case 149 /* ConstructSignature */: + case 150 /* IndexSignature */: + case 220 /* EnumDeclaration */: + case 251 /* SourceFile */: + return node; } - 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); + } + ts.getThisContainer = getThisContainer; + /** + * Given an super call\property node returns a closest node where either + * - super call\property is legal in the node and not legal in the parent node the node. + * i.e. super call is legal in constructor but not legal in the class body. + * - node is arrow function (so caller might need to call getSuperContainer in case it needs to climb higher) + * - super call\property is definitely illegal in the node (but might be legal in some subnode) + * i.e. super property access is illegal in function declaration but can be legal in the statement list + */ + function getSuperContainer(node, stopOnFunctions) { + while (true) { + node = node.parent; + if (!node) { + return node; } - } - 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)); + switch (node.kind) { + case 137 /* ComputedPropertyName */: + node = node.parent; + break; + case 216 /* FunctionDeclaration */: + case 176 /* FunctionExpression */: + case 177 /* ArrowFunction */: + if (!stopOnFunctions) { + continue; + } + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 145 /* Constructor */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + return node; + case 140 /* Decorator */: + // Decorators are always applied outside of the body of a class or method. + if (node.parent.kind === 139 /* 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; } } - 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); + } + ts.getSuperContainer = getSuperContainer; + /** + * Determines whether a node is a property or element access expression for super. + */ + function isSuperPropertyOrElementAccess(node) { + return (node.kind === 169 /* PropertyAccessExpression */ + || node.kind === 170 /* ElementAccessExpression */) + && node.expression.kind === 95 /* SuperKeyword */; + } + ts.isSuperPropertyOrElementAccess = isSuperPropertyOrElementAccess; + function getEntityNameFromTypeNode(node) { + if (node) { + switch (node.kind) { + case 152 /* TypeReference */: + return node.typeName; + case 191 /* ExpressionWithTypeArguments */: + return node.expression; + case 69 /* Identifier */: + case 136 /* QualifiedName */: + return node; } } - function checkStrictModePrefixUnaryExpression(node) { - // Grammar checking - if (inStrictMode) { - if (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } + return undefined; + } + ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; + function getInvokedExpression(node) { + if (node.kind === 173 /* TaggedTemplateExpression */) { + return node.tag; } - function checkStrictModeWithStatement(node) { - // Grammar checking for withStatement - if (inStrictMode) { - grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); - } + // Will either be a CallExpression, NewExpression, or Decorator. + return node.expression; + } + ts.getInvokedExpression = getInvokedExpression; + function nodeCanBeDecorated(node) { + switch (node.kind) { + case 217 /* ClassDeclaration */: + // classes are valid targets + return true; + case 142 /* PropertyDeclaration */: + // property declarations are valid if their parent is a class declaration. + return node.parent.kind === 217 /* ClassDeclaration */; + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 144 /* MethodDeclaration */: + // if this method has a body and its parent is a class declaration, this is a valid target. + return node.body !== undefined + && node.parent.kind === 217 /* ClassDeclaration */; + case 139 /* 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 !== undefined + && (node.parent.kind === 145 /* Constructor */ + || node.parent.kind === 144 /* MethodDeclaration */ + || node.parent.kind === 147 /* SetAccessor */) + && node.parent.parent.kind === 217 /* ClassDeclaration */; } - 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)); + return false; + } + ts.nodeCanBeDecorated = nodeCanBeDecorated; + function nodeIsDecorated(node) { + return node.decorators !== undefined + && nodeCanBeDecorated(node); + } + ts.nodeIsDecorated = nodeIsDecorated; + function isPropertyAccessExpression(node) { + return node.kind === 169 /* PropertyAccessExpression */; + } + ts.isPropertyAccessExpression = isPropertyAccessExpression; + function isElementAccessExpression(node) { + return node.kind === 170 /* 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 167 /* ArrayLiteralExpression */: + case 168 /* ObjectLiteralExpression */: + case 169 /* PropertyAccessExpression */: + case 170 /* ElementAccessExpression */: + case 171 /* CallExpression */: + case 172 /* NewExpression */: + case 173 /* TaggedTemplateExpression */: + case 192 /* AsExpression */: + case 174 /* TypeAssertionExpression */: + case 175 /* ParenthesizedExpression */: + case 176 /* FunctionExpression */: + case 189 /* ClassExpression */: + case 177 /* ArrowFunction */: + case 180 /* VoidExpression */: + case 178 /* DeleteExpression */: + case 179 /* TypeOfExpression */: + case 182 /* PrefixUnaryExpression */: + case 183 /* PostfixUnaryExpression */: + case 184 /* BinaryExpression */: + case 185 /* ConditionalExpression */: + case 188 /* SpreadElementExpression */: + case 186 /* TemplateExpression */: + case 11 /* NoSubstitutionTemplateLiteral */: + case 190 /* OmittedExpression */: + case 236 /* JsxElement */: + case 237 /* JsxSelfClosingElement */: + case 187 /* YieldExpression */: + case 181 /* AwaitExpression */: + return true; + case 136 /* QualifiedName */: + while (node.parent.kind === 136 /* QualifiedName */) { + node = node.parent; + } + return node.parent.kind === 155 /* TypeQuery */; + case 69 /* Identifier */: + if (node.parent.kind === 155 /* TypeQuery */) { + return true; + } + // fall through + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 97 /* ThisKeyword */: + var parent_2 = node.parent; + switch (parent_2.kind) { + case 214 /* VariableDeclaration */: + case 139 /* Parameter */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: + case 250 /* EnumMember */: + case 248 /* PropertyAssignment */: + case 166 /* BindingElement */: + return parent_2.initializer === node; + case 198 /* ExpressionStatement */: + case 199 /* IfStatement */: + case 200 /* DoStatement */: + case 201 /* WhileStatement */: + case 207 /* ReturnStatement */: + case 208 /* WithStatement */: + case 209 /* SwitchStatement */: + case 244 /* CaseClause */: + case 211 /* ThrowStatement */: + case 209 /* SwitchStatement */: + return parent_2.expression === node; + case 202 /* ForStatement */: + var forStatement = parent_2; + return (forStatement.initializer === node && forStatement.initializer.kind !== 215 /* VariableDeclarationList */) || + forStatement.condition === node || + forStatement.incrementor === node; + case 203 /* ForInStatement */: + case 204 /* ForOfStatement */: + var forInStatement = parent_2; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 215 /* VariableDeclarationList */) || + forInStatement.expression === node; + case 174 /* TypeAssertionExpression */: + case 192 /* AsExpression */: + return node === parent_2.expression; + case 193 /* TemplateSpan */: + return node === parent_2.expression; + case 137 /* ComputedPropertyName */: + return node === parent_2.expression; + case 140 /* Decorator */: + case 243 /* JsxExpression */: + case 242 /* JsxSpreadAttribute */: + return true; + case 191 /* ExpressionWithTypeArguments */: + return parent_2.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_2); + default: + if (isExpression(parent_2)) { + return true; + } + } } - function getDestructuringParameterName(node) { - return "__" + ts.indexOf(node.parent.parameters, node); + 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 === 224 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 235 /* 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 === 224 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 235 /* ExternalModuleReference */; + } + ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; + function isSourceFileJavaScript(file) { + return isInJavaScriptFile(file); + } + ts.isSourceFileJavaScript = isSourceFileJavaScript; + function isInJavaScriptFile(node) { + return node && !!(node.parserContextFlags & 32 /* JavaScriptFile */); + } + ts.isInJavaScriptFile = isInJavaScriptFile; + /** + * Returns true if the node is a CallExpression to the identifier 'require' with + * exactly one argument. + * This function does not test if the node is in a JavaScript file or not. + */ + function isRequireCall(expression, checkArgumentIsStringLiteral) { + // of the form 'require("name")' + var isRequire = expression.kind === 171 /* CallExpression */ && + expression.expression.kind === 69 /* Identifier */ && + expression.expression.text === "require" && + expression.arguments.length === 1; + return isRequire && (!checkArgumentIsStringLiteral || expression.arguments[0].kind === 9 /* StringLiteral */); + } + ts.isRequireCall = isRequireCall; + /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property + /// assignments we treat as special in the binder + function getSpecialPropertyAssignmentKind(expression) { + if (expression.kind !== 184 /* BinaryExpression */) { + return 0 /* None */; } - function bind(node) { - node.parent = parent; - var savedInStrictMode = inStrictMode; - if (!savedInStrictMode) { - updateStrictMode(node); + var expr = expression; + if (expr.operatorToken.kind !== 56 /* EqualsToken */ || expr.left.kind !== 169 /* PropertyAccessExpression */) { + return 0 /* None */; + } + var lhs = expr.left; + if (lhs.expression.kind === 69 /* Identifier */) { + var lhsId = lhs.expression; + if (lhsId.text === "exports") { + // exports.name = expr + return 1 /* ExportsProperty */; + } + else if (lhsId.text === "module" && lhs.name.text === "exports") { + // module.exports = expr + return 2 /* ModuleExports */; } - // 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; + else if (lhs.expression.kind === 97 /* ThisKeyword */) { + return 4 /* ThisProperty */; + } + else if (lhs.expression.kind === 169 /* PropertyAccessExpression */) { + // chained dot, e.g. x.y.z = expr; this var is the 'x.y' part + var innerPropertyAccess = lhs.expression; + if (innerPropertyAccess.expression.kind === 69 /* Identifier */ && innerPropertyAccess.name.text === "prototype") { + return 3 /* PrototypeProperty */; } } - 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; - } + return 0 /* None */; + } + ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function getExternalModuleName(node) { + if (node.kind === 225 /* ImportDeclaration */) { + return node.moduleSpecifier; + } + if (node.kind === 224 /* ImportEqualsDeclaration */) { + var reference = node.moduleReference; + if (reference.kind === 235 /* ExternalModuleReference */) { + return reference.expression; } } - /// 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'"; + if (node.kind === 231 /* ExportDeclaration */) { + return node.moduleSpecifier; } - function bindWorker(node) { + if (node.kind === 221 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) { + return node.name; + } + } + ts.getExternalModuleName = getExternalModuleName; + function hasQuestionToken(node) { + if (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(); + case 139 /* Parameter */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 249 /* ShorthandPropertyAssignment */: + case 248 /* PropertyAssignment */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: + return node.questionToken !== undefined; } } - function bindSourceFileIfExternalModule() { - setExportContextFlag(file); - if (ts.isExternalModule(file)) { - bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); - } + return false; + } + ts.hasQuestionToken = hasQuestionToken; + function isJSDocConstructSignature(node) { + return node.kind === 264 /* JSDocFunctionType */ && + node.parameters.length > 0 && + node.parameters[0].type.kind === 266 /* JSDocConstructorType */; + } + ts.isJSDocConstructSignature = isJSDocConstructSignature; + function getJSDocTag(node, kind, checkParentVariableStatement) { + if (!node) { + return undefined; } - 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 */); - } + var jsDocComment = getJSDocComment(node, checkParentVariableStatement); + if (!jsDocComment) { + return undefined; } - 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 */); + for (var _i = 0, _a = jsDocComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.kind === kind) { + return tag; + } + } + } + function getJSDocComment(node, checkParentVariableStatement) { + if (node.jsDocComment) { + return node.jsDocComment; + } + // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. + // /** + // * @param {number} name + // * @returns {number} + // */ + // var x = function(name) { return name.length; } + if (checkParentVariableStatement) { + var isInitializerOfVariableDeclarationInStatement = node.parent.kind === 214 /* VariableDeclaration */ && + node.parent.initializer === node && + node.parent.parent.parent.kind === 196 /* VariableStatement */; + var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? node.parent.parent.parent : undefined; + if (variableStatementNode) { + return variableStatementNode.jsDocComment; + } + // Also recognize when the node is the RHS of an assignment expression + var parent_3 = node.parent; + var isSourceOfAssignmentExpressionStatement = parent_3 && parent_3.parent && + parent_3.kind === 184 /* BinaryExpression */ && + parent_3.operatorToken.kind === 56 /* EqualsToken */ && + parent_3.parent.kind === 198 /* ExpressionStatement */; + if (isSourceOfAssignmentExpressionStatement) { + return parent_3.parent.jsDocComment; + } + var isPropertyAssignmentExpression = parent_3 && parent_3.kind === 248 /* PropertyAssignment */; + if (isPropertyAssignmentExpression) { + return parent_3.jsDocComment; } } - function bindImportClause(node) { - if (node.name) { - declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); + return undefined; + } + function getJSDocTypeTag(node) { + return getJSDocTag(node, 272 /* JSDocTypeTag */, /*checkParentVariableStatement*/ false); + } + ts.getJSDocTypeTag = getJSDocTypeTag; + function getJSDocReturnTag(node) { + return getJSDocTag(node, 271 /* JSDocReturnTag */, /*checkParentVariableStatement*/ true); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + function getJSDocTemplateTag(node) { + return getJSDocTag(node, 273 /* JSDocTemplateTag */, /*checkParentVariableStatement*/ false); + } + 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 jsDocComment = getJSDocComment(parameter.parent, /*checkParentVariableStatement*/ true); + if (jsDocComment) { + for (var _i = 0, _a = jsDocComment.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.kind === 270 /* JSDocParameterTag */) { + var parameterTag = tag; + var name_6 = parameterTag.preParameterName || parameterTag.postParameterName; + if (name_6.text === parameterName) { + return parameterTag; + } + } + } } } - 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; + return undefined; + } + 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 === 265 /* JSDocVariadicType */) { + return true; } - } - 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; + var paramTag = getCorrespondingJSDocParameterTag(node); + if (paramTag && paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 265 /* JSDocVariadicType */; } - 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); + return node.dotDotDotToken !== undefined; } + return false; } -})(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.isRestParameter = isRestParameter; + function isLiteralKind(kind) { + return 8 /* FirstLiteralToken */ <= kind && kind <= 11 /* LastLiteralToken */; } - 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.isLiteralKind = isLiteralKind; + function isTextualLiteralKind(kind) { + return kind === 9 /* StringLiteral */ || kind === 11 /* NoSubstitutionTemplateLiteral */; } - ts.getSingleLineStringWriter = getSingleLineStringWriter; - function releaseStringWriter(writer) { - writer.clear(); - stringWriters.push(writer); + ts.isTextualLiteralKind = isTextualLiteralKind; + function isTemplateLiteralKind(kind) { + return 11 /* FirstTemplateToken */ <= kind && kind <= 14 /* LastTemplateToken */; } - ts.releaseStringWriter = releaseStringWriter; - function getFullWidth(node) { - return node.end - node.pos; + ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isBindingPattern(node) { + return !!node && (node.kind === 165 /* ArrayBindingPattern */ || node.kind === 164 /* ObjectBindingPattern */); } - ts.getFullWidth = getFullWidth; - function arrayIsEqualTo(arr1, arr2, comparer) { - if (!arr1 || !arr2) { - return arr1 === arr2; - } - if (arr1.length !== arr2.length) { - return false; + ts.isBindingPattern = isBindingPattern; + function isNodeDescendentOf(node, ancestor) { + while (node) { + if (node === ancestor) + return true; + node = node.parent; } - 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 false; + } + ts.isNodeDescendentOf = isNodeDescendentOf; + function isInAmbientContext(node) { + while (node) { + if (node.flags & (4 /* Ambient */ | 4096 /* DeclarationFile */)) { + return true; } + node = node.parent; } - return true; - } - ts.arrayIsEqualTo = arrayIsEqualTo; - function hasResolvedModule(sourceFile, moduleNameText) { - return sourceFile.resolvedModules && ts.hasProperty(sourceFile.resolvedModules, moduleNameText); + return false; } - ts.hasResolvedModule = hasResolvedModule; - function getResolvedModule(sourceFile, moduleNameText) { - return hasResolvedModule(sourceFile, moduleNameText) ? sourceFile.resolvedModules[moduleNameText] : undefined; + ts.isInAmbientContext = isInAmbientContext; + function isDeclaration(node) { + switch (node.kind) { + case 177 /* ArrowFunction */: + case 166 /* BindingElement */: + case 217 /* ClassDeclaration */: + case 189 /* ClassExpression */: + case 145 /* Constructor */: + case 220 /* EnumDeclaration */: + case 250 /* EnumMember */: + case 233 /* ExportSpecifier */: + case 216 /* FunctionDeclaration */: + case 176 /* FunctionExpression */: + case 146 /* GetAccessor */: + case 226 /* ImportClause */: + case 224 /* ImportEqualsDeclaration */: + case 229 /* ImportSpecifier */: + case 218 /* InterfaceDeclaration */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 221 /* ModuleDeclaration */: + case 227 /* NamespaceImport */: + case 139 /* Parameter */: + case 248 /* PropertyAssignment */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: + case 147 /* SetAccessor */: + case 249 /* ShorthandPropertyAssignment */: + case 219 /* TypeAliasDeclaration */: + case 138 /* TypeParameter */: + case 214 /* VariableDeclaration */: + return true; + } + return false; } - ts.getResolvedModule = getResolvedModule; - function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { - if (!sourceFile.resolvedModules) { - sourceFile.resolvedModules = {}; + ts.isDeclaration = isDeclaration; + function isStatement(n) { + switch (n.kind) { + case 206 /* BreakStatement */: + case 205 /* ContinueStatement */: + case 213 /* DebuggerStatement */: + case 200 /* DoStatement */: + case 198 /* ExpressionStatement */: + case 197 /* EmptyStatement */: + case 203 /* ForInStatement */: + case 204 /* ForOfStatement */: + case 202 /* ForStatement */: + case 199 /* IfStatement */: + case 210 /* LabeledStatement */: + case 207 /* ReturnStatement */: + case 209 /* SwitchStatement */: + case 211 /* ThrowStatement */: + case 212 /* TryStatement */: + case 196 /* VariableStatement */: + case 201 /* WhileStatement */: + case 208 /* WithStatement */: + case 230 /* ExportAssignment */: + return true; + default: + return false; } - 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.isStatement = isStatement; + function isClassElement(n) { + switch (n.kind) { + case 145 /* Constructor */: + case 142 /* PropertyDeclaration */: + case 144 /* MethodDeclaration */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 143 /* MethodSignature */: + case 150 /* IndexSignature */: + return true; + default: + return false; + } } - 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 */; + 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 === 229 /* ImportSpecifier */ || parent.kind === 233 /* ExportSpecifier */) { + if (parent.propertyName) { + return true; } - // 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; + if (isDeclaration(parent)) { + return parent.name === name; } - return node; + return false; } - ts.getSourceFileOfNode = getSourceFileOfNode; - function getStartPositionOfLine(line, sourceFile) { - ts.Debug.assert(line >= 0); - return ts.getLineStarts(sourceFile)[line]; + 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 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 250 /* EnumMember */: + case 248 /* PropertyAssignment */: + case 169 /* PropertyAccessExpression */: + // Name in member declaration or property name in property access + return parent.name === node; + case 136 /* QualifiedName */: + // Name on right hand side of dot in a type query + if (parent.right === node) { + while (parent.kind === 136 /* QualifiedName */) { + parent = parent.parent; + } + return parent.kind === 155 /* TypeQuery */; + } + return false; + case 166 /* BindingElement */: + case 229 /* ImportSpecifier */: + // Property name in binding element or import specifier + return parent.propertyName === node; + case 233 /* ExportSpecifier */: + // Any name in an export specifier + return true; + } + return false; } - 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.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 === 224 /* ImportEqualsDeclaration */ || + node.kind === 226 /* ImportClause */ && !!node.name || + node.kind === 227 /* NamespaceImport */ || + node.kind === 229 /* ImportSpecifier */ || + node.kind === 233 /* ExportSpecifier */ || + node.kind === 230 /* ExportAssignment */ && node.expression.kind === 69 /* Identifier */; } - ts.nodePosToString = nodePosToString; - function getStartPosOfNode(node) { - return node.pos; + ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; + function getClassExtendsHeritageClauseElement(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 83 /* ExtendsKeyword */); + return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } - 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.getClassExtendsHeritageClauseElement = getClassExtendsHeritageClauseElement; + function getClassImplementsHeritageClauseElements(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 106 /* ImplementsKeyword */); + return heritageClause ? heritageClause.types : undefined; } - ts.nodeIsMissing = nodeIsMissing; - function nodeIsPresent(node) { - return !nodeIsMissing(node); + ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; + function getInterfaceBaseTypeNodes(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 83 /* ExtendsKeyword */); + return heritageClause ? heritageClause.types : undefined; } - 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; + ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; + function getHeritageClause(clauses, kind) { + if (clauses) { + for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) { + var clause = clauses_1[_i]; + if (clause.token === kind) { + return clause; + } + } } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + return undefined; } - ts.getTokenPosOfNode = getTokenPosOfNode; - function getNonDecoratorTokenPosOfNode(node, sourceFile) { - if (nodeIsMissing(node) || !node.decorators) { - return getTokenPosOfNode(node, sourceFile); + 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); + return host.getSourceFile(referenceFileName); } - 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 ""; + ts.tryResolveScriptReference = tryResolveScriptReference; + function getAncestor(node, kind) { + while (node) { + if (node.kind === kind) { + return node; + } + node = node.parent; } - var text = sourceFile.text; - return text.substring(includeTrivia ? node.pos : ts.skipTrivia(text, node.pos), node.end); + return undefined; } - ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; - function getTextOfNodeFromSourceText(sourceText, node) { - if (nodeIsMissing(node)) { - return ""; + ts.getAncestor = getAncestor; + function getFileReferenceFromReferencePath(comment, commentRange) { + var simpleReferenceRegEx = /^\/\/\/\s*/gim; + if (simpleReferenceRegEx.test(comment)) { + if (isNoDefaultLibRegEx.test(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 sourceText.substring(ts.skipTrivia(sourceText, node.pos), node.end); + return undefined; } - ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; - function getTextOfNode(node, includeTrivia) { - if (includeTrivia === void 0) { includeTrivia = false; } - return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); + ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; + function isKeyword(token) { + return 70 /* FirstKeyword */ <= token && token <= 135 /* LastKeyword */; } - 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.isKeyword = isKeyword; + function isTrivia(token) { + return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */; } - 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.isTrivia = isTrivia; + function isAsyncFunctionLike(node) { + return isFunctionLike(node) && (node.flags & 256 /* Async */) !== 0 && !isAccessor(node); } - 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.isAsyncFunctionLike = isAsyncFunctionLike; + function isStringOrNumericLiteral(kind) { + return kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */; } - ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; - function isBlockOrCatchScoped(declaration) { - return (getCombinedNodeFlags(declaration) & 49152 /* BlockScoped */) !== 0 || - isCatchClauseVariableDeclaration(declaration); + ts.isStringOrNumericLiteral = isStringOrNumericLiteral; + /** + * 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 && isDynamicName(declaration.name); } - 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; - } + ts.hasDynamicName = hasDynamicName; + function isDynamicName(name) { + return name.kind === 137 /* ComputedPropertyName */ && + !isStringOrNumericLiteral(name.expression.kind) && + !isWellKnownSymbolSyntactically(name.expression); + } + ts.isDynamicName = isDynamicName; + /** + * 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 === 137 /* ComputedPropertyName */) { + var nameExpression = name.expression; + if (isWellKnownSymbolSyntactically(nameExpression)) { + var rightHandSideName = nameExpression.name.text; + return getPropertyNameForKnownSymbolName(rightHandSideName); } - current = current.parent; } + return undefined; } - ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; - function isCatchClauseVariableDeclaration(declaration) { - return declaration && - declaration.kind === 211 /* VariableDeclaration */ && - declaration.parent && - declaration.parent.kind === 244 /* CatchClause */; + ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; + function getPropertyNameForKnownSymbolName(symbolName) { + return "__@" + symbolName; } - 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.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + /** + * Includes the word "Symbol" with unicode escapes + */ + function isESSymbolIdentifier(node) { + return node.kind === 69 /* Identifier */ && node.text === "Symbol"; } - 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.isESSymbolIdentifier = isESSymbolIdentifier; + function isModifierKind(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.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.isModifierKind = isModifierKind; + function isParameterDeclaration(node) { + var root = getRootDeclaration(node); + return root.kind === 139 /* Parameter */; } - 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.isParameterDeclaration = isParameterDeclaration; + function getRootDeclaration(node) { + while (node.kind === 166 /* BindingElement */) { + node = node.parent.parent; + } + return node; } - 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; + ts.getRootDeclaration = getRootDeclaration; + function nodeStartsNewLexicalEnvironment(n) { + return isFunctionLike(n) || n.kind === 221 /* ModuleDeclaration */ || n.kind === 251 /* SourceFile */; + } + ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; + /** + * Creates a shallow, memberwise clone of a node. The "kind", "pos", "end", "flags", and "parent" + * properties are excluded by default, and can be provided via the "location", "flags", and + * "parent" parameters. + * @param node The node to clone. + * @param location An optional TextRange to use to supply the new position. + * @param flags The NodeFlags to use for the cloned node. + * @param parent The parent for the new node. + */ + function cloneNode(node, location, flags, parent) { + // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of + // the original node. We also need to exclude specific properties and only include own- + // properties (to skip members already defined on the shared prototype). + var clone = location !== undefined + ? ts.createNode(node.kind, location.pos, location.end) + : createSynthesizedNode(node.kind); + for (var key in node) { + if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { + continue; + } + clone[key] = node[key]; } - 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); + if (flags !== undefined) { + clone.flags = flags; } - var pos = nodeIsMissing(errorNode) - ? errorNode.pos - : ts.skipTrivia(sourceFile.text, errorNode.pos); - return ts.createTextSpanFromBounds(pos, errorNode.end); + if (parent !== undefined) { + clone.parent = parent; + } + return clone; } - ts.getErrorSpanForNode = getErrorSpanForNode; - function isExternalModule(file) { - return file.externalModuleIndicator !== undefined; + ts.cloneNode = cloneNode; + /** + * Creates a deep clone of an EntityName, with new parent pointers. + * @param node The EntityName to clone. + * @param parent The parent for the cloned node. + */ + function cloneEntityName(node, parent) { + var clone = cloneNode(node, node, node.flags, parent); + if (isQualifiedName(clone)) { + var left = clone.left, right = clone.right; + clone.left = cloneEntityName(left, clone); + clone.right = cloneNode(right, right, right.flags, parent); + } + return clone; } - ts.isExternalModule = isExternalModule; - function isDeclarationFile(file) { - return (file.flags & 8192 /* DeclarationFile */) !== 0; + ts.cloneEntityName = cloneEntityName; + function isQualifiedName(node) { + return node.kind === 136 /* QualifiedName */; } - ts.isDeclarationFile = isDeclarationFile; - function isConstEnumDeclaration(node) { - return node.kind === 217 /* EnumDeclaration */ && isConst(node); + ts.isQualifiedName = isQualifiedName; + function nodeIsSynthesized(node) { + return node.pos === -1; } - ts.isConstEnumDeclaration = isConstEnumDeclaration; - function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 163 /* BindingElement */ || isBindingPattern(node))) { - node = node.parent; - } + ts.nodeIsSynthesized = nodeIsSynthesized; + function createSynthesizedNode(kind, startsOnNewLine) { + var node = ts.createNode(kind, /* pos */ -1, /* end */ -1); + node.startsOnNewLine = startsOnNewLine; 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.createSynthesizedNode = createSynthesizedNode; + function createSynthesizedNodeArray() { + var array = []; + array.pos = -1; + array.end = -1; + return array; } - 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.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; } - } - ts.getJsDocComments = getJsDocComments; - ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; - ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; - function isTypeNode(node) { - if (151 /* FirstTypeNode */ <= node.kind && node.kind <= 160 /* LastTypeNode */) { - return true; + 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; + } } - 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; + 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++; } - 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); + 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); } - } - 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); - } + 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.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; - } + 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)); } - return false; } - ts.isVariableLike = isVariableLike; - function isAccessor(node) { - return node && (node.kind === 145 /* GetAccessor */ || node.kind === 146 /* SetAccessor */); + ts.escapeString = escapeString; + function isIntrinsicJsxName(name) { + var ch = name.substr(0, 1); + return ch.toLowerCase() === ch; } - ts.isAccessor = isAccessor; - function isClassLike(node) { - return node && (node.kind === 214 /* ClassDeclaration */ || node.kind === 186 /* ClassExpression */); + ts.isIntrinsicJsxName = isIntrinsicJsxName; + function get16BitUnicodeEscapeSequence(charCode) { + var hexCharCode = charCode.toString(16).toUpperCase(); + var paddedHexCode = ("0000" + hexCharCode).slice(-4); + return "\\u" + paddedHexCode; } - 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; + 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.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; + ts.escapeNonAsciiCharacters = escapeNonAsciiCharacters; + var indentStrings = ["", " "]; + function getIndentString(level) { + if (indentStrings[level] === undefined) { + indentStrings[level] = getIndentString(level - 1) + indentStrings[1]; } - return false; - } - ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; - function isFunctionBlock(node) { - return node && node.kind === 192 /* Block */ && isFunctionLike(node.parent); + return indentStrings[level]; } - ts.isFunctionBlock = isFunctionBlock; - function isObjectLiteralMethod(node) { - return node && node.kind === 143 /* MethodDeclaration */ && node.parent.kind === 165 /* ObjectLiteralExpression */; + ts.getIndentString = getIndentString; + function getIndentSize() { + return indentStrings[1].length; } - ts.isObjectLiteralMethod = isObjectLiteralMethod; - function getContainingFunction(node) { - while (true) { - node = node.parent; - if (!node || isFunctionLike(node)) { - return node; + ts.getIndentSize = getIndentSize; + function createTextWriter(newLine) { + var output; + var indent; + var lineStart; + var lineCount; + var linePos; + function write(s) { + if (s && s.length) { + if (lineStart) { + output += getIndentString(indent); + lineStart = false; + } + output += s; } } - } - ts.getContainingFunction = getContainingFunction; - function getContainingClass(node) { - while (true) { - node = node.parent; - if (!node || isClassLike(node)) { - return node; - } + function reset() { + output = ""; + indent = 0; + lineStart = true; + lineCount = 0; + linePos = 0; } - } - 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; + function rawWrite(s) { + if (s !== undefined) { + if (lineStart) { + lineStart = false; + } + output += s; } } - } - 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; + 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); + } } } - } - 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; + function writeLine() { + if (!lineStart) { + output += newLine; + lineCount++; + linePos = output.length; + lineStart = true; } } - return undefined; - } - ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; - function getInvokedExpression(node) { - if (node.kind === 170 /* TaggedTemplateExpression */) { - return node.tag; + function writeTextOfNode(text, node) { + write(getTextOfNodeFromSourceText(text, node)); } - // Will either be a CallExpression, NewExpression, or Decorator. - return node.expression; + reset(); + return { + write: write, + rawWrite: rawWrite, + writeTextOfNode: writeTextOfNode, + writeLiteral: writeLiteral, + writeLine: writeLine, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { 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; }, + reset: reset + }; } - 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 */; + ts.createTextWriter = createTextWriter; + /** + * Resolves a local path to a path which is absolute to the base of the emit + */ + function getExternalModuleNameFromPath(host, fileName) { + var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; + var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); + var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.removeFileExtension(relativePath); + } + ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; + function getOwnEmitOutputFilePath(sourceFile, host, extension) { + var compilerOptions = host.getCompilerOptions(); + var emitOutputFilePathWithoutExtension; + if (compilerOptions.outDir) { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); } - return false; + else { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.fileName); + } + return emitOutputFilePathWithoutExtension + extension; } - 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; + ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? 5 /* ES6 */ : 1 /* CommonJS */; + } + ts.getEmitModuleKind = getEmitModuleKind; + function forEachExpectedEmitFile(host, action, targetSourceFile) { + var options = host.getCompilerOptions(); + // Emit on each source file + if (options.outFile || options.out) { + onBundledEmit(host); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var sourceFile = sourceFiles_1[_i]; + if (!isDeclarationFile(sourceFile)) { + onSingleFileEmit(host, sourceFile); } - return false; - case 145 /* GetAccessor */: - if (node.body && node.decorators) { - return true; + } + } + function onSingleFileEmit(host, sourceFile) { + // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. + // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. + // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve + var extension = ".js"; + if (options.jsx === 1 /* Preserve */) { + if (isSourceFileJavaScript(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { + extension = ".jsx"; + } } - return false; - case 143 /* MethodDeclaration */: - case 146 /* SetAccessor */: - if (node.body && node.decorators) { - return true; + else if (sourceFile.languageVariant === 1 /* JSX */) { + // TypeScript source file preserving JSX syntax + extension = ".jsx"; } - return false; + } + var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var emitFileNames = { + jsFilePath: jsFilePath, + sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), + declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitFilePath(jsFilePath, options) : undefined + }; + action(emitFileNames, [sourceFile], /*isBundledEmit*/ false); + } + function onBundledEmit(host) { + // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified + var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && + (!isExternalModule(sourceFile) || + (getEmitModuleKind(options) && isExternalModule(sourceFile))); }); // module that can emit - note falsy value from getEmitModuleKind means the module kind that shouldn't be emitted + if (bundledSources.length) { + var jsFilePath = options.outFile || options.out; + var emitFileNames = { + jsFilePath: jsFilePath, + sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), + declarationFilePath: getDeclarationEmitFilePath(jsFilePath, options) + }; + action(emitFileNames, bundledSources, /*isBundledEmit*/ true); + } } - 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); + function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap ? jsFilePath + ".map" : undefined; + } + function getDeclarationEmitFilePath(jsFilePath, options) { + return options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; } - return false; } - ts.childIsDecorated = childIsDecorated; - function nodeOrChildIsDecorated(node) { - return nodeIsDecorated(node) || childIsDecorated(node); + ts.forEachExpectedEmitFile = forEachExpectedEmitFile; + function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { + var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); + sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); + return ts.combinePaths(newDirPath, sourceFilePath); } - ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; - function isPropertyAccessExpression(node) { - return node.kind === 166 /* PropertyAccessExpression */; + ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + function writeFile(host, diagnostics, fileName, data, writeByteOrderMark) { + host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + }); } - ts.isPropertyAccessExpression = isPropertyAccessExpression; - function isElementAccessExpression(node) { - return node.kind === 167 /* ElementAccessExpression */; + ts.writeFile = writeFile; + function getLineOfLocalPosition(currentSourceFile, pos) { + return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; } - 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.getLineOfLocalPosition = getLineOfLocalPosition; + function getLineOfLocalPositionFromLineMap(lineMap, pos) { + return ts.computeLineAndCharacterOfPosition(lineMap, pos).line; } - ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; - function getExternalModuleImportEqualsDeclarationExpression(node) { - ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node)); - return node.moduleReference.expression; + ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; + function getFirstConstructorWithBody(node) { + return ts.forEach(node.members, function (member) { + if (member.kind === 145 /* Constructor */ && nodeIsPresent(member.body)) { + return member; + } + }); } - ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; - function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 221 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 232 /* ExternalModuleReference */; + ts.getFirstConstructorWithBody = getFirstConstructorWithBody; + function getSetAccessorTypeAnnotationNode(accessor) { + return accessor && accessor.parameters.length > 0 && accessor.parameters[0].type; } - 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; + ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getAllAccessorDeclarations(declarations, accessor) { + var firstAccessor; + var secondAccessor; + var getAccessor; + var setAccessor; + if (hasDynamicName(accessor)) { + firstAccessor = accessor; + if (accessor.kind === 146 /* GetAccessor */) { + getAccessor = accessor; + } + else if (accessor.kind === 147 /* SetAccessor */) { + setAccessor = accessor; + } + else { + ts.Debug.fail("Accessor has wrong kind"); } } - if (node.kind === 228 /* ExportDeclaration */) { - return node.moduleSpecifier; + else { + ts.forEach(declarations, function (member) { + if ((member.kind === 146 /* GetAccessor */ || member.kind === 147 /* SetAccessor */) + && (member.flags & 64 /* Static */) === (accessor.flags & 64 /* 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 === 146 /* GetAccessor */ && !getAccessor) { + getAccessor = member; + } + if (member.kind === 147 /* SetAccessor */ && !setAccessor) { + setAccessor = member; + } + } + } + }); } + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + getAccessor: getAccessor, + setAccessor: setAccessor + }; } - 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; - } + ts.getAllAccessorDeclarations = getAllAccessorDeclarations; + function emitNewLineBeforeLeadingComments(lineMap, 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 && + getLineOfLocalPositionFromLineMap(lineMap, node.pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { + writer.writeLine(); } - 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.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; + function emitComments(text, lineMap, writer, comments, trailingSeparator, newLine, writeComment) { + var emitLeadingSpace = !trailingSeparator; + ts.forEach(comments, function (comment) { + if (emitLeadingSpace) { + writer.write(" "); + emitLeadingSpace = false; + } + writeComment(text, lineMap, 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.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; + ts.emitComments = emitComments; + /** + * Detached comment is a comment at the top of file or function body that is separated from + * the next statement by space. + */ + function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { + var leadingComments; + var currentDetachedCommentInfo; + if (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(text, node.pos), isPinnedComment); + } + } + else { + // removeComments is false, just get detached as normal and bypass the process to filter comment + leadingComments = ts.getLeadingCommentRanges(text, node.pos); + } + if (leadingComments) { + var detachedComments = []; + var lastComment = void 0; + for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { + var comment = leadingComments_1[_i]; + if (lastComment) { + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); + var commentLine = getLineOfLocalPositionFromLineMap(lineMap, 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. + break; + } + } + 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 = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); + var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); + if (nodeLine >= lastCommentLine + 2) { + // Valid detachedComments + emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); + emitComments(text, lineMap, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment); + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; } } } + return currentDetachedCommentInfo; + function isPinnedComment(comment) { + return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && + text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; + } } - 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.emitDetachedComments = emitDetachedComments; + function writeCommentRange(text, lineMap, writer, comment, newLine) { + if (text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { + var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, comment.pos); + var lineCount = lineMap.length; + var firstCommentLineIndent = void 0; + for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { + var nextLineStart = (currentLine + 1) === lineCount + ? text.length + 1 + : lineMap[currentLine + 1]; + 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(text, lineMap[firstCommentLineAndCharacter.line], 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(text, 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(text, comment, writer, newLine, pos, nextLineStart); + pos = nextLineStart; } } + else { + // Single line comment of style //.... + writer.write(text.substring(comment.pos, comment.end)); + } } - 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 */; - } + ts.writeCommentRange = writeCommentRange; + function writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart) { + var end = Math.min(comment.end, nextLineStart - 1); + var currentLineText = 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(); } - 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 */; + else { + // Empty string - make sure we write empty line + writer.writeLiteral(newLine); + } } - ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isBindingPattern(node) { - return !!node && (node.kind === 162 /* ArrayBindingPattern */ || node.kind === 161 /* ObjectBindingPattern */); + function calculateIndent(text, pos, end) { + var currentLineIndent = 0; + for (; pos < end && ts.isWhiteSpace(text.charCodeAt(pos)); pos++) { + if (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.isBindingPattern = isBindingPattern; - function isNodeDescendentOf(node, ancestor) { - while (node) { - if (node === ancestor) - return true; - node = node.parent; + function modifierToFlag(token) { + switch (token) { + case 113 /* StaticKeyword */: return 64 /* Static */; + case 112 /* PublicKeyword */: return 8 /* Public */; + case 111 /* ProtectedKeyword */: return 32 /* Protected */; + case 110 /* PrivateKeyword */: return 16 /* Private */; + case 115 /* AbstractKeyword */: return 128 /* Abstract */; + case 82 /* ExportKeyword */: return 2 /* Export */; + case 122 /* DeclareKeyword */: return 4 /* Ambient */; + case 74 /* ConstKeyword */: return 16384 /* Const */; + case 77 /* DefaultKeyword */: return 512 /* Default */; + case 118 /* AsyncKeyword */: return 256 /* Async */; } - return false; + return 0; } - ts.isNodeDescendentOf = isNodeDescendentOf; - function isInAmbientContext(node) { - while (node) { - if (node.flags & (2 /* Ambient */ | 8192 /* DeclarationFile */)) { - return true; + ts.modifierToFlag = modifierToFlag; + function isLeftHandSideExpression(expr) { + if (expr) { + switch (expr.kind) { + case 169 /* PropertyAccessExpression */: + case 170 /* ElementAccessExpression */: + case 172 /* NewExpression */: + case 171 /* CallExpression */: + case 236 /* JsxElement */: + case 237 /* JsxSelfClosingElement */: + case 173 /* TaggedTemplateExpression */: + case 167 /* ArrayLiteralExpression */: + case 175 /* ParenthesizedExpression */: + case 168 /* ObjectLiteralExpression */: + case 189 /* ClassExpression */: + case 176 /* FunctionExpression */: + case 69 /* Identifier */: + case 10 /* RegularExpressionLiteral */: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 11 /* NoSubstitutionTemplateLiteral */: + case 186 /* TemplateExpression */: + case 84 /* FalseKeyword */: + case 93 /* NullKeyword */: + case 97 /* ThisKeyword */: + case 99 /* TrueKeyword */: + case 95 /* SuperKeyword */: + 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.isLeftHandSideExpression = isLeftHandSideExpression; + function isAssignmentOperator(token) { + return token >= 56 /* FirstAssignment */ && token <= 68 /* LastAssignment */; } - 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.isAssignmentOperator = isAssignmentOperator; + function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return node.kind === 191 /* ExpressionWithTypeArguments */ && + node.parent.token === 83 /* ExtendsKeyword */ && + isClassLike(node.parent.parent); } - 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.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.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; + ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; + function isSupportedExpressionWithTypeArgumentsRest(node) { + if (node.kind === 69 /* Identifier */) { + return true; } - var parent = name.parent; - if (parent.kind === 226 /* ImportSpecifier */ || parent.kind === 230 /* ExportSpecifier */) { - if (parent.propertyName) { - return true; - } + else if (isPropertyAccessExpression(node)) { + return isSupportedExpressionWithTypeArgumentsRest(node.expression); } - if (isDeclaration(parent)) { - return parent.name === name; + else { + return false; } - 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; + function isRightSideOfQualifiedNameOrPropertyAccess(node) { + return (node.parent.kind === 136 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 169 /* PropertyAccessExpression */ && node.parent.name === node); + } + ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; + function isEmptyObjectLiteralOrArrayLiteral(expression) { + var kind = expression.kind; + if (kind === 168 /* ObjectLiteralExpression */) { + return expression.properties.length === 0; + } + if (kind === 167 /* ArrayLiteralExpression */) { + return expression.elements.length === 0; } 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.isEmptyObjectLiteralOrArrayLiteral = isEmptyObjectLiteralOrArrayLiteral; + function getLocalSymbolForExportDefault(symbol) { + return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; } - ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; - function getInterfaceBaseTypeNodes(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 83 /* ExtendsKeyword */); - return heritageClause ? heritageClause.types : undefined; + ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; + function hasJavaScriptFileExtension(fileName) { + return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - 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; - } + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + /** + * 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); } - } - 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; + else if (charCode < 0x800) { + output.push((charCode >> 6) | 192); + output.push((charCode & 63) | 128); } - 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 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 { - 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 - }; - } + ts.Debug.assert(false, "Unexpected code point"); } } - 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); + return output; } - 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. + * Serialize an object graph into a JSON string. This is intended only for use on an acyclic graph + * as the fallback implementation does not check for circular references by default. */ - function hasDynamicName(declaration) { - return declaration.name && - declaration.name.kind === 136 /* ComputedPropertyName */ && - !isWellKnownSymbolSyntactically(declaration.name.expression); - } - ts.hasDynamicName = hasDynamicName; + ts.stringify = typeof JSON !== "undefined" && JSON.stringify + ? JSON.stringify + : stringifyFallback; /** - * Checks if the expression is of the form: - * Symbol.name - * where Symbol is literally the word "Symbol", and name is any identifierName + * Serialize an object graph into a JSON string. */ - function isWellKnownSymbolSyntactically(node) { - return isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); + function stringifyFallback(value) { + // JSON.stringify returns `undefined` here, instead of the string "undefined". + return value === undefined ? undefined : stringifyValue(value); + } + function stringifyValue(value) { + return typeof value === "string" ? "\"" + escapeString(value) + "\"" + : typeof value === "number" ? isFinite(value) ? String(value) : "null" + : typeof value === "boolean" ? value ? "true" : "false" + : typeof value === "object" && value ? ts.isArray(value) ? cycleCheck(stringifyArray, value) : cycleCheck(stringifyObject, value) + : "null"; + } + function cycleCheck(cb, value) { + ts.Debug.assert(!value.hasOwnProperty("__cycle"), "Converting circular structure to JSON"); + value.__cycle = true; + var result = cb(value); + delete value.__cycle; + return result; } - 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; + function stringifyArray(value) { + return "[" + ts.reduceLeft(value, stringifyElement, "") + "]"; } - ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; - function getPropertyNameForKnownSymbolName(symbolName) { - return "__@" + symbolName; + function stringifyElement(memo, value) { + return (memo ? memo + "," : memo) + stringifyValue(value); } - ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; - /** - * Includes the word "Symbol" with unicode escapes - */ - function isESSymbolIdentifier(node) { - return node.kind === 69 /* Identifier */ && node.text === "Symbol"; + function stringifyObject(value) { + return "{" + ts.reduceProperties(value, stringifyProperty, "") + "}"; } - 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; + function stringifyProperty(memo, value, key) { + return value === undefined || typeof value === "function" || key === "__cycle" ? memo + : (memo ? memo + "," : memo) + ("\"" + escapeString(key) + "\":" + stringifyValue(value)); } var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; /** @@ -7138,6 +6914,12 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !ts.isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /* isAbsolutePathAnUrl */ false); + } + ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -7366,38 +7148,34 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 137 /* TypeParameter */) { + if (d && d.kind === 138 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 215 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 218 /* 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()); + function isParameterPropertyDeclaration(node) { + return node.flags & 56 /* AccessibilityModifier */ && node.parent.kind === 145 /* Constructor */ && ts.isClassLike(node.parent.parent); } - ts.arrayStructurallyIsEqualTo = arrayStructurallyIsEqualTo; + ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; })(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))(); + var NodeConstructor; + var SourceFileConstructor; + function createNode(kind, pos, end) { + if (kind === 251 /* SourceFile */) { + return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); + } + else { + return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); + } } ts.createNode = createNode; function visitNode(cbNode, node) { @@ -7412,8 +7190,8 @@ var ts; } function visitEachNode(cbNode, nodes) { if (nodes) { - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; var result = cbNode(node); if (result) { return result; @@ -7435,26 +7213,26 @@ var ts; var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; var cbNodes = cbNodeArray || cbNode; switch (node.kind) { - case 135 /* QualifiedName */: + case 136 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 137 /* TypeParameter */: + case 138 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.expression); - case 246 /* ShorthandPropertyAssignment */: + case 249 /* 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 */: + case 139 /* Parameter */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: + case 248 /* PropertyAssignment */: + case 214 /* VariableDeclaration */: + case 166 /* BindingElement */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.propertyName) || @@ -7463,24 +7241,24 @@ var ts; 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 */: + case 153 /* FunctionType */: + case 154 /* ConstructorType */: + case 148 /* CallSignature */: + case 149 /* ConstructSignature */: + case 150 /* 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 */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 145 /* Constructor */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 176 /* FunctionExpression */: + case 216 /* FunctionDeclaration */: + case 177 /* ArrowFunction */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -7491,290 +7269,290 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 151 /* TypeReference */: + case 152 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNodes, node.typeArguments); - case 150 /* TypePredicate */: + case 151 /* TypePredicate */: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 154 /* TypeQuery */: + case 155 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 155 /* TypeLiteral */: + case 156 /* TypeLiteral */: return visitNodes(cbNodes, node.members); - case 156 /* ArrayType */: + case 157 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 157 /* TupleType */: + case 158 /* TupleType */: return visitNodes(cbNodes, node.elementTypes); - case 158 /* UnionType */: - case 159 /* IntersectionType */: + case 159 /* UnionType */: + case 160 /* IntersectionType */: return visitNodes(cbNodes, node.types); - case 160 /* ParenthesizedType */: + case 161 /* ParenthesizedType */: return visitNode(cbNode, node.type); - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: + case 164 /* ObjectBindingPattern */: + case 165 /* ArrayBindingPattern */: return visitNodes(cbNodes, node.elements); - case 164 /* ArrayLiteralExpression */: + case 167 /* ArrayLiteralExpression */: return visitNodes(cbNodes, node.elements); - case 165 /* ObjectLiteralExpression */: + case 168 /* ObjectLiteralExpression */: return visitNodes(cbNodes, node.properties); - case 166 /* PropertyAccessExpression */: + case 169 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); - case 167 /* ElementAccessExpression */: + case 170 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 171 /* CallExpression */: + case 172 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments) || visitNodes(cbNodes, node.arguments); - case 170 /* TaggedTemplateExpression */: + case 173 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || visitNode(cbNode, node.template); - case 171 /* TypeAssertionExpression */: + case 174 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 172 /* ParenthesizedExpression */: + case 175 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 175 /* DeleteExpression */: + case 178 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 176 /* TypeOfExpression */: + case 179 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 177 /* VoidExpression */: + case 180 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 179 /* PrefixUnaryExpression */: + case 182 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 184 /* YieldExpression */: + case 187 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 178 /* AwaitExpression */: + case 181 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 180 /* PostfixUnaryExpression */: + case 183 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 181 /* BinaryExpression */: + case 184 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 189 /* AsExpression */: + case 192 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 182 /* ConditionalExpression */: + case 185 /* 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 */: + case 188 /* SpreadElementExpression */: return visitNode(cbNode, node.expression); - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 195 /* Block */: + case 222 /* ModuleBlock */: return visitNodes(cbNodes, node.statements); - case 248 /* SourceFile */: + case 251 /* SourceFile */: return visitNodes(cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 193 /* VariableStatement */: + case 196 /* VariableStatement */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 212 /* VariableDeclarationList */: + case 215 /* VariableDeclarationList */: return visitNodes(cbNodes, node.declarations); - case 195 /* ExpressionStatement */: + case 198 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 196 /* IfStatement */: + case 199 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 197 /* DoStatement */: + case 200 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 198 /* WhileStatement */: + case 201 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 199 /* ForStatement */: + case 202 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 200 /* ForInStatement */: + case 203 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 201 /* ForOfStatement */: + case 204 /* ForOfStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 202 /* ContinueStatement */: - case 203 /* BreakStatement */: + case 205 /* ContinueStatement */: + case 206 /* BreakStatement */: return visitNode(cbNode, node.label); - case 204 /* ReturnStatement */: + case 207 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 205 /* WithStatement */: + case 208 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 206 /* SwitchStatement */: + case 209 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 220 /* CaseBlock */: + case 223 /* CaseBlock */: return visitNodes(cbNodes, node.clauses); - case 241 /* CaseClause */: + case 244 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.statements); - case 242 /* DefaultClause */: + case 245 /* DefaultClause */: return visitNodes(cbNodes, node.statements); - case 207 /* LabeledStatement */: + case 210 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 208 /* ThrowStatement */: + case 211 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 209 /* TryStatement */: + case 212 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 244 /* CatchClause */: + case 247 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 139 /* Decorator */: + case 140 /* Decorator */: return visitNode(cbNode, node.expression); - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 217 /* ClassDeclaration */: + case 189 /* 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 */: + case 218 /* 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 */: + case 219 /* 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 */: + case 220 /* EnumDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNodes, node.members); - case 247 /* EnumMember */: + case 250 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 218 /* ModuleDeclaration */: + case 221 /* ModuleDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 221 /* ImportEqualsDeclaration */: + case 224 /* ImportEqualsDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 222 /* ImportDeclaration */: + case 225 /* ImportDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 223 /* ImportClause */: + case 226 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 224 /* NamespaceImport */: + case 227 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 225 /* NamedImports */: - case 229 /* NamedExports */: + case 228 /* NamedImports */: + case 232 /* NamedExports */: return visitNodes(cbNodes, node.elements); - case 228 /* ExportDeclaration */: + case 231 /* ExportDeclaration */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 226 /* ImportSpecifier */: - case 230 /* ExportSpecifier */: + case 229 /* ImportSpecifier */: + case 233 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 227 /* ExportAssignment */: + case 230 /* ExportAssignment */: return visitNodes(cbNodes, node.decorators) || visitNodes(cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 183 /* TemplateExpression */: + case 186 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 190 /* TemplateSpan */: + case 193 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 136 /* ComputedPropertyName */: + case 137 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 243 /* HeritageClause */: + case 246 /* HeritageClause */: return visitNodes(cbNodes, node.types); - case 188 /* ExpressionWithTypeArguments */: + case 191 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNodes, node.typeArguments); - case 232 /* ExternalModuleReference */: + case 235 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 231 /* MissingDeclaration */: + case 234 /* MissingDeclaration */: return visitNodes(cbNodes, node.decorators); - case 233 /* JsxElement */: + case 236 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 234 /* JsxSelfClosingElement */: - case 235 /* JsxOpeningElement */: + case 237 /* JsxSelfClosingElement */: + case 238 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || visitNodes(cbNodes, node.attributes); - case 238 /* JsxAttribute */: + case 241 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 239 /* JsxSpreadAttribute */: + case 242 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 240 /* JsxExpression */: + case 243 /* JsxExpression */: return visitNode(cbNode, node.expression); - case 237 /* JsxClosingElement */: + case 240 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 249 /* JSDocTypeExpression */: + case 252 /* JSDocTypeExpression */: return visitNode(cbNode, node.type); - case 253 /* JSDocUnionType */: + case 256 /* JSDocUnionType */: return visitNodes(cbNodes, node.types); - case 254 /* JSDocTupleType */: + case 257 /* JSDocTupleType */: return visitNodes(cbNodes, node.types); - case 252 /* JSDocArrayType */: + case 255 /* JSDocArrayType */: return visitNode(cbNode, node.elementType); - case 256 /* JSDocNonNullableType */: + case 259 /* JSDocNonNullableType */: return visitNode(cbNode, node.type); - case 255 /* JSDocNullableType */: + case 258 /* JSDocNullableType */: return visitNode(cbNode, node.type); - case 257 /* JSDocRecordType */: + case 260 /* JSDocRecordType */: return visitNodes(cbNodes, node.members); - case 259 /* JSDocTypeReference */: + case 262 /* JSDocTypeReference */: return visitNode(cbNode, node.name) || visitNodes(cbNodes, node.typeArguments); - case 260 /* JSDocOptionalType */: + case 263 /* JSDocOptionalType */: return visitNode(cbNode, node.type); - case 261 /* JSDocFunctionType */: + case 264 /* JSDocFunctionType */: return visitNodes(cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 262 /* JSDocVariadicType */: + case 265 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 263 /* JSDocConstructorType */: + case 266 /* JSDocConstructorType */: return visitNode(cbNode, node.type); - case 264 /* JSDocThisType */: + case 267 /* JSDocThisType */: return visitNode(cbNode, node.type); - case 258 /* JSDocRecordMember */: + case 261 /* JSDocRecordMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.type); - case 265 /* JSDocComment */: + case 268 /* JSDocComment */: return visitNodes(cbNodes, node.tags); - case 267 /* JSDocParameterTag */: + case 270 /* JSDocParameterTag */: return visitNode(cbNode, node.preParameterName) || visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.postParameterName); - case 268 /* JSDocReturnTag */: + case 271 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 269 /* JSDocTypeTag */: + case 272 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 270 /* JSDocTemplateTag */: + case 273 /* JSDocTemplateTag */: return visitNodes(cbNodes, node.typeParameters); } } @@ -7820,6 +7598,9 @@ var ts; // 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 */; + // capture constructors in 'initializeState' to avoid null checks + var NodeConstructor; + var SourceFileConstructor; var sourceFile; var parseDiagnostics; var syntaxCursor; @@ -7905,13 +7686,20 @@ var ts; // attached to the EOF token. var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, _sourceText, languageVersion, _syntaxCursor, setParentNodes) { - initializeState(fileName, _sourceText, languageVersion, _syntaxCursor); + var isJavaScriptFile = ts.hasJavaScriptFileExtension(fileName) || _sourceText.lastIndexOf("// @language=javascript", 0) === 0; + initializeState(fileName, _sourceText, languageVersion, isJavaScriptFile, _syntaxCursor); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes); clearState(); return result; } Parser.parseSourceFile = parseSourceFile; - function initializeState(fileName, _sourceText, languageVersion, _syntaxCursor) { + function getLanguageVariant(fileName) { + // .tsx and .jsx files are treated as jsx language variant. + return ts.fileExtensionIs(fileName, ".tsx") || ts.fileExtensionIs(fileName, ".jsx") || ts.fileExtensionIs(fileName, ".js") ? 1 /* JSX */ : 0 /* Standard */; + } + function initializeState(fileName, _sourceText, languageVersion, isJavaScriptFile, _syntaxCursor) { + NodeConstructor = ts.objectAllocator.getNodeConstructor(); + SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); sourceText = _sourceText; syntaxCursor = _syntaxCursor; parseDiagnostics = []; @@ -7919,13 +7707,13 @@ var ts; identifiers = {}; identifierCount = 0; nodeCount = 0; - contextFlags = ts.isJavaScript(fileName) ? 32 /* JavaScriptFile */ : 0 /* None */; + contextFlags = isJavaScriptFile ? 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 */); + scanner.setLanguageVariant(getLanguageVariant(fileName)); } function clearState() { // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. @@ -7940,6 +7728,9 @@ var ts; } function parseSourceFileWorker(fileName, languageVersion, setParentNodes) { sourceFile = createSourceFile(fileName, languageVersion); + if (contextFlags & 32 /* JavaScriptFile */) { + sourceFile.parserContextFlags = 32 /* JavaScriptFile */; + } // Prime the scanner. token = nextToken(); processReferenceComments(sourceFile); @@ -7954,40 +7745,22 @@ var ts; 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; + if (contextFlags & 32 /* JavaScriptFile */) { + var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); + if (comments) { + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; + var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (jsDocComment) { + node.jsDocComment = jsDocComment; + } } } } + return node; } function fixupParentReferences(sourceFile) { // normally parent references are set during binding. However, for clients that only need @@ -8012,15 +7785,16 @@ var ts; } Parser.fixupParentReferences = fixupParentReferences; function createSourceFile(fileName, languageVersion) { - var sourceFile = createNode(248 /* SourceFile */, /*pos*/ 0); - sourceFile.pos = 0; - sourceFile.end = sourceText.length; + // code from createNode is inlined here so createNode won't have to deal with special case of creating source files + // this is quite rare comparing to other nodes and createNode should be as fast as possible + var sourceFile = new SourceFileConstructor(251 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + nodeCount++; 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 */; + sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 4096 /* DeclarationFile */ : 0; + sourceFile.languageVariant = getLanguageVariant(sourceFile.fileName); return sourceFile; } function setContextFlag(val, flag) { @@ -8053,10 +7827,10 @@ var ts; var contextFlagsToClear = context & contextFlags; if (contextFlagsToClear) { // clear the requested context flags - setContextFlag(false, contextFlagsToClear); + setContextFlag(/*val*/ false, contextFlagsToClear); var result = func(); // restore the context flags we just cleared - setContextFlag(true, contextFlagsToClear); + setContextFlag(/*val*/ true, contextFlagsToClear); return result; } // no need to do anything special as we are not in any of the requested contexts @@ -8072,10 +7846,10 @@ var ts; var contextFlagsToSet = context & ~contextFlags; if (contextFlagsToSet) { // set the requested context flags - setContextFlag(true, contextFlagsToSet); + setContextFlag(/*val*/ true, contextFlagsToSet); var result = func(); // reset the context flags we just set - setContextFlag(false, contextFlagsToSet); + setContextFlag(/*val*/ false, contextFlagsToSet); return result; } // no need to do anything special as we are already in all of the requested contexts @@ -8090,9 +7864,6 @@ var ts; function doInYieldContext(func) { return doInsideOfContext(2 /* Yield */, func); } - function doOutsideOfYieldContext(func) { - return doOutsideOfContext(2 /* Yield */, func); - } function doInDecoratorContext(func) { return doInsideOfContext(4 /* Decorator */, func); } @@ -8105,9 +7876,6 @@ var ts; 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; } @@ -8151,9 +7919,6 @@ var ts; function nextToken() { return token = scanner.scan(); } - function getTokenPos(pos) { - return ts.skipTrivia(sourceText, pos); - } function reScanGreaterToken() { return token = scanner.reScanGreaterToken(); } @@ -8196,16 +7961,18 @@ var ts; } 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. + /** 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. + /** 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); } @@ -8285,15 +8052,13 @@ var ts; return parseExpected(23 /* SemicolonToken */); } } + // note: this function creates only node 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; + return new NodeConstructor(kind, pos, pos); } function finishNode(node, end) { node.end = end === undefined ? scanner.getStartPos() : end; @@ -8362,10 +8127,10 @@ var ts; return parseIdentifierName(); } function parsePropertyName() { - return parsePropertyNameWorker(/*allowComputedPropertyNames:*/ true); + return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true); } function parseSimplePropertyName() { - return parsePropertyNameWorker(/*allowComputedPropertyNames:*/ false); + return parsePropertyNameWorker(/*allowComputedPropertyNames*/ false); } function isSimplePropertyName() { return token === 9 /* StringLiteral */ || token === 8 /* NumericLiteral */ || ts.tokenIsIdentifierOrKeyword(token); @@ -8374,7 +8139,7 @@ var ts; // PropertyName [Yield]: // LiteralPropertyName // ComputedPropertyName[?Yield] - var node = createNode(136 /* ComputedPropertyName */); + var node = createNode(137 /* 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 @@ -8386,6 +8151,13 @@ var ts; function parseContextualModifier(t) { return token === t && tryParse(nextTokenCanFollowModifier); } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } function nextTokenCanFollowModifier() { if (token === 74 /* ConstKeyword */) { // 'const' is only a modifier if followed by 'enum'. @@ -8405,14 +8177,10 @@ var ts; nextToken(); return canFollowModifier(); } - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return false; - } - return canFollowModifier(); + return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { - return ts.isModifier(token) && tryParse(nextTokenCanFollowModifier); + return ts.isModifierKind(token) && tryParse(nextTokenCanFollowModifier); } function canFollowModifier() { return token === 19 /* OpenBracketToken */ @@ -8458,7 +8226,7 @@ var ts; case 12 /* ObjectLiteralMembers */: return token === 19 /* OpenBracketToken */ || token === 37 /* AsteriskToken */ || isLiteralPropertyName(); case 9 /* ObjectBindingElements */: - return isLiteralPropertyName(); + return token === 19 /* OpenBracketToken */ || 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. @@ -8618,7 +8386,7 @@ var ts; function isInSomeParsingContext() { for (var kind = 0; kind < 26 /* Count */; kind++) { if (parsingContext & (1 << kind)) { - if (isListElement(kind, /* inErrorRecovery */ true) || isListTerminator(kind)) { + if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { return true; } } @@ -8632,7 +8400,7 @@ var ts; var result = []; result.pos = getNodePos(); while (!isListTerminator(kind)) { - if (isListElement(kind, /* inErrorRecovery */ false)) { + if (isListElement(kind, /*inErrorRecovery*/ false)) { var element = parseListElement(kind, parseElement); result.push(element); continue; @@ -8772,14 +8540,14 @@ var ts; 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 */: + case 145 /* Constructor */: + case 150 /* IndexSignature */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 142 /* PropertyDeclaration */: + case 194 /* SemicolonClassElement */: return true; - case 143 /* MethodDeclaration */: + case 144 /* 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. @@ -8794,8 +8562,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + case 244 /* CaseClause */: + case 245 /* DefaultClause */: return true; } } @@ -8804,58 +8572,58 @@ var ts; 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 */: + case 216 /* FunctionDeclaration */: + case 196 /* VariableStatement */: + case 195 /* Block */: + case 199 /* IfStatement */: + case 198 /* ExpressionStatement */: + case 211 /* ThrowStatement */: + case 207 /* ReturnStatement */: + case 209 /* SwitchStatement */: + case 206 /* BreakStatement */: + case 205 /* ContinueStatement */: + case 203 /* ForInStatement */: + case 204 /* ForOfStatement */: + case 202 /* ForStatement */: + case 201 /* WhileStatement */: + case 208 /* WithStatement */: + case 197 /* EmptyStatement */: + case 212 /* TryStatement */: + case 210 /* LabeledStatement */: + case 200 /* DoStatement */: + case 213 /* DebuggerStatement */: + case 225 /* ImportDeclaration */: + case 224 /* ImportEqualsDeclaration */: + case 231 /* ExportDeclaration */: + case 230 /* ExportAssignment */: + case 221 /* ModuleDeclaration */: + case 217 /* ClassDeclaration */: + case 218 /* InterfaceDeclaration */: + case 220 /* EnumDeclaration */: + case 219 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 247 /* EnumMember */; + return node.kind === 250 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 148 /* ConstructSignature */: - case 142 /* MethodSignature */: - case 149 /* IndexSignature */: - case 140 /* PropertySignature */: - case 147 /* CallSignature */: + case 149 /* ConstructSignature */: + case 143 /* MethodSignature */: + case 150 /* IndexSignature */: + case 141 /* PropertySignature */: + case 148 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 211 /* VariableDeclaration */) { + if (node.kind !== 214 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -8876,7 +8644,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 138 /* Parameter */) { + if (node.kind !== 139 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -8931,7 +8699,7 @@ var ts; result.pos = getNodePos(); var commaStart = -1; // Meaning the previous token was not a comma while (true) { - if (isListElement(kind, /* inErrorRecovery */ false)) { + if (isListElement(kind, /*inErrorRecovery*/ false)) { result.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); if (parseOptional(24 /* CommaToken */)) { @@ -8993,7 +8761,7 @@ var ts; function parseEntityName(allowReservedWords, diagnosticMessage) { var entity = parseIdentifier(diagnosticMessage); while (parseOptional(21 /* DotToken */)) { - var node = createNode(135 /* QualifiedName */, entity.pos); + var node = createNode(136 /* QualifiedName */, entity.pos); node.left = entity; node.right = parseRightSideOfDot(allowReservedWords); entity = finishNode(node); @@ -9026,14 +8794,14 @@ var ts; // 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 createMissingNode(69 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); } } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(183 /* TemplateExpression */); - template.head = parseLiteralNode(); + var template = createNode(186 /* TemplateExpression */); + template.head = parseTemplateLiteralFragment(); ts.Debug.assert(template.head.kind === 12 /* TemplateHead */, "Template head has wrong token kind"); var templateSpans = []; templateSpans.pos = getNodePos(); @@ -9045,12 +8813,12 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(190 /* TemplateSpan */); + var span = createNode(193 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; if (token === 16 /* CloseBraceToken */) { reScanTemplateToken(); - literal = parseLiteralNode(); + literal = parseTemplateLiteralFragment(); } else { literal = parseExpectedToken(14 /* TemplateTail */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(16 /* CloseBraceToken */)); @@ -9058,8 +8826,17 @@ var ts; span.literal = literal; return finishNode(span); } + function parseStringLiteralTypeNode() { + return parseLiteralLikeNode(163 /* StringLiteralType */, /*internName*/ true); + } function parseLiteralNode(internName) { - var node = createNode(token); + return parseLiteralLikeNode(token, internName); + } + function parseTemplateLiteralFragment() { + return parseLiteralLikeNode(token, /*internName*/ false); + } + function parseLiteralLikeNode(kind, internName) { + var node = createNode(kind); var text = scanner.getTokenValue(); node.text = internName ? internIdentifier(text) : text; if (scanner.hasExtendedUnicodeEscape()) { @@ -9080,35 +8857,40 @@ var ts; if (node.kind === 8 /* NumericLiteral */ && sourceText.charCodeAt(tokenPos) === 48 /* _0 */ && ts.isOctalDigit(sourceText.charCodeAt(tokenPos + 1))) { - node.flags |= 65536 /* OctalLiteral */; + node.flags |= 32768 /* OctalLiteral */; } return node; } // TYPES - function parseTypeReferenceOrTypePredicate() { + function parseTypeReference() { 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); + var node = createNode(152 /* 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 parseThisTypePredicate(lhs) { + nextToken(); + var node = createNode(151 /* TypePredicate */, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(162 /* ThisType */); + nextToken(); + return finishNode(node); + } function parseTypeQuery() { - var node = createNode(154 /* TypeQuery */); + var node = createNode(155 /* TypeQuery */); parseExpected(101 /* TypeOfKeyword */); node.exprName = parseEntityName(/*allowReservedWords*/ true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(137 /* TypeParameter */); + var node = createNode(138 /* TypeParameter */); node.name = parseIdentifier(); if (parseOptional(83 /* ExtendsKeyword */)) { // It's not uncommon for people to write improper constraints to a generic. If the @@ -9138,14 +8920,12 @@ var ts; } function parseParameterType() { if (parseOptional(54 /* ColonToken */)) { - return token === 9 /* StringLiteral */ - ? parseLiteralNode(/*internName*/ true) - : parseType(); + return parseType(); } return undefined; } function isStartOfParameter() { - return token === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifier(token) || token === 55 /* AtToken */; + return token === 22 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token) || token === 55 /* AtToken */; } function setModifiers(node, modifiers) { if (modifiers) { @@ -9154,14 +8934,14 @@ var ts; } } function parseParameter() { - var node = createNode(138 /* Parameter */); + var node = createNode(139 /* 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)) { + if (ts.getFullWidth(node.name) === 0 && node.flags === 0 && ts.isModifierKind(token)) { // in cases like // 'use strict' // function foo(static) @@ -9183,7 +8963,7 @@ var ts; // contexts. In addition, parameter initializers are semantically disallowed in // overload signatures. So parameter initializers are transitively disallowed in // ambient contexts. - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseBindingElementInitializer(inParameter) { return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); @@ -9197,10 +8977,10 @@ var ts; signature.parameters = parseParameterList(yieldContext, awaitContext, requireCompleteParameterList); if (returnTokenRequired) { parseExpected(returnToken); - signature.type = parseType(); + signature.type = parseTypeOrTypePredicate(); } else if (parseOptional(returnToken)) { - signature.type = parseType(); + signature.type = parseTypeOrTypePredicate(); } } function parseParameterList(yieldContext, awaitContext, requireCompleteParameterList) { @@ -9248,7 +9028,7 @@ var ts; } function parseSignatureMember(kind) { var node = createNode(kind); - if (kind === 148 /* ConstructSignature */) { + if (kind === 149 /* ConstructSignature */) { parseExpected(92 /* NewKeyword */); } fillSignature(54 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); @@ -9282,7 +9062,7 @@ var ts; if (token === 22 /* DotDotDotToken */ || token === 20 /* CloseBracketToken */) { return true; } - if (ts.isModifier(token)) { + if (ts.isModifierKind(token)) { nextToken(); if (isIdentifier()) { return true; @@ -9312,7 +9092,7 @@ var ts; return token === 54 /* ColonToken */ || token === 24 /* CommaToken */ || token === 20 /* CloseBracketToken */; } function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(149 /* IndexSignature */, fullStart); + var node = createNode(150 /* IndexSignature */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 19 /* OpenBracketToken */, 20 /* CloseBracketToken */); @@ -9325,7 +9105,7 @@ var ts; var name = parsePropertyName(); var questionToken = parseOptionalToken(53 /* QuestionToken */); if (token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */) { - var method = createNode(142 /* MethodSignature */, fullStart); + var method = createNode(143 /* MethodSignature */, fullStart); method.name = name; method.questionToken = questionToken; // Method signatues don't exist in expression contexts. So they have neither @@ -9335,10 +9115,16 @@ var ts; return finishNode(method); } else { - var property = createNode(140 /* PropertySignature */, fullStart); + var property = createNode(141 /* PropertySignature */, fullStart); property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); + if (token === 56 /* EqualsToken */) { + // Although type literal properties cannot not have initializers, we attempt + // to parse an initializer so we can report in the checker that an interface + // property or type literal property cannot have an initializer. + property.initializer = parseNonParameterInitializer(); + } parseTypeMemberSemicolon(); return finishNode(property); } @@ -9350,7 +9136,7 @@ var ts; case 19 /* OpenBracketToken */: return true; default: - if (ts.isModifier(token)) { + if (ts.isModifierKind(token)) { var result = lookAhead(isStartOfIndexSignatureDeclaration); if (result) { return result; @@ -9360,7 +9146,7 @@ var ts; } } function isStartOfIndexSignatureDeclaration() { - while (ts.isModifier(token)) { + while (ts.isModifierKind(token)) { nextToken(); } return isIndexSignature(); @@ -9377,7 +9163,7 @@ var ts; switch (token) { case 17 /* OpenParenToken */: case 25 /* LessThanToken */: - return parseSignatureMember(147 /* CallSignature */); + return parseSignatureMember(148 /* CallSignature */); case 19 /* OpenBracketToken */: // Indexer or computed property return isIndexSignature() @@ -9385,7 +9171,7 @@ var ts; : parsePropertyOrMethodSignature(); case 92 /* NewKeyword */: if (lookAhead(isStartOfConstructSignature)) { - return parseSignatureMember(148 /* ConstructSignature */); + return parseSignatureMember(149 /* ConstructSignature */); } // fall through. case 9 /* StringLiteral */: @@ -9398,7 +9184,7 @@ var ts; // 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)) { + if (ts.isModifierKind(token)) { var result = tryParse(parseIndexSignatureWithModifiers); if (result) { return result; @@ -9422,7 +9208,7 @@ var ts; return token === 17 /* OpenParenToken */ || token === 25 /* LessThanToken */; } function parseTypeLiteral() { - var node = createNode(155 /* TypeLiteral */); + var node = createNode(156 /* TypeLiteral */); node.members = parseObjectTypeMembers(); return finishNode(node); } @@ -9438,12 +9224,12 @@ var ts; return members; } function parseTupleType() { - var node = createNode(157 /* TupleType */); + var node = createNode(158 /* TupleType */); node.elementTypes = parseBracketedList(19 /* TupleElementTypes */, parseType, 19 /* OpenBracketToken */, 20 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(160 /* ParenthesizedType */); + var node = createNode(161 /* ParenthesizedType */); parseExpected(17 /* OpenParenToken */); node.type = parseType(); parseExpected(18 /* CloseParenToken */); @@ -9451,7 +9237,7 @@ var ts; } function parseFunctionOrConstructorType(kind) { var node = createNode(kind); - if (kind === 153 /* ConstructorType */) { + if (kind === 154 /* ConstructorType */) { parseExpected(92 /* NewKeyword */); } fillSignature(34 /* EqualsGreaterThanToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); @@ -9470,10 +9256,20 @@ var ts; 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(); + return node || parseTypeReference(); + case 9 /* StringLiteral */: + return parseStringLiteralTypeNode(); case 103 /* VoidKeyword */: - case 97 /* ThisKeyword */: return parseTokenNode(); + case 97 /* ThisKeyword */: { + var thisKeyword = parseThisTypeNode(); + if (token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + return parseThisTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } case 101 /* TypeOfKeyword */: return parseTypeQuery(); case 15 /* OpenBraceToken */: @@ -9483,7 +9279,7 @@ var ts; case 17 /* OpenParenToken */: return parseParenthesizedType(); default: - return parseTypeReferenceOrTypePredicate(); + return parseTypeReference(); } } function isStartOfType() { @@ -9500,6 +9296,7 @@ var ts; case 19 /* OpenBracketToken */: case 25 /* LessThanToken */: case 92 /* NewKeyword */: + case 9 /* StringLiteral */: return true; case 17 /* OpenParenToken */: // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, @@ -9517,7 +9314,7 @@ var ts; var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak() && parseOptional(19 /* OpenBracketToken */)) { parseExpected(20 /* CloseBracketToken */); - var node = createNode(156 /* ArrayType */, type.pos); + var node = createNode(157 /* ArrayType */, type.pos); node.elementType = type; type = finishNode(node); } @@ -9539,10 +9336,10 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(159 /* IntersectionType */, parseArrayTypeOrHigher, 46 /* AmpersandToken */); + return parseUnionOrIntersectionType(160 /* IntersectionType */, parseArrayTypeOrHigher, 46 /* AmpersandToken */); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(158 /* UnionType */, parseIntersectionTypeOrHigher, 47 /* BarToken */); + return parseUnionOrIntersectionType(159 /* UnionType */, parseIntersectionTypeOrHigher, 47 /* BarToken */); } function isStartOfFunctionType() { if (token === 25 /* LessThanToken */) { @@ -9557,11 +9354,11 @@ var ts; // ( ... return true; } - if (isIdentifier() || ts.isModifier(token)) { + if (isIdentifier() || ts.isModifierKind(token)) { nextToken(); if (token === 54 /* ColonToken */ || token === 24 /* CommaToken */ || token === 53 /* QuestionToken */ || token === 56 /* EqualsToken */ || - isIdentifier() || ts.isModifier(token)) { + isIdentifier() || ts.isModifierKind(token)) { // ( id : // ( id , // ( id ? @@ -9579,6 +9376,26 @@ var ts; } return false; } + function parseTypeOrTypePredicate() { + var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); + var type = parseType(); + if (typePredicateVariable) { + var node = createNode(151 /* TypePredicate */, typePredicateVariable.pos); + node.parameterName = typePredicateVariable; + node.type = type; + return finishNode(node); + } + else { + return type; + } + } + function parseTypePredicatePrefix() { + var id = parseIdentifier(); + if (token === 124 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + return id; + } + } 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. @@ -9586,10 +9403,10 @@ var ts; } function parseTypeWorker() { if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(152 /* FunctionType */); + return parseFunctionOrConstructorType(153 /* FunctionType */); } if (token === 92 /* NewKeyword */) { - return parseFunctionOrConstructorType(153 /* ConstructorType */); + return parseFunctionOrConstructorType(154 /* ConstructorType */); } return parseUnionTypeOrHigher(); } @@ -9662,9 +9479,6 @@ var ts; token !== 55 /* AtToken */ && isStartOfExpression(); } - function allowInAndParseExpression() { - return allowInAnd(parseExpression); - } function parseExpression() { // Expression[in]: // AssignmentExpression[in] @@ -9672,7 +9486,7 @@ var ts; // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext(false); + setDecoratorContext(/*val*/ false); } var expr = parseAssignmentExpressionOrHigher(); var operatorToken; @@ -9680,7 +9494,7 @@ var ts; expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); } if (saveDecoratorContext) { - setDecoratorContext(true); + setDecoratorContext(/*val*/ true); } return expr; } @@ -9785,7 +9599,7 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(184 /* YieldExpression */); + var node = createNode(187 /* YieldExpression */); // YieldExpression[In] : // yield // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] @@ -9805,14 +9619,14 @@ var ts; } 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); + var node = createNode(177 /* ArrowFunction */, identifier.pos); + var parameter = createNode(139 /* 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.equalsGreaterThanToken = parseExpectedToken(34 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); node.body = parseArrowFunctionExpressionBody(/*isAsync*/ false); return finishNode(node); } @@ -9833,7 +9647,7 @@ var ts; // Didn't appear to actually be a parenthesized arrow function. Just bail out. return undefined; } - var isAsync = !!(arrowFunction.flags & 512 /* Async */); + var isAsync = !!(arrowFunction.flags & 256 /* 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; @@ -9958,9 +9772,9 @@ var ts; return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false); } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(174 /* ArrowFunction */); + var node = createNode(177 /* ArrowFunction */); setModifiers(node, parseModifiersForArrowFunction()); - var isAsync = !!(node.flags & 512 /* Async */); + var isAsync = !!(node.flags & 256 /* Async */); // Arrow functions are never generators. // // If we're speculatively parsing a signature for a parenthesized arrow function, then @@ -10024,7 +9838,7 @@ var ts; } // 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); + var node = createNode(185 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -10037,7 +9851,7 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 90 /* InKeyword */ || t === 134 /* OfKeyword */; + return t === 90 /* InKeyword */ || t === 135 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { @@ -10145,39 +9959,39 @@ var ts; return -1; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(181 /* BinaryExpression */, left.pos); + var node = createNode(184 /* 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); + var node = createNode(192 /* AsExpression */, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(179 /* PrefixUnaryExpression */); + var node = createNode(182 /* PrefixUnaryExpression */); node.operator = token; nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(175 /* DeleteExpression */); + var node = createNode(178 /* DeleteExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(176 /* TypeOfExpression */); + var node = createNode(179 /* TypeOfExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(177 /* VoidExpression */); + var node = createNode(180 /* VoidExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -10193,7 +10007,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(178 /* AwaitExpression */); + var node = createNode(181 /* AwaitExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -10218,9 +10032,8 @@ var ts; var unaryOperator = token; var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token === 38 /* AsteriskAsteriskToken */) { - var diagnostic; var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 171 /* TypeAssertionExpression */) { + if (simpleUnaryExpression.kind === 174 /* 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 { @@ -10310,7 +10123,7 @@ var ts; */ function parseIncrementExpression() { if (token === 41 /* PlusPlusToken */ || token === 42 /* MinusMinusToken */) { - var node = createNode(179 /* PrefixUnaryExpression */); + var node = createNode(182 /* PrefixUnaryExpression */); node.operator = token; nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); @@ -10323,7 +10136,7 @@ var ts; 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); + var node = createNode(183 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token; nextToken(); @@ -10427,35 +10240,70 @@ var ts; } // 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); + var node = createNode(169 /* 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 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 parseJsxElementOrSelfClosingElement(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); - if (opening.kind === 235 /* JsxOpeningElement */) { - var node = createNode(233 /* JsxElement */, opening.pos); + var result; + if (opening.kind === 238 /* JsxOpeningElement */) { + var node = createNode(236 /* JsxElement */, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement.tagName); node.closingElement = parseJsxClosingElement(inExpressionContext); - return finishNode(node); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } + result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 234 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 237 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements - return opening; + result = opening; + } + // If the user writes the invalid code '
' in an expression context (i.e. not wrapped in + // an enclosing tag), we'll naively try to parse ^ this as a 'less than' operator and the remainder of the tag + // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX + // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter + // does less damage and we can report a better error. + // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios + // of one sort or another. + if (inExpressionContext && token === 25 /* LessThanToken */) { + var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); }); + if (invalidElement) { + parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); + var badNode = createNode(184 /* BinaryExpression */, result.pos); + badNode.end = invalidElement.end; + badNode.left = result; + badNode.right = invalidElement; + badNode.operatorToken = createMissingNode(24 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); + badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; + return badNode; + } } + return result; } function parseJsxText() { - var node = createNode(236 /* JsxText */, scanner.getStartPos()); + var node = createNode(239 /* JsxText */, scanner.getStartPos()); token = scanner.scanJsxToken(); return finishNode(node); } function parseJsxChild() { switch (token) { - case 236 /* JsxText */: + case 239 /* JsxText */: return parseJsxText(); case 15 /* OpenBraceToken */: return parseJsxExpression(/*inExpressionContext*/ false); @@ -10472,10 +10320,13 @@ var ts; while (true) { token = scanner.reScanJsxToken(); if (token === 26 /* LessThanSlashToken */) { + // Closing tag break; } else if (token === 1 /* EndOfFileToken */) { - parseErrorAtCurrentToken(ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + // If we hit EOF, issue the error at the tag that lacks the closing element + // rather than at the end of the file (which is useless) + parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); break; } result.push(parseJsxChild()); @@ -10494,7 +10345,7 @@ var ts; // 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); + node = createNode(238 /* JsxOpeningElement */, fullStart); scanJsxText(); } else { @@ -10503,10 +10354,10 @@ var ts; parseExpected(27 /* GreaterThanToken */); } else { - parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*advance*/ false); + parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } - node = createNode(234 /* JsxSelfClosingElement */, fullStart); + node = createNode(237 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; node.attributes = attributes; @@ -10517,7 +10368,7 @@ var ts; var elementName = parseIdentifierName(); while (parseOptional(21 /* DotToken */)) { scanJsxIdentifier(); - var node = createNode(135 /* QualifiedName */, elementName.pos); + var node = createNode(136 /* QualifiedName */, elementName.pos); node.left = elementName; node.right = parseIdentifierName(); elementName = finishNode(node); @@ -10525,16 +10376,16 @@ var ts; return elementName; } function parseJsxExpression(inExpressionContext) { - var node = createNode(240 /* JsxExpression */); + var node = createNode(243 /* JsxExpression */); parseExpected(15 /* OpenBraceToken */); if (token !== 16 /* CloseBraceToken */) { - node.expression = parseExpression(); + node.expression = parseAssignmentExpressionOrHigher(); } if (inExpressionContext) { parseExpected(16 /* CloseBraceToken */); } else { - parseExpected(16 /* CloseBraceToken */, /*message*/ undefined, /*advance*/ false); + parseExpected(16 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); @@ -10544,7 +10395,7 @@ var ts; return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(238 /* JsxAttribute */); + var node = createNode(241 /* JsxAttribute */); node.name = parseIdentifierName(); if (parseOptional(56 /* EqualsToken */)) { switch (token) { @@ -10559,7 +10410,7 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(239 /* JsxSpreadAttribute */); + var node = createNode(242 /* JsxSpreadAttribute */); parseExpected(15 /* OpenBraceToken */); parseExpected(22 /* DotDotDotToken */); node.expression = parseExpression(); @@ -10567,20 +10418,20 @@ var ts; return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(237 /* JsxClosingElement */); + var node = createNode(240 /* JsxClosingElement */); parseExpected(26 /* LessThanSlashToken */); node.tagName = parseJsxElementName(); if (inExpressionContext) { parseExpected(27 /* GreaterThanToken */); } else { - parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*advance*/ false); + parseExpected(27 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } return finishNode(node); } function parseTypeAssertion() { - var node = createNode(171 /* TypeAssertionExpression */); + var node = createNode(174 /* TypeAssertionExpression */); parseExpected(25 /* LessThanToken */); node.type = parseType(); parseExpected(27 /* GreaterThanToken */); @@ -10591,7 +10442,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(21 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(166 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(169 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); @@ -10600,7 +10451,7 @@ var ts; } // 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); + var indexedAccess = createNode(170 /* 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. @@ -10616,7 +10467,7 @@ var ts; continue; } if (token === 11 /* NoSubstitutionTemplateLiteral */ || token === 12 /* TemplateHead */) { - var tagExpression = createNode(170 /* TaggedTemplateExpression */, expression.pos); + var tagExpression = createNode(173 /* TaggedTemplateExpression */, expression.pos); tagExpression.tag = expression; tagExpression.template = token === 11 /* NoSubstitutionTemplateLiteral */ ? parseLiteralNode() @@ -10639,7 +10490,7 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(168 /* CallExpression */, expression.pos); + var callExpr = createNode(171 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -10647,7 +10498,7 @@ var ts; continue; } else if (token === 17 /* OpenParenToken */) { - var callExpr = createNode(168 /* CallExpression */, expression.pos); + var callExpr = createNode(171 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -10757,41 +10608,41 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNode(172 /* ParenthesizedExpression */); + var node = createNode(175 /* ParenthesizedExpression */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(18 /* CloseParenToken */); return finishNode(node); } function parseSpreadElement() { - var node = createNode(185 /* SpreadElementExpression */); + var node = createNode(188 /* SpreadElementExpression */); parseExpected(22 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token === 22 /* DotDotDotToken */ ? parseSpreadElement() : - token === 24 /* CommaToken */ ? createNode(187 /* OmittedExpression */) : + token === 24 /* CommaToken */ ? createNode(190 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(164 /* ArrayLiteralExpression */); + var node = createNode(167 /* ArrayLiteralExpression */); parseExpected(19 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) - node.flags |= 2048 /* MultiLine */; + node.flags |= 1024 /* 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); + return parseAccessorDeclaration(146 /* GetAccessor */, fullStart, decorators, modifiers); } else if (parseContextualModifier(129 /* SetKeyword */)) { - return parseAccessorDeclaration(146 /* SetAccessor */, fullStart, decorators, modifiers); + return parseAccessorDeclaration(147 /* SetAccessor */, fullStart, decorators, modifiers); } return undefined; } @@ -10805,7 +10656,6 @@ var ts; } 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 */); @@ -10819,7 +10669,7 @@ var ts; // 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); + var shorthandDeclaration = createNode(249 /* ShorthandPropertyAssignment */, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; var equalsToken = parseOptionalToken(56 /* EqualsToken */); @@ -10827,22 +10677,23 @@ var ts; shorthandDeclaration.equalsToken = equalsToken; shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); } - return finishNode(shorthandDeclaration); + return addJSDocComment(finishNode(shorthandDeclaration)); } else { - var propertyAssignment = createNode(245 /* PropertyAssignment */, fullStart); + var propertyAssignment = createNode(248 /* PropertyAssignment */, fullStart); + propertyAssignment.modifiers = modifiers; propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; parseExpected(54 /* ColonToken */); propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); - return finishNode(propertyAssignment); + return addJSDocComment(finishNode(propertyAssignment)); } } function parseObjectLiteralExpression() { - var node = createNode(165 /* ObjectLiteralExpression */); + var node = createNode(168 /* ObjectLiteralExpression */); parseExpected(15 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { - node.flags |= 2048 /* MultiLine */; + node.flags |= 1024 /* MultiLine */; } node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimeter*/ true); parseExpected(16 /* CloseBraceToken */); @@ -10856,14 +10707,14 @@ var ts; // function BindingIdentifier[opt](FormalParameters){ FunctionBody } var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext(false); + setDecoratorContext(/*val*/ false); } - var node = createNode(173 /* FunctionExpression */); + var node = createNode(176 /* FunctionExpression */); setModifiers(node, parseModifiers()); parseExpected(87 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 512 /* Async */); + var isAsync = !!(node.flags & 256 /* Async */); node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : isGenerator ? doInYieldContext(parseOptionalIdentifier) : @@ -10872,15 +10723,15 @@ var ts; fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlock(/*allowYield*/ isGenerator, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); if (saveDecoratorContext) { - setDecoratorContext(true); + setDecoratorContext(/*val*/ true); } - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseOptionalIdentifier() { return isIdentifier() ? parseIdentifier() : undefined; } function parseNewExpression() { - var node = createNode(169 /* NewExpression */); + var node = createNode(172 /* NewExpression */); parseExpected(92 /* NewKeyword */); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); @@ -10891,7 +10742,7 @@ var ts; } // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(192 /* Block */); + var node = createNode(195 /* Block */); if (parseExpected(15 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(16 /* CloseBraceToken */); @@ -10910,23 +10761,23 @@ var ts; // arrow function. The body of the function is not in [Decorator] context. var saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { - setDecoratorContext(false); + setDecoratorContext(/*val*/ false); } var block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); if (saveDecoratorContext) { - setDecoratorContext(true); + setDecoratorContext(/*val*/ true); } setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); return block; } function parseEmptyStatement() { - var node = createNode(194 /* EmptyStatement */); + var node = createNode(197 /* EmptyStatement */); parseExpected(23 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(196 /* IfStatement */); + var node = createNode(199 /* IfStatement */); parseExpected(88 /* IfKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -10936,7 +10787,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(197 /* DoStatement */); + var node = createNode(200 /* DoStatement */); parseExpected(79 /* DoKeyword */); node.statement = parseStatement(); parseExpected(104 /* WhileKeyword */); @@ -10951,7 +10802,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(198 /* WhileStatement */); + var node = createNode(201 /* WhileStatement */); parseExpected(104 /* WhileKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -10974,21 +10825,21 @@ var ts; } var forOrForInOrForOfStatement; if (parseOptional(90 /* InKeyword */)) { - var forInStatement = createNode(200 /* ForInStatement */, pos); + var forInStatement = createNode(203 /* 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); + else if (parseOptional(135 /* OfKeyword */)) { + var forOfStatement = createNode(204 /* ForOfStatement */, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(18 /* CloseParenToken */); forOrForInOrForOfStatement = forOfStatement; } else { - var forStatement = createNode(199 /* ForStatement */, pos); + var forStatement = createNode(202 /* ForStatement */, pos); forStatement.initializer = initializer; parseExpected(23 /* SemicolonToken */); if (token !== 23 /* SemicolonToken */ && token !== 18 /* CloseParenToken */) { @@ -11006,7 +10857,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 203 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */); + parseExpected(kind === 206 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -11014,7 +10865,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(204 /* ReturnStatement */); + var node = createNode(207 /* ReturnStatement */); parseExpected(94 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -11023,7 +10874,7 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(205 /* WithStatement */); + var node = createNode(208 /* WithStatement */); parseExpected(105 /* WithKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -11032,7 +10883,7 @@ var ts; return finishNode(node); } function parseCaseClause() { - var node = createNode(241 /* CaseClause */); + var node = createNode(244 /* CaseClause */); parseExpected(71 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); parseExpected(54 /* ColonToken */); @@ -11040,7 +10891,7 @@ var ts; return finishNode(node); } function parseDefaultClause() { - var node = createNode(242 /* DefaultClause */); + var node = createNode(245 /* DefaultClause */); parseExpected(77 /* DefaultKeyword */); parseExpected(54 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); @@ -11050,12 +10901,12 @@ var ts; return token === 71 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(206 /* SwitchStatement */); + var node = createNode(209 /* SwitchStatement */); parseExpected(96 /* SwitchKeyword */); parseExpected(17 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(18 /* CloseParenToken */); - var caseBlock = createNode(220 /* CaseBlock */, scanner.getStartPos()); + var caseBlock = createNode(223 /* CaseBlock */, scanner.getStartPos()); parseExpected(15 /* OpenBraceToken */); caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); parseExpected(16 /* CloseBraceToken */); @@ -11070,7 +10921,7 @@ var ts; // 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 */); + var node = createNode(211 /* ThrowStatement */); parseExpected(98 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); @@ -11078,7 +10929,7 @@ var ts; } // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(209 /* TryStatement */); + var node = createNode(212 /* TryStatement */); parseExpected(100 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); node.catchClause = token === 72 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -11091,7 +10942,7 @@ var ts; return finishNode(node); } function parseCatchClause() { - var result = createNode(244 /* CatchClause */); + var result = createNode(247 /* CatchClause */); parseExpected(72 /* CatchKeyword */); if (parseExpected(17 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); @@ -11101,7 +10952,7 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(210 /* DebuggerStatement */); + var node = createNode(213 /* DebuggerStatement */); parseExpected(76 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); @@ -11113,16 +10964,16 @@ var ts; var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); if (expression.kind === 69 /* Identifier */ && parseOptional(54 /* ColonToken */)) { - var labeledStatement = createNode(207 /* LabeledStatement */, fullStart); + var labeledStatement = createNode(210 /* LabeledStatement */, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); - return finishNode(labeledStatement); + return addJSDocComment(finishNode(labeledStatement)); } else { - var expressionStatement = createNode(195 /* ExpressionStatement */, fullStart); + var expressionStatement = createNode(198 /* ExpressionStatement */, fullStart); expressionStatement.expression = expression; parseSemicolon(); - return finishNode(expressionStatement); + return addJSDocComment(finishNode(expressionStatement)); } } function nextTokenIsIdentifierOrKeywordOnSameLine() { @@ -11186,6 +11037,8 @@ var ts; return false; } continue; + case 134 /* GlobalKeyword */: + return nextToken() === 15 /* OpenBraceToken */; case 89 /* ImportKeyword */: nextToken(); return token === 9 /* StringLiteral */ || token === 37 /* AsteriskToken */ || @@ -11245,6 +11098,7 @@ var ts; case 125 /* ModuleKeyword */: case 126 /* NamespaceKeyword */: case 132 /* TypeKeyword */: + case 134 /* GlobalKeyword */: // When these don't start a declaration, they're an identifier in an expression statement return true; case 112 /* PublicKeyword */: @@ -11293,9 +11147,9 @@ var ts; case 86 /* ForKeyword */: return parseForOrForInOrForOfStatement(); case 75 /* ContinueKeyword */: - return parseBreakOrContinueStatement(202 /* ContinueStatement */); + return parseBreakOrContinueStatement(205 /* ContinueStatement */); case 70 /* BreakKeyword */: - return parseBreakOrContinueStatement(203 /* BreakStatement */); + return parseBreakOrContinueStatement(206 /* BreakStatement */); case 94 /* ReturnKeyword */: return parseReturnStatement(); case 105 /* WithKeyword */: @@ -11328,6 +11182,7 @@ var ts; case 112 /* PublicKeyword */: case 115 /* AbstractKeyword */: case 113 /* StaticKeyword */: + case 134 /* GlobalKeyword */: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -11354,6 +11209,7 @@ var ts; return parseTypeAliasDeclaration(fullStart, decorators, modifiers); case 81 /* EnumKeyword */: return parseEnumDeclaration(fullStart, decorators, modifiers); + case 134 /* GlobalKeyword */: case 125 /* ModuleKeyword */: case 126 /* NamespaceKeyword */: return parseModuleDeclaration(fullStart, decorators, modifiers); @@ -11368,7 +11224,7 @@ var ts; 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); + var node = createMissingNode(234 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; setModifiers(node, modifiers); @@ -11390,17 +11246,16 @@ var ts; // DECLARATIONS function parseArrayBindingElement() { if (token === 24 /* CommaToken */) { - return createNode(187 /* OmittedExpression */); + return createNode(190 /* OmittedExpression */); } - var node = createNode(163 /* BindingElement */); + var node = createNode(166 /* 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 node = createNode(166 /* BindingElement */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); if (tokenIsIdentifier && token !== 54 /* ColonToken */) { @@ -11415,14 +11270,14 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(161 /* ObjectBindingPattern */); + var node = createNode(164 /* ObjectBindingPattern */); parseExpected(15 /* OpenBraceToken */); node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); parseExpected(16 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(162 /* ArrayBindingPattern */); + var node = createNode(165 /* ArrayBindingPattern */); parseExpected(19 /* OpenBracketToken */); node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); parseExpected(20 /* CloseBracketToken */); @@ -11441,7 +11296,7 @@ var ts; return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(211 /* VariableDeclaration */); + var node = createNode(214 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token)) { @@ -11450,15 +11305,15 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(212 /* VariableDeclarationList */); + var node = createNode(215 /* VariableDeclarationList */); switch (token) { case 102 /* VarKeyword */: break; case 108 /* LetKeyword */: - node.flags |= 16384 /* Let */; + node.flags |= 8192 /* Let */; break; case 74 /* ConstKeyword */: - node.flags |= 32768 /* Const */; + node.flags |= 16384 /* Const */; break; default: ts.Debug.fail(); @@ -11473,7 +11328,7 @@ var ts; // 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)) { + if (token === 135 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -11488,50 +11343,50 @@ var ts; return nextTokenIsIdentifier() && nextToken() === 18 /* CloseParenToken */; } function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(193 /* VariableStatement */, fullStart); + var node = createNode(196 /* VariableStatement */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(213 /* FunctionDeclaration */, fullStart); + var node = createNode(216 /* FunctionDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(87 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); - node.name = node.flags & 1024 /* Default */ ? parseOptionalIdentifier() : parseIdentifier(); + node.name = node.flags & 512 /* Default */ ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 512 /* Async */); + var isAsync = !!(node.flags & 256 /* Async */); fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(144 /* Constructor */, pos); + var node = createNode(145 /* 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); + return addJSDocComment(finishNode(node)); } function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(143 /* MethodDeclaration */, fullStart); + var method = createNode(144 /* 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 */); + var isAsync = !!(method.flags & 256 /* Async */); fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); - return finishNode(method); + return addJSDocComment(finishNode(method)); } function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(141 /* PropertyDeclaration */, fullStart); + var property = createNode(142 /* PropertyDeclaration */, fullStart); property.decorators = decorators; setModifiers(property, modifiers); property.name = name; @@ -11546,7 +11401,7 @@ var ts; // 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 */ + property.initializer = modifiers && modifiers.flags & 64 /* Static */ ? allowInAnd(parseNonParameterInitializer) : doOutsideOfContext(2 /* Yield */ | 1 /* DisallowIn */, parseNonParameterInitializer); parseSemicolon(); @@ -11594,7 +11449,7 @@ var ts; return true; } // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. - while (ts.isModifier(token)) { + while (ts.isModifierKind(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 @@ -11655,9 +11510,9 @@ var ts; } if (!decorators) { decorators = []; - decorators.pos = scanner.getStartPos(); + decorators.pos = decoratorStart; } - var decorator = createNode(139 /* Decorator */, decoratorStart); + var decorator = createNode(140 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); decorators.push(finishNode(decorator)); } @@ -11666,14 +11521,30 @@ var ts; } return decorators; } - function parseModifiers() { + /* + * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. + * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect + * and turns it into a standalone declaration), then it is better to parse it and report an error later. + * + * In such situations, 'permitInvalidConstAsModifier' should be set to true. + */ + function parseModifiers(permitInvalidConstAsModifier) { var flags = 0; var modifiers; while (true) { var modifierStart = scanner.getStartPos(); var modifierKind = token; - if (!parseAnyContextualModifier()) { - break; + if (token === 74 /* ConstKeyword */ && permitInvalidConstAsModifier) { + // We need to ensure that any subsequent modifiers appear on the same line + // so that when 'const' is a standalone declaration, we don't issue an error. + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } } if (!modifiers) { modifiers = []; @@ -11706,13 +11577,13 @@ var ts; } function parseClassElement() { if (token === 23 /* SemicolonToken */) { - var result = createNode(191 /* SemicolonClassElement */); + var result = createNode(194 /* SemicolonClassElement */); nextToken(); return finishNode(result); } var fullStart = getNodePos(); var decorators = parseDecorators(); - var modifiers = parseModifiers(); + var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); if (accessor) { return accessor; @@ -11744,10 +11615,10 @@ var ts; return parseClassDeclarationOrExpression( /*fullStart*/ scanner.getStartPos(), /*decorators*/ undefined, - /*modifiers*/ undefined, 186 /* ClassExpression */); + /*modifiers*/ undefined, 189 /* ClassExpression */); } function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 214 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 217 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { var node = createNode(kind, fullStart); @@ -11772,8 +11643,8 @@ var ts; // 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 + // - class with name 'implements' + // 'isImplementsClause' helps to disambiguate between these two cases return isIdentifier() && !isImplementsClause() ? parseIdentifier() : undefined; @@ -11789,12 +11660,9 @@ var ts; } return undefined; } - function parseHeritageClausesWorker() { - return parseList(20 /* HeritageClauses */, parseHeritageClause); - } function parseHeritageClause() { if (token === 83 /* ExtendsKeyword */ || token === 106 /* ImplementsKeyword */) { - var node = createNode(243 /* HeritageClause */); + var node = createNode(246 /* HeritageClause */); node.token = token; nextToken(); node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); @@ -11803,7 +11671,7 @@ var ts; return undefined; } function parseExpressionWithTypeArguments() { - var node = createNode(188 /* ExpressionWithTypeArguments */); + var node = createNode(191 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); if (token === 25 /* LessThanToken */) { node.typeArguments = parseBracketedList(18 /* TypeArguments */, parseType, 25 /* LessThanToken */, 27 /* GreaterThanToken */); @@ -11817,7 +11685,7 @@ var ts; return parseList(5 /* ClassMembers */, parseClassElement); } function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(215 /* InterfaceDeclaration */, fullStart); + var node = createNode(218 /* InterfaceDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(107 /* InterfaceKeyword */); @@ -11828,7 +11696,7 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(216 /* TypeAliasDeclaration */, fullStart); + var node = createNode(219 /* TypeAliasDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(132 /* TypeKeyword */); @@ -11844,13 +11712,13 @@ var ts; // 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()); + var node = createNode(250 /* EnumMember */, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return finishNode(node); } function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(217 /* EnumDeclaration */, fullStart); + var node = createNode(220 /* EnumDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(81 /* EnumKeyword */); @@ -11865,7 +11733,7 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(219 /* ModuleBlock */, scanner.getStartPos()); + var node = createNode(222 /* ModuleBlock */, scanner.getStartPos()); if (parseExpected(15 /* OpenBraceToken */)) { node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(16 /* CloseBraceToken */); @@ -11876,31 +11744,42 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(218 /* ModuleDeclaration */, fullStart); + var node = createNode(221 /* 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 */; + var namespaceFlag = flags & 65536 /* 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) + ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 2 /* Export */ | namespaceFlag) : parseModuleBlock(); return finishNode(node); } function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(218 /* ModuleDeclaration */, fullStart); + var node = createNode(221 /* ModuleDeclaration */, fullStart); node.decorators = decorators; setModifiers(node, modifiers); - node.name = parseLiteralNode(/*internName*/ true); + if (token === 134 /* GlobalKeyword */) { + // parse 'global' as name of global scope augmentation + node.name = parseIdentifier(); + node.flags |= 2097152 /* GlobalAugmentation */; + } + else { + 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 */; + if (token === 134 /* GlobalKeyword */) { + // global augmentation + return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + } + else if (parseOptional(126 /* NamespaceKeyword */)) { + flags |= 65536 /* Namespace */; } else { parseExpected(125 /* ModuleKeyword */); @@ -11920,11 +11799,6 @@ var ts; 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(); @@ -11935,7 +11809,7 @@ var ts; // ImportEquals declaration of type: // import x = require("mod"); or // import x = M.x; - var importEqualsDeclaration = createNode(221 /* ImportEqualsDeclaration */, fullStart); + var importEqualsDeclaration = createNode(224 /* ImportEqualsDeclaration */, fullStart); importEqualsDeclaration.decorators = decorators; setModifiers(importEqualsDeclaration, modifiers); importEqualsDeclaration.name = identifier; @@ -11945,1274 +11819,2810 @@ var ts; 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); + // Import statement + var importDeclaration = createNode(225 /* 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(226 /* 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(228 /* NamedImports */); + } + return finishNode(importClause); + } + function parseModuleReference() { + return isExternalModuleReference() + ? parseExternalModuleReference() + : parseEntityName(/*allowReservedWords*/ false); + } + function parseExternalModuleReference() { + var node = createNode(235 /* ExternalModuleReference */); + parseExpected(127 /* RequireKeyword */); + parseExpected(17 /* OpenParenToken */); + node.expression = parseModuleSpecifier(); + parseExpected(18 /* CloseParenToken */); + return finishNode(node); + } + function parseModuleSpecifier() { + if (token === 9 /* StringLiteral */) { + var result = parseLiteralNode(); + internIdentifier(result.text); + return result; + } + else { + // 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 + // check pass. + return parseExpression(); + } + } + function parseNamespaceImport() { + // NameSpaceImport: + // * as ImportedBinding + var namespaceImport = createNode(227 /* 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 === 228 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 15 /* OpenBraceToken */, 16 /* CloseBraceToken */); + return finishNode(node); + } + function parseExportSpecifier() { + return parseImportOrExportSpecifier(233 /* ExportSpecifier */); + } + function parseImportSpecifier() { + return parseImportOrExportSpecifier(229 /* 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 === 229 /* 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(231 /* ExportDeclaration */, fullStart); + node.decorators = decorators; + setModifiers(node, modifiers); + if (parseOptional(37 /* AsteriskToken */)) { + parseExpected(133 /* FromKeyword */); + node.moduleSpecifier = parseModuleSpecifier(); + } + else { + node.exportClause = parseNamedImportsOrExports(232 /* 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(230 /* 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 !== 2 /* SingleLineCommentTrivia */) { + if (ts.isTrivia(kind)) { + continue; + } + else { + 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(136 /* QualifiedName */, left.pos); + result.left = left; + result.right = parseIdentifierName(); + return finishNode(result); + } + function parseJSDocRecordType() { + var result = createNode(260 /* JSDocRecordType */); + nextToken(); + result.members = parseDelimitedList(24 /* JSDocRecordMembers */, parseJSDocRecordMember); + checkForTrailingComma(result.members); + parseExpected(16 /* CloseBraceToken */); + return finishNode(result); + } + function parseJSDocRecordMember() { + var result = createNode(261 /* JSDocRecordMember */); + result.name = parseSimplePropertyName(); + if (token === 54 /* ColonToken */) { + nextToken(); + result.type = parseJSDocType(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(259 /* JSDocNonNullableType */); + nextToken(); + result.type = parseJSDocType(); + return finishNode(result); + } + function parseJSDocTupleType() { + var result = createNode(257 /* 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(256 /* 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(253 /* 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(254 /* JSDocUnknownType */, pos); + return finishNode(result); + } + else { + var result = createNode(258 /* JSDocNullableType */, pos); + result.type = parseJSDocType(); + return finishNode(result); + } + } + function parseIsolatedJSDocComment(content, start, length) { + initializeState("file.js", content, 2 /* Latest */, /*isJavaScriptFile*/ true, /*_syntaxCursor:*/ undefined); + sourceFile = { languageVariant: 0 /* Standard */, text: content }; + var jsDocComment = parseJSDocCommentWorker(start, length); + var diagnostics = parseDiagnostics; + clearState(); + return jsDocComment ? { jsDocComment: jsDocComment, diagnostics: diagnostics } : undefined; + } + JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + function parseJSDocComment(parent, start, length) { + var saveToken = token; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + var comment = parseJSDocCommentWorker(start, length); + if (comment) { + comment.parent = parent; + } + token = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + 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 result; + // Check for /** (JSDoc opening part) + if (content.charCodeAt(start) === 47 /* slash */ && + content.charCodeAt(start + 1) === 42 /* asterisk */ && + content.charCodeAt(start + 2) === 42 /* asterisk */ && + content.charCodeAt(start + 3) !== 42 /* asterisk */) { + // + 3 for leading /**, - 5 in total for /** */ + scanner.scanRange(start + 3, length - 5, function () { + // 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; + nextJSDocToken(); + while (token !== 1 /* EndOfFileToken */) { + switch (token) { + case 55 /* AtToken */: + if (canParseTag) { + parseTag(); + } + // This will take us to the end of the line, so it's OK to parse a tag on the next pass through the loop + seenAsterisk = false; + break; + case 4 /* NewLineTrivia */: + // After a line break, we can parse a tag, and we haven't seen an asterisk on the next line yet + canParseTag = true; + seenAsterisk = false; + break; + case 37 /* AsteriskToken */: + if (seenAsterisk) { + // If we've already seen an asterisk, then we can no longer parse a tag on this line + canParseTag = false; + } + // Ignore the first asterisk on a line + seenAsterisk = true; + break; + case 69 /* Identifier */: + // 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; + break; + case 1 /* EndOfFileToken */: + break; + } + nextJSDocToken(); + } + result = createJSDocComment(); + }); + } + return result; + function createJSDocComment() { + if (!tags) { + return undefined; + } + var result = createNode(268 /* JSDocComment */, start); + result.tags = tags; + return finishNode(result, end); + } + function skipWhitespace() { + while (token === 5 /* WhitespaceTrivia */ || token === 4 /* NewLineTrivia */) { + nextJSDocToken(); + } + } + function parseTag() { + ts.Debug.assert(token === 55 /* AtToken */); + var atToken = createNode(55 /* AtToken */, scanner.getTokenPos()); + atToken.end = scanner.getTextPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifier(); + 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(269 /* JSDocTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + return finishNode(result); + } + function addTag(tag) { + if (tag) { + if (!tags) { + tags = []; + tags.pos = tag.pos; + } + tags.push(tag); + tags.end = tag.end; + } + } + function tryParseTypeExpression() { + if (token !== 15 /* OpenBraceToken */) { + return undefined; + } + var typeExpression = parseJSDocTypeExpression(); + return typeExpression; + } + function handleParamTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + skipWhitespace(); + var name; + var isBracketed; + // Looking for something like '[foo]' or 'foo' + if (parseOptionalToken(19 /* OpenBracketToken */)) { + name = parseJSDocIdentifier(); + isBracketed = true; + // May have an optional default, e.g. '[foo = 42]' + if (parseOptionalToken(56 /* EqualsToken */)) { + parseExpression(); + } + parseExpected(20 /* CloseBracketToken */); + } + else if (token === 69 /* Identifier */) { + name = parseJSDocIdentifier(); + } + if (!name) { + parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); + return undefined; + } + var preName, postName; + if (typeExpression) { + postName = name; + } + else { + preName = name; + } + if (!typeExpression) { + typeExpression = tryParseTypeExpression(); + } + var result = createNode(270 /* JSDocParameterTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.preParameterName = preName; + result.typeExpression = typeExpression; + result.postParameterName = postName; + result.isBracketed = isBracketed; + return finishNode(result); + } + function handleReturnTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 271 /* JSDocReturnTag */; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + } + var result = createNode(271 /* JSDocReturnTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function handleTypeTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 272 /* JSDocTypeTag */; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + } + var result = createNode(272 /* JSDocTypeTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function handleTemplateTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 273 /* JSDocTemplateTag */; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); + } + // Type parameter list looks like '@template T,U,V' + var typeParameters = []; + typeParameters.pos = scanner.getStartPos(); + while (true) { + var name_8 = parseJSDocIdentifier(); + if (!name_8) { + parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); + return undefined; + } + var typeParameter = createNode(138 /* TypeParameter */, name_8.pos); + typeParameter.name = name_8; + finishNode(typeParameter); + typeParameters.push(typeParameter); + if (token === 24 /* CommaToken */) { + nextJSDocToken(); + } + else { + break; + } + } + var result = createNode(273 /* JSDocTemplateTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeParameters = typeParameters; + finishNode(result); + typeParameters.end = result.end; + return result; + } + function nextJSDocToken() { + return token = scanner.scanJSDocToken(); + } + function parseJSDocIdentifier() { + if (token !== 69 /* Identifier */) { + parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); + return undefined; + } + var pos = scanner.getTokenPos(); + var end = scanner.getTextPos(); + var result = createNode(69 /* Identifier */, pos); + result.text = content.substring(pos, end); + finishNode(result, end); + nextJSDocToken(); + return result; + } + } + 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, /*setParentNodes*/ 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, /*setParentNodes*/ 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, array_7 = array; _i < array_7.length; _i++) { + var node = array_7[_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_2 = node.pos; + forEachChild(node, function (child) { + ts.Debug.assert(child.pos >= pos_2); + pos_2 = child.end; + }); + ts.Debug.assert(pos_2 <= 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, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_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; + } + } } - function parseModuleReference() { - return isExternalModuleReference() - ? parseExternalModuleReference() - : parseEntityName(/*allowReservedWords*/ false); + var InvalidPosition; + (function (InvalidPosition) { + InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; + })(InvalidPosition || (InvalidPosition = {})); + })(IncrementalParser || (IncrementalParser = {})); +})(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; + var Reachability; + (function (Reachability) { + Reachability[Reachability["Unintialized"] = 1] = "Unintialized"; + Reachability[Reachability["Reachable"] = 2] = "Reachable"; + Reachability[Reachability["Unreachable"] = 4] = "Unreachable"; + Reachability[Reachability["ReportedUnreachable"] = 8] = "ReportedUnreachable"; + })(Reachability || (Reachability = {})); + function or(state1, state2) { + return (state1 | state2) & 2 /* Reachable */ + ? 2 /* Reachable */ + : (state1 & state2) & 8 /* ReportedUnreachable */ + ? 8 /* ReportedUnreachable */ + : 4 /* Unreachable */; + } + function getModuleInstanceState(node) { + // A module is uninstantiated if it contains only + // 1. interface declarations, type alias declarations + if (node.kind === 218 /* InterfaceDeclaration */ || node.kind === 219 /* TypeAliasDeclaration */) { + return 0 /* NonInstantiated */; } - function parseExternalModuleReference() { - var node = createNode(232 /* ExternalModuleReference */); - parseExpected(127 /* RequireKeyword */); - parseExpected(17 /* OpenParenToken */); - node.expression = parseModuleSpecifier(); - parseExpected(18 /* CloseParenToken */); - return finishNode(node); + else if (ts.isConstEnumDeclaration(node)) { + return 2 /* ConstEnumOnly */; } - 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; + else if ((node.kind === 225 /* ImportDeclaration */ || node.kind === 224 /* ImportEqualsDeclaration */) && !(node.flags & 2 /* Export */)) { + return 0 /* NonInstantiated */; } - function parseNamespaceImport() { - // NameSpaceImport: - // * as ImportedBinding - var namespaceImport = createNode(224 /* NamespaceImport */); - parseExpected(37 /* AsteriskToken */); - parseExpected(116 /* AsKeyword */); - namespaceImport.name = parseIdentifier(); - return finishNode(namespaceImport); + else if (node.kind === 222 /* ModuleBlock */) { + var state_1 = 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_1 = 2 /* ConstEnumOnly */; + return false; + case 1 /* Instantiated */: + // child is instantiated - record state and stop + state_1 = 1 /* Instantiated */; + return true; + } + }); + return state_1; } - 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); + else if (node.kind === 221 /* ModuleDeclaration */) { + return getModuleInstanceState(node.body); } - function parseExportSpecifier() { - return parseImportOrExportSpecifier(230 /* ExportSpecifier */); + else { + return 1 /* Instantiated */; } - function parseImportSpecifier() { - return parseImportOrExportSpecifier(226 /* ImportSpecifier */); + } + 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 = {})); + var binder = createBinder(); + function bindSourceFile(file, options) { + var start = new Date().getTime(); + binder(file, options); + ts.bindTime += new Date().getTime() - start; + } + ts.bindSourceFile = bindSourceFile; + function createBinder() { + var file; + var options; + var parent; + var container; + var blockScopeContainer; + var lastContainer; + var seenThisKeyword; + // state used by reachability checks + var hasExplicitReturn; + var currentReachabilityState; + var labelStack; + var labelIndexMap; + var implicitLabels; + // state used for emit helpers + var hasClassExtends; + var hasAsyncFunctions; + var hasDecorators; + var hasParameterDecorators; + // 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; + var symbolCount = 0; + var Symbol; + var classifiableNames; + function bindSourceFile(f, opts) { + file = f; + options = opts; + inStrictMode = !!file.externalModuleIndicator; + classifiableNames = {}; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + } + file = undefined; + options = undefined; + parent = undefined; + container = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + seenThisKeyword = false; + hasExplicitReturn = false; + labelStack = undefined; + labelIndexMap = undefined; + implicitLabels = undefined; + hasClassExtends = false; + hasAsyncFunctions = false; + hasDecorators = false; + hasParameterDecorators = false; + } + return bindSourceFile; + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); } - 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; + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; + node.symbol = symbol; + if (!symbol.declarations) { + symbol.declarations = []; } - if (kind === 226 /* ImportSpecifier */ && checkIdentifierIsKeyword) { - // Report error identifier expected - parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); + symbol.declarations.push(node); + if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { + symbol.exports = {}; } - 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(); + if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { + symbol.members = {}; } - 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(); + if (symbolFlags & 107455 /* Value */) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 221 /* ModuleDeclaration */)) { + // other kinds of value declarations take precedence over modules + symbol.valueDeclaration = node; } } - 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)); - } + // 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 (ts.isAmbientModule(node)) { + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; } - else { - var amdModuleNameRegEx = /^\/\/\/\s*".length; - return parseErrorAtPosition(start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); + if (kind === 251 /* SourceFile */) { + if (hasClassExtends) { + flags |= 4194304 /* HasClassExtends */; + } + if (hasDecorators) { + flags |= 8388608 /* HasDecorators */; + } + if (hasParameterDecorators) { + flags |= 16777216 /* HasParamDecorators */; + } + if (hasAsyncFunctions) { + flags |= 33554432 /* HasAsyncFunctions */; } } - 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); + node.flags = flags; + if (saveState) { + hasExplicitReturn = savedHasExplicitReturn; + currentReachabilityState = savedReachabilityState; + labelStack = savedLabelStack; + labelIndexMap = savedLabels; + implicitLabels = savedImplicitLabels; } - function parseJSDocRecordMember() { - var result = createNode(258 /* JSDocRecordMember */); - result.name = parseSimplePropertyName(); - if (token === 54 /* ColonToken */) { - nextToken(); - result.type = parseJSDocType(); - } - return finishNode(result); + container = saveContainer; + parent = saveParent; + blockScopeContainer = savedBlockScopeContainer; + } + /** + * Returns true if node and its subnodes were successfully traversed. + * Returning false means that node was not examined and caller needs to dive into the node himself. + */ + function bindReachableStatement(node) { + if (checkUnreachable(node)) { + ts.forEachChild(node, bind); + return; } - function parseJSDocNonNullableType() { - var result = createNode(256 /* JSDocNonNullableType */); - nextToken(); - result.type = parseJSDocType(); - return finishNode(result); + switch (node.kind) { + case 201 /* WhileStatement */: + bindWhileStatement(node); + break; + case 200 /* DoStatement */: + bindDoStatement(node); + break; + case 202 /* ForStatement */: + bindForStatement(node); + break; + case 203 /* ForInStatement */: + case 204 /* ForOfStatement */: + bindForInOrForOfStatement(node); + break; + case 199 /* IfStatement */: + bindIfStatement(node); + break; + case 207 /* ReturnStatement */: + case 211 /* ThrowStatement */: + bindReturnOrThrow(node); + break; + case 206 /* BreakStatement */: + case 205 /* ContinueStatement */: + bindBreakOrContinueStatement(node); + break; + case 212 /* TryStatement */: + bindTryStatement(node); + break; + case 209 /* SwitchStatement */: + bindSwitchStatement(node); + break; + case 223 /* CaseBlock */: + bindCaseBlock(node); + break; + case 210 /* LabeledStatement */: + bindLabeledStatement(node); + break; + default: + ts.forEachChild(node, bind); + break; } - function parseJSDocTupleType() { - var result = createNode(254 /* JSDocTupleType */); - nextToken(); - result.types = parseDelimitedList(25 /* JSDocTupleTypes */, parseJSDocType); - checkForTrailingComma(result.types); - parseExpected(20 /* CloseBracketToken */); - return finishNode(result); + } + function bindWhileStatement(n) { + var preWhileState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + var postWhileState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + // bind expressions (don't affect reachability) + bind(n.expression); + currentReachabilityState = preWhileState; + var postWhileLabel = pushImplicitLabel(); + bind(n.statement); + popImplicitLabel(postWhileLabel, postWhileState); + } + function bindDoStatement(n) { + var preDoState = currentReachabilityState; + var postDoLabel = pushImplicitLabel(); + bind(n.statement); + var postDoState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : preDoState; + popImplicitLabel(postDoLabel, postDoState); + // bind expressions (don't affect reachability) + bind(n.expression); + } + function bindForStatement(n) { + var preForState = currentReachabilityState; + var postForLabel = pushImplicitLabel(); + // bind expressions (don't affect reachability) + bind(n.initializer); + bind(n.condition); + bind(n.incrementor); + bind(n.statement); + // for statement is considered infinite when it condition is either omitted or is true keyword + // - for(..;;..) + // - for(..;true;..) + var isInfiniteLoop = (!n.condition || n.condition.kind === 99 /* TrueKeyword */); + var postForState = isInfiniteLoop ? 4 /* Unreachable */ : preForState; + popImplicitLabel(postForLabel, postForState); + } + function bindForInOrForOfStatement(n) { + var preStatementState = currentReachabilityState; + var postStatementLabel = pushImplicitLabel(); + // bind expressions (don't affect reachability) + bind(n.initializer); + bind(n.expression); + bind(n.statement); + popImplicitLabel(postStatementLabel, preStatementState); + } + function bindIfStatement(n) { + // denotes reachability state when entering 'thenStatement' part of the if statement: + // i.e. if condition is false then thenStatement is unreachable + var ifTrueState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + // denotes reachability state when entering 'elseStatement': + // i.e. if condition is true then elseStatement is unreachable + var ifFalseState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + currentReachabilityState = ifTrueState; + // bind expression (don't affect reachability) + bind(n.expression); + bind(n.thenStatement); + if (n.elseStatement) { + var preElseState = currentReachabilityState; + currentReachabilityState = ifFalseState; + bind(n.elseStatement); + currentReachabilityState = or(currentReachabilityState, preElseState); } - function checkForTrailingComma(list) { - if (parseDiagnostics.length === 0 && list.hasTrailingComma) { - var start = list.end - ",".length; - parseErrorAtPosition(start, ",".length, ts.Diagnostics.Trailing_comma_not_allowed); - } + else { + currentReachabilityState = or(currentReachabilityState, ifFalseState); + } + } + function bindReturnOrThrow(n) { + // bind expression (don't affect reachability) + bind(n.expression); + if (n.kind === 207 /* ReturnStatement */) { + hasExplicitReturn = true; + } + currentReachabilityState = 4 /* Unreachable */; + } + function bindBreakOrContinueStatement(n) { + // call bind on label (don't affect reachability) + bind(n.label); + // for continue case touch label so it will be marked a used + var isValidJump = jumpToLabel(n.label, n.kind === 206 /* BreakStatement */ ? currentReachabilityState : 4 /* Unreachable */); + if (isValidJump) { + currentReachabilityState = 4 /* Unreachable */; + } + } + function bindTryStatement(n) { + // catch\finally blocks has the same reachability as try block + var preTryState = currentReachabilityState; + bind(n.tryBlock); + var postTryState = currentReachabilityState; + currentReachabilityState = preTryState; + bind(n.catchClause); + var postCatchState = currentReachabilityState; + currentReachabilityState = preTryState; + bind(n.finallyBlock); + // post catch/finally state is reachable if + // - post try state is reachable - control flow can fall out of try block + // - post catch state is reachable - control flow can fall out of catch block + currentReachabilityState = or(postTryState, postCatchState); + } + function bindSwitchStatement(n) { + var preSwitchState = currentReachabilityState; + var postSwitchLabel = pushImplicitLabel(); + // bind expression (don't affect reachability) + bind(n.expression); + bind(n.caseBlock); + var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 245 /* DefaultClause */; }); + // post switch state is unreachable if switch is exaustive (has a default case ) and does not have fallthrough from the last case + var postSwitchState = hasDefault && currentReachabilityState !== 2 /* Reachable */ ? 4 /* Unreachable */ : preSwitchState; + popImplicitLabel(postSwitchLabel, postSwitchState); + } + function bindCaseBlock(n) { + var startState = currentReachabilityState; + for (var _i = 0, _a = n.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + currentReachabilityState = startState; + bind(clause); + if (clause.statements.length && currentReachabilityState === 2 /* Reachable */ && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + } + function bindLabeledStatement(n) { + // call bind on label (don't affect reachability) + bind(n.label); + var ok = pushNamedLabel(n.label); + bind(n.statement); + if (ok) { + popNamedLabel(n.label, currentReachabilityState); } - function parseJSDocUnionType() { - var result = createNode(253 /* JSDocUnionType */); - nextToken(); - result.types = parseJSDocTypeList(parseJSDocType()); - parseExpected(18 /* CloseParenToken */); - return finishNode(result); + } + function getContainerFlags(node) { + switch (node.kind) { + case 189 /* ClassExpression */: + case 217 /* ClassDeclaration */: + case 218 /* InterfaceDeclaration */: + case 220 /* EnumDeclaration */: + case 168 /* ObjectLiteralExpression */: + case 156 /* TypeLiteral */: + case 260 /* JSDocRecordType */: + return 1 /* IsContainer */; + case 148 /* CallSignature */: + case 149 /* ConstructSignature */: + case 150 /* IndexSignature */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 216 /* FunctionDeclaration */: + case 145 /* Constructor */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 153 /* FunctionType */: + case 154 /* ConstructorType */: + case 176 /* FunctionExpression */: + case 177 /* ArrowFunction */: + case 221 /* ModuleDeclaration */: + case 251 /* SourceFile */: + case 219 /* TypeAliasDeclaration */: + return 5 /* IsContainerWithLocals */; + case 247 /* CatchClause */: + case 202 /* ForStatement */: + case 203 /* ForInStatement */: + case 204 /* ForOfStatement */: + case 223 /* CaseBlock */: + return 2 /* IsBlockScopedContainer */; + case 195 /* 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 */; } - 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; + return 0 /* None */; + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; } - function parseJSDocAllType() { - var result = createNode(250 /* JSDocAllType */); - nextToken(); - return finishNode(result); + 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 221 /* ModuleDeclaration */: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 251 /* SourceFile */: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 189 /* ClassExpression */: + case 217 /* ClassDeclaration */: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 220 /* EnumDeclaration */: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 156 /* TypeLiteral */: + case 168 /* ObjectLiteralExpression */: + case 218 /* InterfaceDeclaration */: + case 260 /* JSDocRecordType */: + // 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 153 /* FunctionType */: + case 154 /* ConstructorType */: + case 148 /* CallSignature */: + case 149 /* ConstructSignature */: + case 150 /* IndexSignature */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 145 /* Constructor */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 216 /* FunctionDeclaration */: + case 176 /* FunctionExpression */: + case 177 /* ArrowFunction */: + case 264 /* JSDocFunctionType */: + case 219 /* 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 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 declareClassMember(node, symbolFlags, symbolExcludes) { + return node.flags & 64 /* 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 hasExportDeclarations(node) { + var body = node.kind === 251 /* SourceFile */ ? node : node.body; + if (body.kind === 251 /* SourceFile */ || body.kind === 222 /* ModuleBlock */) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var stat = _a[_i]; + if (stat.kind === 231 /* ExportDeclaration */ || stat.kind === 230 /* ExportAssignment */) { + return true; + } } } - 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; + 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 (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { + node.flags |= 131072 /* ExportContext */; } - JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; - function parseJSDocComment(parent, start, length) { - var comment = parseJSDocCommentWorker(start, length); - if (comment) { - fixupParentReferences(comment); - comment.parent = parent; - } - return comment; + else { + node.flags &= ~131072 /* ExportContext */; } - 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 bindModuleDeclaration(node) { + setExportContextFlag(node); + if (ts.isAmbientModule(node)) { + if (node.flags & 2 /* Export */) { + errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); } - function skipWhitespace() { - while (pos < end && ts.isWhiteSpace(content.charCodeAt(pos))) { - pos++; - } + declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); + } + else { + var state = getModuleInstanceState(node); + if (state === 0 /* NonInstantiated */) { + declareSymbolAndAddToSymbolTable(node, 1024 /* NamespaceModule */, 0 /* NamespaceModuleExcludes */); } - 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; + 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; } - 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); + else { + var currentModuleIsConstEnumOnly = state === 2 /* ConstEnumOnly */; + if (node.symbol.constEnumOnlyModule === undefined) { + // non-merged case - use the current state + node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; } - } - 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; + 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; } - 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); + } + } + 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 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 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 === 248 /* PropertyAssignment */ || prop.kind === 249 /* ShorthandPropertyAssignment */ || prop.kind === 144 /* MethodDeclaration */ + ? 1 /* Property */ + : 2 /* Accessor */; + var existingKind = seen[identifier.text]; + if (!existingKind) { + seen[identifier.text] = currentKind; + continue; } - 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++; + 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)); } - 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; - } + } + 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 221 /* ModuleDeclaration */: + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + case 251 /* SourceFile */: + if (ts.isExternalModule(container)) { + declareModuleMember(node, symbolFlags, symbolExcludes); break; } - if (startPos === pos) { - return undefined; + // fall through. + default: + if (!blockScopeContainer.locals) { + blockScopeContainer.locals = {}; + addToContainerChain(blockScopeContainer); } - var result = createNode(69 /* Identifier */, startPos); - result.text = content.substring(startPos, pos); - return finishNode(result, pos); + 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))); } } - 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; + } + 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 (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); + if (file.externalModuleIndicator) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; } - // 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; + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; } - IncrementalParser.updateSourceFile = updateSourceFile; - function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { - if (isArray) { - visitArray(element); + 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); } - else { - visitNode(element); + } + 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); } - 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; + } + 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)); } - node.pos += delta; - node.end += delta; - if (aggressiveChecks && shouldCheckNode(node)) { - ts.Debug.assert(text === newText.substring(node.pos, node.end)); + } + } + 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 & 32768 /* 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); } - 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 checkStrictModeWithStatement(node) { + // Grammar checking for withStatement + if (inStrictMode) { + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function errorOnFirstToken(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) { + if (!node) { + return; + } + 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 251 /* SourceFile */: + case 222 /* ModuleBlock */: + updateStrictModeStatementList(node.statements); + return; + case 195 /* Block */: + if (ts.isFunctionLike(node.parent)) { + updateStrictModeStatementList(node.statements); + } + return; + case 217 /* ClassDeclaration */: + case 189 /* ClassExpression */: + // All classes are automatically in strict mode in ES6. + inStrictMode = true; + return; + } + } + function updateStrictModeStatementList(statements) { + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (!ts.isPrologueDirective(statement)) { + return; + } + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; } } } - function shouldCheckNode(node) { + /// 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 9 /* StringLiteral */: - case 8 /* NumericLiteral */: + /* Strict mode checks */ case 69 /* Identifier */: - return true; + return checkStrictModeIdentifier(node); + case 184 /* BinaryExpression */: + if (ts.isInJavaScriptFile(node)) { + var specialKind = ts.getSpecialPropertyAssignmentKind(node); + switch (specialKind) { + case 1 /* ExportsProperty */: + bindExportsPropertyAssignment(node); + break; + case 2 /* ModuleExports */: + bindModuleExportsAssignment(node); + break; + case 3 /* PrototypeProperty */: + bindPrototypePropertyAssignment(node); + break; + case 4 /* ThisProperty */: + bindThisPropertyAssignment(node); + break; + case 0 /* None */: + // Nothing to do + break; + default: + ts.Debug.fail("Unknown special property assignment kind"); + } + } + return checkStrictModeBinaryExpression(node); + case 247 /* CatchClause */: + return checkStrictModeCatchClause(node); + case 178 /* DeleteExpression */: + return checkStrictModeDeleteExpression(node); + case 8 /* NumericLiteral */: + return checkStrictModeNumericLiteral(node); + case 183 /* PostfixUnaryExpression */: + return checkStrictModePostfixUnaryExpression(node); + case 182 /* PrefixUnaryExpression */: + return checkStrictModePrefixUnaryExpression(node); + case 208 /* WithStatement */: + return checkStrictModeWithStatement(node); + case 162 /* ThisType */: + seenThisKeyword = true; + return; + case 151 /* TypePredicate */: + return checkTypePredicate(node); + case 138 /* TypeParameter */: + return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530912 /* TypeParameterExcludes */); + case 139 /* Parameter */: + return bindParameter(node); + case 214 /* VariableDeclaration */: + case 166 /* BindingElement */: + return bindVariableDeclarationOrBindingElement(node); + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: + case 261 /* JSDocRecordMember */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 107455 /* PropertyExcludes */); + case 248 /* PropertyAssignment */: + case 249 /* ShorthandPropertyAssignment */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */); + case 250 /* EnumMember */: + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */); + case 148 /* CallSignature */: + case 149 /* ConstructSignature */: + case 150 /* IndexSignature */: + return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); + case 144 /* MethodDeclaration */: + case 143 /* 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 216 /* FunctionDeclaration */: + return bindFunctionDeclaration(node); + case 145 /* Constructor */: + return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); + case 146 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); + case 147 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); + case 153 /* FunctionType */: + case 154 /* ConstructorType */: + case 264 /* JSDocFunctionType */: + return bindFunctionOrConstructorType(node); + case 156 /* TypeLiteral */: + case 260 /* JSDocRecordType */: + return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type"); + case 168 /* ObjectLiteralExpression */: + return bindObjectLiteralExpression(node); + case 176 /* FunctionExpression */: + case 177 /* ArrowFunction */: + return bindFunctionExpression(node); + case 171 /* CallExpression */: + if (ts.isInJavaScriptFile(node)) { + bindCallExpression(node); + } + break; + // Members of classes, interfaces, and modules + case 189 /* ClassExpression */: + case 217 /* ClassDeclaration */: + return bindClassLikeDeclaration(node); + case 218 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 792960 /* InterfaceExcludes */); + case 219 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793056 /* TypeAliasExcludes */); + case 220 /* EnumDeclaration */: + return bindEnumDeclaration(node); + case 221 /* ModuleDeclaration */: + return bindModuleDeclaration(node); + // Imports and exports + case 224 /* ImportEqualsDeclaration */: + case 227 /* NamespaceImport */: + case 229 /* ImportSpecifier */: + case 233 /* ExportSpecifier */: + return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); + case 226 /* ImportClause */: + return bindImportClause(node); + case 231 /* ExportDeclaration */: + return bindExportDeclaration(node); + case 230 /* ExportAssignment */: + return bindExportAssignment(node); + case 251 /* SourceFile */: + return bindSourceFileIfExternalModule(); } - 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; + function checkTypePredicate(node) { + var parameterName = node.parameterName, type = node.type; + if (parameterName && parameterName.kind === 69 /* Identifier */) { + checkStrictModeIdentifier(parameterName); + } + if (parameterName && parameterName.kind === 162 /* ThisType */) { + seenThisKeyword = true; + } + bind(type); + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindSourceFileAsExternalModule(); + } + } + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); + } + function bindExportAssignment(node) { + var boundExpression = node.kind === 230 /* ExportAssignment */ ? node.expression : node.right; + if (!container.symbol || !container.symbol.exports) { + // Export assignment in some sort of block construct + bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node)); + } + else if (boundExpression.kind === 69 /* Identifier */ && node.kind === 230 /* ExportAssignment */) { + // 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 { - // 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); + // An export default clause with an expression exports a value + declareSymbol(container.symbol.exports, container.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); } - 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 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 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 bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); } } - 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; + function setCommonJsModuleIndicator(node) { + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + bindSourceFileAsExternalModule(); + } + } + function bindExportsPropertyAssignment(node) { + // When we create a property via 'exports.foo = bar', the 'exports.foo' property access + // expression is the declaration + setCommonJsModuleIndicator(node); + declareSymbol(file.symbol.exports, file.symbol, node.left, 4 /* Property */ | 7340032 /* Export */, 0 /* None */); + } + function bindModuleExportsAssignment(node) { + // 'module.exports = expr' assignment + setCommonJsModuleIndicator(node); + bindExportAssignment(node); + } + function bindThisPropertyAssignment(node) { + // Declare a 'member' in case it turns out the container was an ES5 class + if (container.kind === 176 /* FunctionExpression */ || container.kind === 216 /* FunctionDeclaration */) { + container.symbol.members = container.symbol.members || {}; + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */ & ~4 /* Property */); + } + } + function bindPrototypePropertyAssignment(node) { + // We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x was a function. + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + var leftSideOfAssignment = node.left; + var classPrototype = leftSideOfAssignment.expression; + var constructorFunction = classPrototype.expression; + // Fix up parent pointers since we're going to use these nodes before we bind into them + leftSideOfAssignment.parent = node; + constructorFunction.parent = classPrototype; + classPrototype.parent = leftSideOfAssignment; + var funcSymbol = container.locals[constructorFunction.text]; + if (!funcSymbol || !(funcSymbol.flags & 16 /* Function */)) { + return; + } + // Set up the members collection if it doesn't exist already + if (!funcSymbol.members) { + funcSymbol.members = {}; + } + // Declare the method/property + declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, 4 /* Property */, 107455 /* PropertyExcludes */); + } + function bindCallExpression(node) { + // We're only inspecting call expressions to detect CommonJS modules, so we can skip + // this check if we've already seen the module indicator + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ false)) { + setCommonJsModuleIndicator(node); + } + } + function bindClassLikeDeclaration(node) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.getClassExtendsHeritageClauseElement(node) !== undefined) { + hasClassExtends = true; } - // 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; + if (ts.nodeIsDecorated(node)) { + hasDecorators = true; } - // 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; + if (node.kind === 217 /* 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 */); } - // 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; + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107454 /* FunctionScopedVariableExcludes */); } - // 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); + function bindParameter(node) { + if (!ts.isDeclarationFile(file) && + !ts.isInAmbientContext(node) && + ts.nodeIsDecorated(node)) { + hasDecorators = true; + hasParameterDecorators = true; + } + 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 (ts.isParameterPropertyDeclaration(node)) { + var classDeclaration = node.parent.parent; + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */); } - 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; + function bindFunctionDeclaration(node) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunctionLike(node)) { + hasAsyncFunctions = true; } } - return bestResult; - function getLastChild(node) { - while (true) { - var lastChild = getLastChildWorker(node); - if (lastChild) { - node = lastChild; - } - else { - return node; - } + checkStrictModeFunctionName(node); + return declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */); + } + function bindFunctionExpression(node) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunctionLike(node)) { + hasAsyncFunctions = true; } } - 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; - } + checkStrictModeFunctionName(node); + var bindingName = node.name ? node.name.text : "__function"; + return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); + } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + if (!ts.isDeclarationFile(file) && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunctionLike(node)) { + hasAsyncFunctions = true; } - 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; + if (ts.nodeIsDecorated(node)) { + hasDecorators = true; } } + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed") + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } - 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); - } + // reachability checks + function pushNamedLabel(name) { + initializeReachabilityStateIfNecessary(); + if (ts.hasProperty(labelIndexMap, name.text)) { + return false; } + labelIndexMap[name.text] = labelStack.push(1 /* Unintialized */) - 1; + return true; } - 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 pushImplicitLabel() { + initializeReachabilityStateIfNecessary(); + var index = labelStack.push(1 /* Unintialized */) - 1; + implicitLabels.push(index); + return index; + } + function popNamedLabel(label, outerState) { + var index = labelIndexMap[label.text]; + ts.Debug.assert(index !== undefined); + ts.Debug.assert(labelStack.length == index + 1); + labelIndexMap[label.text] = undefined; + setCurrentStateAtLabel(labelStack.pop(), outerState, label); + } + function popImplicitLabel(implicitLabelIndex, outerState) { + if (labelStack.length !== implicitLabelIndex + 1) { + ts.Debug.assert(false, "Label stack: " + labelStack.length + ", index:" + implicitLabelIndex); + } + var i = implicitLabels.pop(); + if (implicitLabelIndex !== i) { + ts.Debug.assert(false, "i: " + i + ", index: " + implicitLabelIndex); + } + setCurrentStateAtLabel(labelStack.pop(), outerState, /*name*/ undefined); + } + function setCurrentStateAtLabel(innerMergedState, outerState, label) { + if (innerMergedState === 1 /* Unintialized */) { + if (label && !options.allowUnusedLabels) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(label, ts.Diagnostics.Unused_label)); } - 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. + currentReachabilityState = outerState; + } + else { + currentReachabilityState = or(innerMergedState, outerState); + } + } + function jumpToLabel(label, outerState) { + initializeReachabilityStateIfNecessary(); + var index = label ? labelIndexMap[label.text] : ts.lastOrUndefined(implicitLabels); + if (index === undefined) { + // reference to unknown label or + // break/continue used outside of loops + return false; + } + var stateAtLabel = labelStack[index]; + labelStack[index] = stateAtLabel === 1 /* Unintialized */ ? outerState : or(stateAtLabel, outerState); + return true; + } + function checkUnreachable(node) { + switch (currentReachabilityState) { + case 4 /* Unreachable */: + var reportError = + // report error on all statements except empty ones + (ts.isStatement(node) && node.kind !== 197 /* EmptyStatement */) || + // report error on class declarations + node.kind === 217 /* ClassDeclaration */ || + // report error on instantiated modules or const-enums only modules if preserveConstEnums is set + (node.kind === 221 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || + // report error on regular enums and const enums if preserveConstEnums is set + (node.kind === 220 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + if (reportError) { + currentReachabilityState = 8 /* ReportedUnreachable */; + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var reportUnreachableCode = !options.allowUnreachableCode && + !ts.isInAmbientContext(node) && + (node.kind !== 196 /* VariableStatement */ || + ts.getCombinedNodeFlags(node.declarationList) & 24576 /* BlockScoped */ || + ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); + if (reportUnreachableCode) { + errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + } + } + case 8 /* ReportedUnreachable */: + return true; + default: return false; - } + } + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums); } } - var InvalidPosition; - (function (InvalidPosition) { - InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; - })(InvalidPosition || (InvalidPosition = {})); - })(IncrementalParser || (IncrementalParser = {})); + function initializeReachabilityStateIfNecessary() { + if (labelIndexMap) { + return; + } + currentReachabilityState = 2 /* Reachable */; + labelIndexMap = {}; + labelStack = []; + implicitLabels = []; + } + } })(ts || (ts = {})); /// /* @internal */ @@ -13222,15 +14632,18 @@ var ts; var nextNodeId = 1; var nextMergeId = 1; function getNodeId(node) { - if (!node.id) - node.id = nextNodeId++; + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } return node.id; } ts.getNodeId = getNodeId; ts.checkTime = 0; function getSymbolId(symbol) { if (!symbol.id) { - symbol.id = nextSymbolId++; + symbol.id = nextSymbolId; + nextSymbolId++; } return symbol.id; } @@ -13255,9 +14668,11 @@ var ts; 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 modulekind = ts.getEmitModuleKind(compilerOptions); + var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === 4 /* System */; var emitResolver = createResolver(); var undefinedSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "undefined"); + undefinedSymbol.declarations = []; var argumentsSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "arguments"); var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, @@ -13266,11 +14681,13 @@ var ts; getTypeCount: function () { return typeCount; }, isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, + isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, 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, + getSymbolsOfParameterPropertyDeclaration: getSymbolsOfParameterPropertyDeclaration, getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, getPropertiesOfType: getPropertiesOfType, getPropertyOfType: getPropertyOfType, @@ -13281,6 +14698,7 @@ var ts; getSymbolsInScope: getSymbolsInScope, getSymbolAtLocation: getSymbolAtLocation, getShorthandAssignmentValueSymbol: getShorthandAssignmentValueSymbol, + getExportSpecifierLocalTargetSymbol: getExportSpecifierLocalTargetSymbol, getTypeAtLocation: getTypeOfNode, typeToString: typeToString, getSymbolDisplayBuilder: getSymbolDisplayBuilder, @@ -13312,8 +14730,8 @@ var ts; 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 emptyUnionType = emptyObjectType; var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); emptyGenericType.instantiations = {}; var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -13321,8 +14739,8 @@ var ts; // 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 anySignature = createSignature(undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); + var unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false); var globals = {}; var globalESSymbolConstructorSymbol; var getGlobalPromiseConstructorSymbol; @@ -13335,9 +14753,6 @@ var ts; var globalRegExpType; var globalTemplateStringsArrayType; var globalESSymbolType; - var jsxElementType; - /** Lazily loaded, use getJsxIntrinsicElementType() */ - var jsxIntrinsicElementsType; var globalIterableType; var globalIteratorType; var globalIterableIteratorType; @@ -13353,15 +14768,12 @@ var ts; var getInstantiatedGlobalPromiseLikeType; var getGlobalPromiseConstructorLikeType; var getGlobalThenableType; + var jsxElementClassType; + var deferredNodes; 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 = []; @@ -13387,14 +14799,23 @@ var ts; "symbol": { type: esSymbolType, flags: 16777216 /* ESSymbol */ + }, + "undefined": { + type: undefinedType, + flags: 2097152 /* ContainsUndefinedOrNull */ } }; + var jsxElementType; + /** Things we lazy load from the JSX namespace */ + var jsxTypes = {}; var JsxNames = { JSX: "JSX", IntrinsicElements: "IntrinsicElements", ElementClass: "ElementClass", ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - Element: "Element" + Element: "Element", + IntrinsicAttributes: "IntrinsicAttributes", + IntrinsicClassAttributes: "IntrinsicClassAttributes" }; var subtypeRelation = {}; var assignableRelation = {}; @@ -13408,6 +14829,10 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); + var builtinGlobals = (_a = {}, + _a[undefinedSymbol.name] = undefinedSymbol, + _a + ); initializeTypeChecker(); return checker; function getEmitResolver(sourceFile, cancellationToken) { @@ -13463,8 +14888,10 @@ var ts; return result; } function recordMergedSymbol(target, source) { - if (!source.mergeId) - source.mergeId = nextMergeId++; + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } mergedSymbols[source.mergeId] = target; } function cloneSymbol(symbol) { @@ -13489,8 +14916,12 @@ var ts; target.constEnumOnlyModule = false; } target.flags |= source.flags; - if (!target.valueDeclaration && source.valueDeclaration) + if (source.valueDeclaration && + (!target.valueDeclaration || + (target.valueDeclaration.kind === 221 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 221 /* ModuleDeclaration */))) { + // other kinds of value declarations take precedence over modules target.valueDeclaration = source.valueDeclaration; + } ts.forEach(source.declarations, function (node) { target.declarations.push(node); }); @@ -13507,13 +14938,13 @@ var ts; recordMergedSymbol(target, source); } else { - var message = target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */ + var message_2 = 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)); + error(node.name ? node.name : node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message, symbolToString(source)); + error(node.name ? node.name : node, message_2, symbolToString(source)); }); } } @@ -13542,6 +14973,53 @@ var ts; } } } + function mergeModuleAugmentation(moduleName) { + var moduleAugmentation = moduleName.parent; + if (moduleAugmentation.symbol.valueDeclaration !== moduleAugmentation) { + // this is a combined symbol for multiple augmentations within the same file. + // its symbol already has accumulated information for all declarations + // so we need to add it just once - do the work only for first declaration + ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); + return; + } + if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { + mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + } + else { + // find a module that about to be augmented + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found); + if (!mainModule) { + return; + } + // obtain item referenced by 'export=' + mainModule = resolveExternalModuleSymbol(mainModule); + if (mainModule.flags & 1536 /* Namespace */) { + // if module symbol has already been merged - it is safe to use it. + // otherwise clone it + mainModule = mainModule.flags & 33554432 /* Merged */ ? mainModule : cloneSymbol(mainModule); + mergeSymbol(mainModule, moduleAugmentation.symbol); + } + else { + error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); + } + } + } + function addToSymbolTable(target, source, message) { + for (var id in source) { + if (ts.hasProperty(source, id)) { + if (ts.hasProperty(target, id)) { + // Error on redeclarations + ts.forEach(target[id].declarations, addDeclarationDiagnostic(id, message)); + } + else { + target[id] = source[id]; + } + } + } + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } function getSymbolLinks(symbol) { if (symbol.flags & 67108864 /* Transient */) return symbol; @@ -13552,11 +15030,8 @@ var ts; 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); + return node.kind === 251 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning && ts.hasProperty(symbols, name)) { @@ -13575,6 +15050,22 @@ var ts; } // return undefined if we can't find a symbol. } + /** + * Get symbols that represent parameter-property-declaration as parameter and as property declaration + * @param parameter a parameterDeclaration node + * @param parameterName a name of the parameter to get the symbols for. + * @return a tuple of two symbols + */ + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructoDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructoDeclaration.locals, parameterName, 107455 /* Value */); + var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455 /* Value */); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); @@ -13589,7 +15080,7 @@ var ts; 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 */ || + return declaration.kind !== 214 /* VariableDeclaration */ || !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } // declaration is after usage @@ -13597,14 +15088,14 @@ var ts; 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 */) { + if (declaration.parent.parent.kind === 196 /* VariableStatement */ || + declaration.parent.parent.kind === 202 /* 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 */) { + else if (declaration.parent.parent.kind === 204 /* ForOfStatement */ || + declaration.parent.parent.kind === 203 /* ForInStatement */) { // ForIn/ForOf case - use site should not be used in expression part var expression = declaration.parent.parent.expression; return isSameScopeDescendentOf(usage, expression, container); @@ -13621,8 +15112,8 @@ var ts; return true; } var initializerOfNonStaticProperty = current.parent && - current.parent.kind === 141 /* PropertyDeclaration */ && - (current.parent.flags & 128 /* Static */) === 0 && + current.parent.kind === 142 /* PropertyDeclaration */ && + (current.parent.flags & 64 /* Static */) === 0 && current.parent.initializer === current; if (initializerOfNonStaticProperty) { return true; @@ -13645,28 +15136,59 @@ var ts; // 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) { + var useResult = true; + if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { + // symbol lookup restrictions for function-like declarations + // - 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. + // - parameters are only in the scope of function body + // This restriction does not apply to JSDoc comment types because they are parented + // at a higher level than type parameters would normally be + if (meaning & result.flags & 793056 /* Type */ && lastLocation.kind !== 268 /* JSDocComment */) { + useResult = result.flags & 262144 /* TypeParameter */ + ? lastLocation === location.type || + lastLocation.kind === 139 /* Parameter */ || + lastLocation.kind === 138 /* TypeParameter */ + : false; + } + if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 139 /* Parameter */ || + (lastLocation === location.type && + result.valueDeclaration.kind === 139 /* Parameter */); + } + } + if (useResult) { break loop; } - result = undefined; + else { + result = undefined; + } } } switch (location.kind) { - case 248 /* SourceFile */: - if (!ts.isExternalModule(location)) + case 251 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) break; - case 218 /* ModuleDeclaration */: + case 221 /* 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. + if (location.kind === 251 /* SourceFile */ || ts.isAmbientModule(location)) { + // It's an external module. First see if the module has an export default and if the local + // name of that export default matches. + if (result = moduleExports["default"]) { + var localSymbol = ts.getLocalSymbolForExportDefault(result); + if (localSymbol && (result.flags & meaning) && localSymbol.name === name) { + break loop; + } + result = undefined; + } + // 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 @@ -13677,34 +15199,28 @@ var ts; // which is not the desired behavior. if (ts.hasProperty(moduleExports, name) && moduleExports[name].flags === 8388608 /* Alias */ && - ts.getDeclarationOfKind(moduleExports[name], 230 /* ExportSpecifier */)) { + ts.getDeclarationOfKind(moduleExports[name], 233 /* 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 */: + case 220 /* EnumDeclaration */: if (result = getSymbol(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 142 /* PropertyDeclaration */: + case 141 /* 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 */)) { + if (ts.isClassLike(location.parent) && !(location.flags & 64 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) { @@ -13714,11 +15230,11 @@ var ts; } } break; - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: - case 215 /* InterfaceDeclaration */: + case 217 /* ClassDeclaration */: + case 189 /* ClassExpression */: + case 218 /* InterfaceDeclaration */: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056 /* Type */)) { - if (lastLocation && lastLocation.flags & 128 /* Static */) { + if (lastLocation && lastLocation.flags & 64 /* 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. @@ -13727,7 +15243,7 @@ var ts; } break loop; } - if (location.kind === 186 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 189 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.text) { result = location.symbol; @@ -13743,9 +15259,9 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 136 /* ComputedPropertyName */: + case 137 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 215 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 218 /* 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); @@ -13753,19 +15269,19 @@ var ts; } } break; - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 145 /* Constructor */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 216 /* FunctionDeclaration */: + case 177 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 173 /* FunctionExpression */: + case 176 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -13778,7 +15294,7 @@ var ts; } } break; - case 139 /* Decorator */: + case 140 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -13787,7 +15303,7 @@ var ts; // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. // } // - if (location.parent && location.parent.kind === 138 /* Parameter */) { + if (location.parent && location.parent.kind === 139 /* Parameter */) { location = location.parent; } // @@ -13809,7 +15325,9 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg)) { + error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + } } return undefined; } @@ -13828,7 +15346,7 @@ var ts; // declare module foo { // interface bar {} // } - // let foo/*1*/: foo/*2*/.bar; + // const 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, @@ -13842,12 +15360,44 @@ var ts; } return result; } + function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { + if (!errorLocation || (errorLocation.kind === 69 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + return false; + } + var container = ts.getThisContainer(errorLocation, /* includeArrowFunctions */ true); + var location = container; + while (location) { + if (ts.isClassLike(location.parent)) { + var classSymbol = getSymbolOfNode(location.parent); + if (!classSymbol) { + break; + } + // Check to see if a static member exists. + var constructorType = getTypeOfSymbol(classSymbol); + if (getPropertyOfType(constructorType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), symbolToString(classSymbol)); + return true; + } + // No static member is present. + // Check if we're in an instance method and look for a relevant instance member. + if (location === container && !(location.flags & 64 /* Static */)) { + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; + if (getPropertyOfType(instanceType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); + return true; + } + } + } + location = location.parent; + } + return false; + } 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)) { + if (!isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 214 /* VariableDeclaration */), errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); } } @@ -13868,10 +15418,10 @@ var ts; } function getAnyImportSyntax(node) { if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 221 /* ImportEqualsDeclaration */) { + if (node.kind === 224 /* ImportEqualsDeclaration */) { return node; } - while (node && node.kind !== 222 /* ImportDeclaration */) { + while (node && node.kind !== 225 /* ImportDeclaration */) { node = node.parent; } return node; @@ -13881,7 +15431,7 @@ var ts; return ts.forEach(symbol.declarations, function (d) { return ts.isAliasSymbolDeclaration(d) ? d : undefined; }); } function getTargetOfImportEqualsDeclaration(node) { - if (node.moduleReference.kind === 232 /* ExternalModuleReference */) { + if (node.moduleReference.kind === 235 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, node); @@ -13890,9 +15440,12 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { var exportDefaultSymbol = resolveSymbol(moduleSymbol.exports["default"]); - if (!exportDefaultSymbol) { + if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } + else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + return resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); + } return exportDefaultSymbol; } } @@ -13900,14 +15453,6 @@ var ts; 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: // @@ -13988,17 +15533,17 @@ var ts; } function getTargetOfAliasDeclaration(node) { switch (node.kind) { - case 221 /* ImportEqualsDeclaration */: + case 224 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node); - case 223 /* ImportClause */: + case 226 /* ImportClause */: return getTargetOfImportClause(node); - case 224 /* NamespaceImport */: + case 227 /* NamespaceImport */: return getTargetOfNamespaceImport(node); - case 226 /* ImportSpecifier */: + case 229 /* ImportSpecifier */: return getTargetOfImportSpecifier(node); - case 230 /* ExportSpecifier */: + case 233 /* ExportSpecifier */: return getTargetOfExportSpecifier(node); - case 227 /* ExportAssignment */: + case 230 /* ExportAssignment */: return getTargetOfExportAssignment(node); } } @@ -14043,11 +15588,11 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - if (node.kind === 227 /* ExportAssignment */) { + if (node.kind === 230 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); } - else if (node.kind === 230 /* ExportSpecifier */) { + else if (node.kind === 233 /* ExportSpecifier */) { // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } @@ -14060,7 +15605,7 @@ var ts; // This function is only for imports with entity names function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, importDeclaration) { if (!importDeclaration) { - importDeclaration = ts.getAncestor(entityName, 221 /* ImportEqualsDeclaration */); + importDeclaration = ts.getAncestor(entityName, 224 /* ImportEqualsDeclaration */); ts.Debug.assert(importDeclaration !== undefined); } // There are three things we might try to look for. In the following examples, @@ -14073,13 +15618,13 @@ var ts; entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 69 /* Identifier */ || entityName.parent.kind === 135 /* QualifiedName */) { + if (entityName.kind === 69 /* Identifier */ || entityName.parent.kind === 136 /* 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 */); + ts.Debug.assert(entityName.parent.kind === 224 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */); } } @@ -14099,9 +15644,9 @@ var ts; 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; + else if (name.kind === 136 /* QualifiedName */ || name.kind === 169 /* PropertyAccessExpression */) { + var left = name.kind === 136 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 136 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, 1536 /* Namespace */, ignoreErrors); if (!namespace || namespace === unknownSymbol || ts.nodeIsMissing(right)) { return undefined; @@ -14121,11 +15666,13 @@ var ts; return symbol.flags & meaning ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); + } + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError) { 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); @@ -14136,24 +15683,33 @@ var ts; if (!isRelative) { var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512 /* ValueModule */); if (symbol) { - return symbol; + // merged symbol is module declaration symbol combined with all augmentations + return getMergedSymbol(symbol); } } - var resolvedModule = ts.getResolvedModule(getSourceFile(location), moduleReferenceLiteral.text); + var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReferenceLiteral.text); var sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - return sourceFile.symbol; + // merged symbol is module declaration symbol combined with all augmentations + return getMergedSymbol(sourceFile.symbol); } - error(moduleReferenceLiteral, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); - return; + if (moduleNotFoundError) { + // report errors only if it was requested + error(moduleReferenceLiteral, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + } + return undefined; + } + if (moduleNotFoundError) { + // report errors only if it was requested + error(moduleReferenceLiteral, moduleNotFoundError, moduleName); } - error(moduleReferenceLiteral, ts.Diagnostics.Cannot_find_module_0, moduleName); + return undefined; } // 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; + return moduleSymbol && getMergedSymbol(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 @@ -14166,8 +15722,8 @@ var ts; } return symbol; } - function getExportAssignmentSymbol(moduleSymbol) { - return moduleSymbol.exports["export="]; + function hasExportAssignmentSymbol(moduleSymbol) { + return moduleSymbol.exports["export="] !== undefined; } function getExportsOfModuleAsArray(moduleSymbol) { return symbolsToArray(getExportsOfModule(moduleSymbol)); @@ -14179,38 +15735,66 @@ var ts; var links = getSymbolLinks(moduleSymbol); return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol)); } - function extendExportSymbols(target, source) { + /** + * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument + * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables + */ + function extendExportSymbols(target, source, lookupTable, exportNode) { for (var id in source) { if (id !== "default" && !ts.hasProperty(target, id)) { target[id] = source[id]; + if (lookupTable && exportNode) { + lookupTable[id] = { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }; + } + } + else if (lookupTable && exportNode && id !== "default" && ts.hasProperty(target, id) && resolveSymbol(target[id]) !== resolveSymbol(source[id])) { + if (!lookupTable[id].exportsWithDuplicate) { + lookupTable[id].exportsWithDuplicate = [exportNode]; + } + else { + lookupTable[id].exportsWithDuplicate.push(exportNode); + } } } } function getExportsForModule(moduleSymbol) { - var result; var visitedSymbols = []; - visit(moduleSymbol); - return result || moduleSymbol.exports; + return visit(moduleSymbol) || 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); + if (!(symbol && symbol.flags & 1952 /* HasExports */ && !ts.contains(visitedSymbols, symbol))) { + return; + } + visitedSymbols.push(symbol); + var symbols = cloneSymbolTable(symbol.exports); + // All export * declarations are collected in an __export symbol by the binder + var exportStars = symbol.exports["__export"]; + if (exportStars) { + var nestedSymbols = {}; + var lookupTable = {}; + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable, node); + } + for (var id in lookupTable) { + var exportsWithDuplicate = lookupTable[id].exportsWithDuplicate; + // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || ts.hasProperty(symbols, id)) { + continue; } - 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)); + for (var _b = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _b < exportsWithDuplicate_1.length; _b++) { + var node = exportsWithDuplicate_1[_b]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable[id].specifierText, id)); } } + extendExportSymbols(symbols, nestedSymbols); } + return symbols; } } function getMergedSymbol(symbol) { @@ -14246,16 +15830,17 @@ var ts; } 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)) { + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var member = members_1[_i]; + if (member.kind === 145 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } } function createType(flags) { var result = new Type(checker, flags); - result.id = typeCount++; + result.id = typeCount; + typeCount++; return result; } function createIntrinsicType(kind, intrinsicName) { @@ -14318,17 +15903,17 @@ var ts; } } switch (location_1.kind) { - case 248 /* SourceFile */: - if (!ts.isExternalModule(location_1)) { + case 251 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location_1)) { break; } - case 218 /* ModuleDeclaration */: + case 221 /* ModuleDeclaration */: if (result = callback(getSymbolOfNode(location_1).exports)) { return result; } break; - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: + case 217 /* ClassDeclaration */: + case 218 /* InterfaceDeclaration */: if (result = callback(getSymbolOfNode(location_1).members)) { return result; } @@ -14369,7 +15954,7 @@ var ts; return ts.forEachValue(symbols, function (symbolFromSymbolTable) { if (symbolFromSymbolTable.flags & 8388608 /* Alias */ && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 230 /* ExportSpecifier */)) { + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 233 /* ExportSpecifier */)) { if (!useOnlyExternalAliasing || // Is this external alias, then use it to name ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { @@ -14406,7 +15991,7 @@ var ts; 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; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 233 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -14441,7 +16026,7 @@ var ts; // export class c { // } // } - // let x: typeof m.c + // const 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 @@ -14479,8 +16064,7 @@ var ts; } } function hasExternalModuleSymbol(declaration) { - return (declaration.kind === 218 /* ModuleDeclaration */ && declaration.name.kind === 9 /* StringLiteral */) || - (declaration.kind === 248 /* SourceFile */ && ts.isExternalModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 251 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol) { var aliasesToMakeVisible; @@ -14494,7 +16078,7 @@ var ts; // because these kind of aliases can be used to name types in declaration file var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(anyImportSyntax.flags & 1 /* Export */) && + !(anyImportSyntax.flags & 2 /* Export */) && isDeclarationVisible(anyImportSyntax.parent)) { getNodeLinks(declaration).isVisible = true; if (aliasesToMakeVisible) { @@ -14516,12 +16100,12 @@ var ts; function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 154 /* TypeQuery */) { + if (entityName.parent.kind === 155 /* TypeQuery */) { // Typeof value meaning = 107455 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 135 /* QualifiedName */ || entityName.kind === 166 /* PropertyAccessExpression */ || - entityName.parent.kind === 221 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 136 /* QualifiedName */ || entityName.kind === 169 /* PropertyAccessExpression */ || + entityName.parent.kind === 224 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1536 /* Namespace */; @@ -14555,9 +16139,9 @@ var ts; ts.releaseStringWriter(writer); return result; } - function signatureToString(signature, enclosingDeclaration, flags) { + function signatureToString(signature, enclosingDeclaration, flags, kind) { var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); var result = writer.string(); ts.releaseStringWriter(writer); return result; @@ -14573,18 +16157,30 @@ var ts; } return result; } + function typePredicateToString(typePredicate, enclosingDeclaration, flags) { + var writer = ts.getSingleLineStringWriter(); + getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); + var result = writer.string(); + ts.releaseStringWriter(writer); + 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 */) { + while (node.kind === 161 /* ParenthesizedType */) { node = node.parent; } - if (node.kind === 216 /* TypeAliasDeclaration */) { + if (node.kind === 219 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } return undefined; } + function isTopLevelInExternalModuleAugmentation(node) { + return node && node.parent && + node.parent.kind === 222 /* ModuleBlock */ && + ts.isExternalModuleAugmentation(node.parent.parent); + } function getSymbolDisplayBuilder() { function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { @@ -14593,10 +16189,10 @@ var ts; return ts.declarationNameToString(declaration.name); } switch (declaration.kind) { - case 186 /* ClassExpression */: + case 189 /* ClassExpression */: return "(Anonymous class)"; - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 176 /* FunctionExpression */: + case 177 /* ArrowFunction */: return "(Anonymous function)"; } } @@ -14631,7 +16227,7 @@ var ts; parentSymbol = symbol; appendSymbolNameOnly(symbol, writer); } - // Let the writer know we just wrote out a symbol. The declaration emitter writer uses + // const 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. // @@ -14648,8 +16244,8 @@ var ts; walkSymbol(getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol), getQualifiedLeftMeaning(meaning)); } if (accessibleSymbolChain) { - for (var _i = 0; _i < accessibleSymbolChain.length; _i++) { - var accessibleSymbol = accessibleSymbolChain[_i]; + for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { + var accessibleSymbol = accessibleSymbolChain_1[_i]; appendParentTypeArgumentsAndSymbolName(accessibleSymbol); } } @@ -14712,7 +16308,7 @@ var ts; writeAnonymousType(type, flags); } else if (type.flags & 256 /* StringLiteral */) { - writer.writeStringLiteral(type.text); + writer.writeStringLiteral("\"" + ts.escapeString(type.text) + "\""); } else { // Should never get here @@ -14743,11 +16339,13 @@ var ts; } if (pos < end) { writePunctuation(writer, 25 /* LessThanToken */); - writeType(typeArguments[pos++], 0 /* None */); + writeType(typeArguments[pos], 0 /* None */); + pos++; while (pos < end) { writePunctuation(writer, 24 /* CommaToken */); writeSpace(writer); - writeType(typeArguments[pos++], 0 /* None */); + writeType(typeArguments[pos], 0 /* None */); + pos++; } writePunctuation(writer, 27 /* GreaterThanToken */); } @@ -14770,14 +16368,14 @@ var ts; 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]); + var parent_4 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_3); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_4); // 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); + writeSymbolTypeReference(parent_4, typeArguments, start, i, flags); writePunctuation(writer, 21 /* DotToken */); } } @@ -14839,11 +16437,11 @@ var ts; } function shouldWriteTypeOfFunctionSymbol() { var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && - ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 128 /* Static */; })); + ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 64 /* 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 */; + return declaration.parent.kind === 251 /* SourceFile */ || declaration.parent.kind === 222 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions @@ -14879,7 +16477,7 @@ var ts; if (flags & 64 /* InElementType */) { writePunctuation(writer, 17 /* OpenParenToken */); } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, symbolStack); + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); if (flags & 64 /* InElementType */) { writePunctuation(writer, 18 /* CloseParenToken */); } @@ -14891,7 +16489,7 @@ var ts; } writeKeyword(writer, 92 /* NewKeyword */); writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, symbolStack); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); if (flags & 64 /* InElementType */) { writePunctuation(writer, 18 /* CloseParenToken */); } @@ -14905,15 +16503,13 @@ var ts; writer.increaseIndent(); for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, 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); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1 /* Construct */, symbolStack); writePunctuation(writer, 23 /* SemicolonToken */); writer.writeLine(); } @@ -14950,13 +16546,13 @@ var ts; 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]; + for (var _f = 0, signatures_1 = signatures; _f < signatures_1.length; _f++) { + var signature = signatures_1[_f]; buildSymbolDisplay(p, writer); if (p.flags & 536870912 /* Optional */) { writePunctuation(writer, 53 /* QuestionToken */); } - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); writePunctuation(writer, 23 /* SemicolonToken */); writer.writeLine(); } @@ -14978,10 +16574,10 @@ var ts; inObjectTypeLiteral = saveInObjectTypeLiteral; } } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaraiton, flags) { + function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { var targetSymbol = getTargetSymbol(symbol); if (targetSymbol.flags & 32 /* Class */ || targetSymbol.flags & 64 /* Interface */ || targetSymbol.flags & 524288 /* TypeAlias */) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaraiton, flags); + buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); } } function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { @@ -15044,6 +16640,18 @@ var ts; } writePunctuation(writer, 18 /* CloseParenToken */); } + function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { + if (ts.isIdentifierTypePredicate(predicate)) { + writer.writeParameter(predicate.parameterName); + } + else { + writeKeyword(writer, 97 /* ThisKeyword */); + } + writeSpace(writer); + writeKeyword(writer, 124 /* IsKeyword */); + writeSpace(writer); + buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); + } function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { if (flags & 8 /* WriteArrowStyleSignature */) { writeSpace(writer); @@ -15053,20 +16661,19 @@ var ts; 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; + buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); } else { - returnType = getReturnTypeOfSignature(signature); + var returnType = getReturnTypeOfSignature(signature); + buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); } - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { + function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { + if (kind === 1 /* Construct */) { + writeKeyword(writer, 92 /* NewKeyword */); + writeSpace(writer); + } if (signature.target && (flags & 32 /* WriteTypeArgumentsOfSignature */)) { // Instantiated signature, write type arguments instead // This is achieved by passing in the mapper separately @@ -15082,6 +16689,7 @@ var ts; buildSymbolDisplay: buildSymbolDisplay, buildTypeDisplay: buildTypeDisplay, buildTypeParameterDisplay: buildTypeParameterDisplay, + buildTypePredicateDisplay: buildTypePredicateDisplay, buildParameterDisplay: buildParameterDisplay, buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, @@ -15091,145 +16699,96 @@ var ts; }); } 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; - } - }); - } + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); } + return links.isVisible; } + return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 163 /* BindingElement */: + case 166 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 211 /* VariableDeclaration */: + case 214 /* 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); + case 221 /* ModuleDeclaration */: + case 217 /* ClassDeclaration */: + case 218 /* InterfaceDeclaration */: + case 219 /* TypeAliasDeclaration */: + case 216 /* FunctionDeclaration */: + case 220 /* EnumDeclaration */: + case 224 /* ImportEqualsDeclaration */: + // external module augmentation is always visible + if (ts.isExternalModuleAugmentation(node)) { + return true; + } + var parent_5 = 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); + if (!(ts.getCombinedNodeFlags(node) & 2 /* Export */) && + !(node.kind !== 224 /* ImportEqualsDeclaration */ && parent_5.kind !== 251 /* SourceFile */ && ts.isInAmbientContext(parent_5))) { + return isGlobalSourceFile(parent_5); } // 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 */)) { + return isDeclarationVisible(parent_5); + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + if (node.flags & (16 /* Private */ | 32 /* 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 */: + // Public properties/methods are visible if its parents are visible, so const it fall into next case statement + case 145 /* Constructor */: + case 149 /* ConstructSignature */: + case 148 /* CallSignature */: + case 150 /* IndexSignature */: + case 139 /* Parameter */: + case 222 /* ModuleBlock */: + case 153 /* FunctionType */: + case 154 /* ConstructorType */: + case 156 /* TypeLiteral */: + case 152 /* TypeReference */: + case 157 /* ArrayType */: + case 158 /* TupleType */: + case 159 /* UnionType */: + case 160 /* IntersectionType */: + case 161 /* 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 */: + case 226 /* ImportClause */: + case 227 /* NamespaceImport */: + case 229 /* ImportSpecifier */: return false; // Type parameters are always visible - case 137 /* TypeParameter */: + case 138 /* TypeParameter */: // Source file is always visible - case 248 /* SourceFile */: + case 251 /* SourceFile */: return true; - // Export assignements do not create name bindings outside the module - case 227 /* ExportAssignment */: + // Export assignments do not create name bindings outside the module + case 230 /* 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 */) { + if (node.parent && node.parent.kind === 230 /* 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 */) { + else if (node.parent.kind === 233 /* ExportSpecifier */) { var exportSpecifier = node.parent; exportSymbol = exportSpecifier.parent.parent.moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : @@ -15252,7 +16811,9 @@ var ts; 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); + if (importSymbol) { + buildVisibleNodeList(importSymbol.declarations); + } } }); } @@ -15279,7 +16840,7 @@ var ts; return false; } resolutionTargets.push(target); - resolutionResults.push(true); + resolutionResults.push(/*items*/ true); resolutionPropertyNames.push(propertyName); return true; } @@ -15319,16 +16880,27 @@ var ts; } 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; + while (node) { + switch (node.kind) { + case 214 /* VariableDeclaration */: + case 215 /* VariableDeclarationList */: + case 229 /* ImportSpecifier */: + case 228 /* NamedImports */: + case 227 /* NamespaceImport */: + case 226 /* ImportClause */: + node = node.parent; + break; + default: + return 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); + var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); 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 @@ -15345,6 +16917,23 @@ var ts; var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node); } + function getTextOfPropertyName(name) { + switch (name.kind) { + case 69 /* Identifier */: + return name.text; + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return name.text; + case 137 /* ComputedPropertyName */: + if (ts.isStringOrNumericLiteral(name.expression.kind)) { + return name.expression.text; + } + } + return undefined; + } + function isComputedNonLiteralName(name) { + return name.kind === 137 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression.kind); + } // Return the inferred type for a binding element function getTypeForBindingElement(declaration) { var pattern = declaration.parent; @@ -15363,13 +16952,18 @@ var ts; return parentType; } var type; - if (pattern.kind === 161 /* ObjectBindingPattern */) { + if (pattern.kind === 164 /* ObjectBindingPattern */) { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name_10 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_10)) { + // computed properties with non-literal names are treated as 'any' + return anyType; + } // 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 */) || + var text = getTextOfPropertyName(name_10); + type = getTypeOfPropertyOfType(parentType, text) || + isNumericLiteralName(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)); @@ -15404,13 +16998,53 @@ var ts; } return type; } + function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { + var jsDocType = getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration); + if (jsDocType) { + return getTypeFromTypeNode(jsDocType); + } + } + function getJSDocTypeForVariableLikeDeclarationFromJSDocComment(declaration) { + // First, see if this node has an @type annotation on it directly. + var typeTag = ts.getJSDocTypeTag(declaration); + if (typeTag && typeTag.typeExpression) { + return typeTag.typeExpression.type; + } + if (declaration.kind === 214 /* VariableDeclaration */ && + declaration.parent.kind === 215 /* VariableDeclarationList */ && + declaration.parent.parent.kind === 196 /* VariableStatement */) { + // @type annotation might have been on the variable statement, try that instead. + var annotation = ts.getJSDocTypeTag(declaration.parent.parent); + if (annotation && annotation.typeExpression) { + return annotation.typeExpression.type; + } + } + else if (declaration.kind === 139 /* Parameter */) { + // If it's a parameter, see if the parent has a jsdoc comment with an @param + // annotation. + var paramTag = ts.getCorrespondingJSDocParameterTag(declaration); + if (paramTag && paramTag.typeExpression) { + return paramTag.typeExpression.type; + } + } + return undefined; + } // 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.parserContextFlags & 32 /* JavaScriptFile */) { + // If this is a variable in a JavaScript file, then use the JSDoc type (if it has + // one as its type), otherwise fallback to the below standard TS codepaths to + // try to figure it out. + var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); + if (type && type !== unknownType) { + return type; + } } - if (declaration.parent.parent.kind === 201 /* ForOfStatement */) { + // A variable declared in a for..in statement is always of type string + if (declaration.parent.parent.kind === 203 /* ForInStatement */) { + return stringType; + } + if (declaration.parent.parent.kind === 204 /* 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, @@ -15424,11 +17058,11 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 138 /* Parameter */) { + if (declaration.kind === 139 /* 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 (func.kind === 147 /* SetAccessor */ && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 146 /* GetAccessor */); if (getter) { return getReturnTypeOfSignature(getSignatureFromDeclaration(getter)); } @@ -15444,7 +17078,7 @@ var ts; return checkExpressionCached(declaration.initializer); } // If it is a short-hand property assignment, use the type of the identifier - if (declaration.kind === 246 /* ShorthandPropertyAssignment */) { + if (declaration.kind === 249 /* ShorthandPropertyAssignment */) { return checkIdentifier(declaration.name); } // If the declaration specifies a binding pattern, use the type implied by the binding pattern @@ -15469,10 +17103,17 @@ var ts; // Return the type implied by an object binding pattern function getTypeFromObjectBindingPattern(pattern, includePatternInType) { var members = {}; + var hasComputedProperties = false; 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); + if (isComputedNonLiteralName(name)) { + // do not include computed properties in the implied type + hasComputedProperties = true; + return; + } + var text = getTextOfPropertyName(name); + var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0); + var symbol = createSymbol(flags, text); symbol.type = getTypeFromBindingElement(e, includePatternInType); symbol.bindingElement = e; members[symbol.name] = symbol; @@ -15481,6 +17122,9 @@ var ts; if (includePatternInType) { result.pattern = pattern; } + if (hasComputedProperties) { + result.flags |= 67108864 /* ObjectLiteralPatternWithComputedProperties */; + } return result; } // Return the type implied by an array binding pattern @@ -15490,7 +17134,7 @@ var ts; 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); }); + var elementTypes = ts.map(elements, function (e) { return e.kind === 190 /* OmittedExpression */ ? anyType : getTypeFromBindingElement(e, includePatternInType); }); if (includePatternInType) { var result = createNewTupleType(elementTypes); result.pattern = pattern; @@ -15506,7 +17150,7 @@ var ts; // 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 */ + return pattern.kind === 164 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType) : getTypeFromArrayBindingPattern(pattern, includePatternInType); } @@ -15528,14 +17172,17 @@ var ts; // 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; + if (declaration.kind === 248 /* PropertyAssignment */) { + return type; + } + return getWidenedType(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))) { + if (!isPrivateWithinAmbient(root) && !(root.kind === 139 /* Parameter */ && isPrivateWithinAmbient(root.parent))) { reportImplicitAnyError(declaration, type); } } @@ -15550,13 +17197,25 @@ var ts; } // Handle catch clause variables var declaration = symbol.valueDeclaration; - if (declaration.parent.kind === 244 /* CatchClause */) { + if (declaration.parent.kind === 247 /* CatchClause */) { return links.type = anyType; } // Handle export default expressions - if (declaration.kind === 227 /* ExportAssignment */) { + if (declaration.kind === 230 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } + // Handle module.exports = expr + if (declaration.kind === 184 /* BinaryExpression */) { + return links.type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); + } + if (declaration.kind === 169 /* PropertyAccessExpression */) { + // Declarations only exist for property access expressions for certain + // special assignment kinds + if (declaration.parent.kind === 184 /* BinaryExpression */) { + // Handle exports.p = expr or this.p = expr or className.prototype.method = expr + return links.type = checkExpressionCached(declaration.parent.right); + } + } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return unknownType; @@ -15582,7 +17241,7 @@ var ts; } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 145 /* GetAccessor */) { + if (accessor.kind === 146 /* GetAccessor */) { return accessor.type && getTypeFromTypeNode(accessor.type); } else { @@ -15598,9 +17257,9 @@ var ts; if (!pushTypeResolution(symbol, 0 /* Type */)) { return unknownType; } - var getter = ts.getDeclarationOfKind(symbol, 145 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 146 /* SetAccessor */); - var type; + var getter = ts.getDeclarationOfKind(symbol, 146 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 147 /* SetAccessor */); + var type = void 0; // First try to see if the user specified a return type on the get-accessor. var getterReturnType = getAnnotatedAccessorType(getter); if (getterReturnType) { @@ -15628,7 +17287,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (compilerOptions.noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 145 /* GetAccessor */); + var getter_1 = ts.getDeclarationOfKind(symbol, 146 /* 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)); } } @@ -15707,8 +17366,8 @@ var ts; // 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]; + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); if (!typeParameters) { typeParameters = [tp]; @@ -15728,9 +17387,9 @@ var ts; 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 */) { + if (node.kind === 217 /* ClassDeclaration */ || node.kind === 189 /* ClassExpression */ || + node.kind === 216 /* FunctionDeclaration */ || node.kind === 176 /* FunctionExpression */ || + node.kind === 144 /* MethodDeclaration */ || node.kind === 177 /* ArrowFunction */) { var declarations = node.typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); @@ -15740,7 +17399,7 @@ var ts; } // 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 */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 218 /* InterfaceDeclaration */); return appendOuterTypeParameters(undefined, declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -15749,8 +17408,8 @@ var ts; 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 */) { + if (node.kind === 218 /* InterfaceDeclaration */ || node.kind === 217 /* ClassDeclaration */ || + node.kind === 189 /* ClassExpression */ || node.kind === 219 /* TypeAliasDeclaration */) { var declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); @@ -15777,8 +17436,8 @@ var ts; 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); }); + var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); + signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); } return signatures; } @@ -15814,9 +17473,6 @@ var ts; } 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 */; @@ -15835,23 +17491,25 @@ var ts; } function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - var baseContructorType = getBaseConstructorTypeOfClass(type); - if (!(baseContructorType.flags & 80896 /* ObjectType */)) { + var baseConstructorType = getBaseConstructorTypeOfClass(type); + if (!(baseConstructorType.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 + var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && + areAllOuterTypeParametersApplied(originalBaseType)) { + // When base constructor type is a class with no captured type arguments 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); + baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.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); + var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments); if (!constructors.length) { error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return; @@ -15876,11 +17534,22 @@ var ts; type.resolvedBaseTypes.push(baseType); } } + function areAllOuterTypeParametersApplied(type) { + // An unapplied type parameter has its symbol still the same as the matching argument symbol. + // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked. + var outerTypeParameters = type.outerTypeParameters; + if (outerTypeParameters) { + var last = outerTypeParameters.length - 1; + var typeArguments = type.typeArguments; + return outerTypeParameters[last].symbol !== typeArguments[last].symbol; + } + return true; + } 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)) { + if (declaration.kind === 218 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); @@ -15912,14 +17581,14 @@ var ts; 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 */) { + if (declaration.kind === 218 /* InterfaceDeclaration */) { + if (declaration.flags & 262144 /* ContainsThis */) { return false; } var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); if (baseTypeNodes) { - for (var _b = 0; _b < baseTypeNodes.length; _b++) { - var node = baseTypeNodes[_b]; + for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { + var node = baseTypeNodes_1[_b]; if (ts.isSupportedExpressionWithTypeArguments(node)) { var baseSymbol = resolveEntityName(node.expression, 793056 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { @@ -15955,7 +17624,7 @@ var ts; type.typeArguments = type.typeParameters; type.thisType = createType(512 /* TypeParameter */ | 33554432 /* ThisType */); type.thisType.symbol = symbol; - type.thisType.constraint = getTypeWithThisArgument(type); + type.thisType.constraint = type; } } return links.declaredType; @@ -15968,7 +17637,7 @@ var ts; if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return unknownType; } - var declaration = ts.getDeclarationOfKind(symbol, 216 /* TypeAliasDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 219 /* TypeAliasDeclaration */); var type = getTypeFromTypeNode(declaration.type); if (popTypeResolution()) { links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -16001,7 +17670,7 @@ var ts; if (!links.declaredType) { var type = createType(512 /* TypeParameter */); type.symbol = symbol; - if (!ts.getDeclarationOfKind(symbol, 137 /* TypeParameter */).constraint) { + if (!ts.getDeclarationOfKind(symbol, 138 /* TypeParameter */).constraint) { type.constraint = noConstraintType; } links.declaredType = type; @@ -16057,11 +17726,11 @@ var ts; case 120 /* BooleanKeyword */: case 131 /* SymbolKeyword */: case 103 /* VoidKeyword */: - case 9 /* StringLiteral */: + case 163 /* StringLiteralType */: return true; - case 156 /* ArrayType */: + case 157 /* ArrayType */: return isIndependentType(node.elementType); - case 151 /* TypeReference */: + case 152 /* TypeReference */: return isIndependentTypeReference(node); } return false; @@ -16074,7 +17743,7 @@ var ts; // 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))) { + if (node.kind !== 145 /* Constructor */ && (!node.type || !isIndependentType(node.type))) { return false; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { @@ -16095,12 +17764,12 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: return isIndependentVariableLikeDeclaration(declaration); - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 144 /* Constructor */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 145 /* Constructor */: return isIndependentFunctionLikeDeclaration(declaration); } } @@ -16109,8 +17778,8 @@ var ts; } function createSymbolTable(symbols) { var result = {}; - for (var _i = 0; _i < symbols.length; _i++) { - var symbol = symbols[_i]; + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; result[symbol.name] = symbol; } return result; @@ -16119,28 +17788,20 @@ var ts; // 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]; + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var symbol = symbols_2[_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]; + for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { + var s = baseSymbols_1[_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; @@ -16179,8 +17840,8 @@ var ts; members = createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); - for (var _i = 0; _i < baseTypes.length; _i++) { - var baseType = baseTypes[_i]; + for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { + var baseType = baseTypes_1[_i]; var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; addInheritedMembers(members, getPropertiesOfObjectType(instantiatedBaseType)); callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); @@ -16217,17 +17878,17 @@ var ts; 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 */); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasStringLiterals*/ false)]; + } 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]; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); @@ -16256,9 +17917,9 @@ var ts; 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)) { + for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { + var s = signatureList_1[_i]; + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreReturnTypes, compareTypesIdentical)) { return s; } } @@ -16321,8 +17982,8 @@ var ts; } function getUnionIndexType(types, kind) { var indexTypes = []; - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexType = getIndexTypeOfType(type, kind); if (!indexType) { return undefined; @@ -16361,36 +18022,29 @@ var ts; } 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); + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); + var callSignatures = instantiateList(getSignaturesOfType(type.target, 0 /* Call */), type.mapper, instantiateSignature); + var constructSignatures = instantiateList(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper, instantiateSignature); + var stringIndexType = instantiateType(getIndexTypeOfType(type.target, 0 /* String */), type.mapper); + var numberIndexType = instantiateType(getIndexTypeOfType(type.target, 1 /* Number */), type.mapper); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } 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 */); + var members = symbol.members; + var callSignatures = getSignaturesOfSymbol(members["__call"]); + var constructSignatures = getSignaturesOfSymbol(members["__new"]); + var stringIndexType = getIndexTypeOfSymbol(symbol, 0 /* String */); + var numberIndexType = getIndexTypeOfSymbol(symbol, 1 /* Number */); + setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } else { // Combinations of function, class, enum and module - members = emptySymbols; - callSignatures = emptyArray; - constructSignatures = emptyArray; + var members = emptySymbols; + var 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"]); @@ -16403,10 +18057,16 @@ var ts; addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); } } - stringIndexType = undefined; - numberIndexType = (symbol.flags & 384 /* Enum */) ? stringType : undefined; + var numberIndexType = (symbol.flags & 384 /* Enum */) ? stringType : undefined; + setObjectTypeMembers(type, members, emptyArray, constructSignatures, undefined, numberIndexType); + // We resolve the members before computing the signatures because a signature may use + // typeof with a qualified name expression that circularly references the type we are + // in the process of resolving (see issue #6072). The temporarily empty signature list + // will never be observed because a qualified name can't reference signatures. + if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + } } - setObjectTypeMembers(type, members, callSignatures, constructSignatures, stringIndexType, numberIndexType); } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -16431,15 +18091,15 @@ var ts; } return type; } - // Return properties of an object type or an empty array for other types + /** 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. + /** 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); @@ -16470,6 +18130,20 @@ var ts; type = getApparentType(type); return type.flags & 49152 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + /** + * The apparent type of a type parameter is the base constraint instantiated with the type parameter + * as the type argument for the 'this' type. + */ + function getApparentTypeOfTypeParameter(type) { + if (!type.resolvedApparentType) { + var constraintType = getConstraintOfTypeParameter(type); + while (constraintType && constraintType.flags & 512 /* TypeParameter */) { + constraintType = getConstraintOfTypeParameter(constraintType); + } + type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type); + } + return type.resolvedApparentType; + } /** * 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 @@ -16477,12 +18151,7 @@ var ts; */ function getApparentType(type) { if (type.flags & 512 /* TypeParameter */) { - do { - type = getConstraintOfTypeParameter(type); - } while (type && type.flags & 512 /* TypeParameter */); - if (!type) { - type = emptyObjectType; - } + type = getApparentTypeOfTypeParameter(type); } if (type.flags & 258 /* StringLike */) { type = globalStringType; @@ -16501,12 +18170,15 @@ var ts; function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + // Flags we want to propagate to the result if they exist in all source symbols + var commonFlags = (containingType.flags & 32768 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var current = types_2[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationFlagsFromSymbol(prop) & (32 /* Private */ | 64 /* Protected */))) { + if (prop && !(getDeclarationFlagsFromSymbol(prop) & (16 /* Private */ | 32 /* Protected */))) { + commonFlags &= prop.flags; if (!props) { props = [prop]; } @@ -16528,14 +18200,17 @@ var ts; } var propTypes = []; var declarations = []; - for (var _a = 0; _a < props.length; _a++) { - var prop = props[_a]; + for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { + var prop = props_1[_a]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } propTypes.push(getTypeOfSymbol(prop)); } - var result = createSymbol(4 /* Property */ | 67108864 /* Transient */ | 268435456 /* SyntheticProperty */, name); + var result = createSymbol(4 /* Property */ | + 67108864 /* Transient */ | + 268435456 /* SyntheticProperty */ | + commonFlags, name); result.containingType = containingType; result.declarations = declarations; result.type = containingType.flags & 16384 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); @@ -16592,22 +18267,6 @@ var ts; 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); @@ -16619,6 +18278,15 @@ var ts; function getIndexTypeOfType(type, kind) { return getIndexTypeOfStructuredType(getApparentType(type), kind); } + function getTypeParametersFromJSDocTemplate(declaration) { + if (declaration.parserContextFlags & 32 /* JavaScriptFile */) { + var templateTag = ts.getJSDocTemplateTag(declaration); + if (templateTag) { + return getTypeParametersFromDeclaration(templateTag.typeParameters); + } + } + return undefined; + } // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual // type checking functions). function getTypeParametersFromDeclaration(typeParameterDeclarations) { @@ -16641,33 +18309,77 @@ var ts; return result; } function isOptionalParameter(node) { + if (node.parserContextFlags & 32 /* JavaScriptFile */) { + if (node.type && node.type.kind === 263 /* JSDocOptionalType */) { + return true; + } + var paramTag = ts.getCorrespondingJSDocParameterTag(node); + if (paramTag) { + if (paramTag.isBracketed) { + return true; + } + if (paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 263 /* JSDocOptionalType */; + } + } + } if (ts.hasQuestionToken(node)) { return true; } if (node.initializer) { var signatureDeclaration = node.parent; var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = signatureDeclaration.parameters.indexOf(node); + var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } return false; } + function createTypePredicateFromTypePredicateNode(node) { + if (node.parameterName.kind === 69 /* Identifier */) { + var parameterName = node.parameterName; + return { + kind: 1 /* Identifier */, + parameterName: parameterName ? parameterName.text : undefined, + parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, + type: getTypeFromTypeNode(node.type) + }; + } + else { + return { + kind: 0 /* This */, + type: getTypeFromTypeNode(node.type) + }; + } + } function getSignatureFromDeclaration(declaration) { var links = getNodeLinks(declaration); if (!links.resolvedSignature) { - var classType = declaration.kind === 144 /* Constructor */ ? + var classType = declaration.kind === 145 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : - declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : undefined; + declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : + getTypeParametersFromJSDocTemplate(declaration); var parameters = []; var hasStringLiterals = false; var minArgumentCount = -1; - for (var i = 0, n = declaration.parameters.length; i < n; i++) { + var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var returnType = undefined; + var typePredicate = undefined; + // If this is a JSDoc construct signature, then skip the first parameter in the + // parameter list. The first parameter represents the return type of the construct + // signature. + for (var i = isJSConstructSignature ? 1 : 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 */) { + var paramSymbol = param.symbol; + // Include parameter symbol instead of property symbol in the signature + if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.name, 107455 /* Value */, undefined, undefined); + paramSymbol = resolvedSymbol; + } + parameters.push(paramSymbol); + if (param.type && param.type.kind === 163 /* StringLiteralType */) { hasStringLiterals = true; } if (param.initializer || param.questionToken || param.dotDotDotToken) { @@ -16683,27 +18395,30 @@ var ts; if (minArgumentCount < 0) { minArgumentCount = declaration.parameters.length; } - var returnType; - var typePredicate; - if (classType) { + if (isJSConstructSignature) { + minArgumentCount--; + returnType = getTypeFromTypeNode(declaration.parameters[0].type); + } + else 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) - }; + if (declaration.type.kind === 151 /* TypePredicate */) { + typePredicate = createTypePredicateFromTypePredicateNode(declaration.type); } } else { + if (declaration.parserContextFlags & 32 /* JavaScriptFile */) { + var type = getReturnTypeFromJSDocComment(declaration); + if (type && type !== unknownType) { + returnType = type; + } + } // 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 */); + if (declaration.kind === 146 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 147 /* SetAccessor */); returnType = getAnnotatedAccessorType(setter); } if (!returnType && ts.nodeIsMissing(declaration.body)) { @@ -16721,19 +18436,20 @@ var ts; 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 */: + case 153 /* FunctionType */: + case 154 /* ConstructorType */: + case 216 /* FunctionDeclaration */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 145 /* Constructor */: + case 148 /* CallSignature */: + case 149 /* ConstructSignature */: + case 150 /* IndexSignature */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 176 /* FunctionExpression */: + case 177 /* ArrowFunction */: + case 264 /* JSDocFunctionType */: // 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). @@ -16748,12 +18464,22 @@ var ts; } return result; } + function resolveExternalModuleTypeByLiteral(name) { + var moduleSym = resolveExternalModuleName(name, name); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + return getTypeOfSymbol(resolvedModuleSymbol); + } + } + return anyType; + } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { return unknownType; } - var type; + var type = void 0; if (signature.target) { type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); } @@ -16789,7 +18515,7 @@ var ts; return anyType; } function getSignatureInstantiation(signature, typeArguments) { - return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); + return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true); } function getErasedSignature(signature) { if (!signature.typeParameters) @@ -16799,7 +18525,7 @@ var ts; signature.erasedSignatureCache = instantiateSignature(getErasedSignature(signature.target), signature.mapper); } else { - signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); + signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); } } return signature.erasedSignatureCache; @@ -16810,7 +18536,7 @@ var ts; // 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 isConstructor = signature.declaration.kind === 145 /* Constructor */ || signature.declaration.kind === 149 /* ConstructSignature */; var type = createObjectType(65536 /* Anonymous */ | 262144 /* FromSignature */); type.members = emptySymbols; type.properties = emptyArray; @@ -16846,20 +18572,41 @@ var ts; ? 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; + function getConstraintDeclaration(type) { + return ts.getDeclarationOfKind(type.symbol, 138 /* TypeParameter */).constraint; + } + function hasConstraintReferenceTo(type, target) { + var checked; + while (type && !(type.flags & 33554432 /* ThisType */) && type.flags & 512 /* TypeParameter */ && !ts.contains(checked, type)) { + if (type === target) { + return true; + } + (checked || (checked = [])).push(type); + var constraintDeclaration = getConstraintDeclaration(type); + type = constraintDeclaration && getTypeFromTypeNode(constraintDeclaration); + } + return false; + } + function getConstraintOfTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; } else { - type.constraint = getTypeFromTypeNode(ts.getDeclarationOfKind(type.symbol, 137 /* TypeParameter */).constraint); + var constraintDeclaration = getConstraintDeclaration(typeParameter); + var constraint = getTypeFromTypeNode(constraintDeclaration); + if (hasConstraintReferenceTo(constraint, typeParameter)) { + error(constraintDeclaration, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + constraint = unknownType; + } + typeParameter.constraint = constraint; } } - return type.constraint === noConstraintType ? undefined : type.constraint; + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 137 /* TypeParameter */).parent); + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 138 /* TypeParameter */).parent); } function getTypeListId(types) { if (types) { @@ -16887,8 +18634,8 @@ var ts; // 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]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var type = types_3[_i]; result |= type.flags; } return result & 14680064 /* PropagatingFlags */; @@ -16904,50 +18651,6 @@ var ts; } 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); @@ -16992,31 +18695,74 @@ var ts; } // 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 getTypeReferenceName(node) { + switch (node.kind) { + case 152 /* TypeReference */: + return node.typeName; + case 262 /* JSDocTypeReference */: + return node.name; + case 191 /* ExpressionWithTypeArguments */: + // We only support expressions that are simple qualified names. For other + // expressions this produces undefined. + if (ts.isSupportedExpressionWithTypeArguments(node)) { + return node.expression; + } + } + return undefined; + } + function resolveTypeReferenceName(node, typeReferenceName) { + if (!typeReferenceName) { + return unknownSymbol; + } + return resolveEntityName(typeReferenceName, 793056 /* Type */) || unknownSymbol; + } + function getTypeReferenceType(node, symbol) { + if (symbol === unknownSymbol) { + return unknownType; + } + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + return getTypeFromClassOrInterfaceReference(node, symbol); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getTypeFromTypeAliasReference(node, symbol); + } + if (symbol.flags & 107455 /* Value */ && node.kind === 262 /* JSDocTypeReference */) { + // A JSDocTypeReference may have resolved to a value (as opposed to a type). In + // that case, the type of this reference is just the type of the value we resolved + // to. + return getTypeOfSymbol(symbol); + } + return getTypeFromNonGenericTypeReference(node, 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); + var symbol = void 0; + var type = void 0; + if (node.kind === 262 /* JSDocTypeReference */) { + var typeReferenceName = getTypeReferenceName(node); + symbol = resolveTypeReferenceName(node, typeReferenceName); + type = getTypeReferenceType(node, symbol); + links.resolvedSymbol = symbol; + links.resolvedType = type; + } + else { + // We only support expressions that are simple qualified names. For other expressions this produces undefined. + var typeNameOrExpression = node.kind === 152 /* TypeReference */ ? node.typeName : + ts.isSupportedExpressionWithTypeArguments(node) ? node.expression : + undefined; + symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793056 /* Type */) || unknownSymbol; + 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; @@ -17038,12 +18784,12 @@ var ts; function getTypeOfGlobalSymbol(symbol, arity) { function getTypeDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; switch (declaration.kind) { - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 217 /* EnumDeclaration */: + case 217 /* ClassDeclaration */: + case 218 /* InterfaceDeclaration */: + case 220 /* EnumDeclaration */: return declaration; } } @@ -17075,10 +18821,6 @@ var ts; 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 @@ -17149,8 +18891,8 @@ var ts; // 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]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; addTypeToSet(typeSet, type, typeSetKind); } } @@ -17172,8 +18914,8 @@ var ts; } } function containsTypeAny(types) { - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; if (isTypeAny(type)) { return true; } @@ -17198,7 +18940,7 @@ var ts; // a named type that circularly references itself. function getUnionType(types, noSubtypeReduction) { if (types.length === 0) { - return emptyObjectType; + return emptyUnionType; } var typeSet = []; addTypesToSet(typeSet, types, 16384 /* Union */); @@ -17270,27 +19012,43 @@ var ts; } return links.resolvedType; } - function getStringLiteralType(node) { - if (ts.hasProperty(stringLiteralTypes, node.text)) { - return stringLiteralTypes[node.text]; + function getStringLiteralTypeForText(text) { + if (ts.hasProperty(stringLiteralTypes, text)) { + return stringLiteralTypes[text]; } - var type = stringLiteralTypes[node.text] = createType(256 /* StringLiteral */); - type.text = ts.getTextOfNode(node); + var type = stringLiteralTypes[text] = createType(256 /* StringLiteral */); + type.text = text; return type; } - function getTypeFromStringLiteral(node) { + function getTypeFromStringLiteralTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getStringLiteralTypeForText(node.text); + } + return links.resolvedType; + } + function getTypeFromJSDocVariadicType(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getStringLiteralType(node); + var type = getTypeFromTypeNode(node.type); + links.resolvedType = type ? createArrayType(type) : unknownType; + } + return links.resolvedType; + } + function getTypeFromJSDocTupleType(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var types = ts.map(node.types, getTypeFromTypeNode); + links.resolvedType = createTupleType(types); } 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))) { + if (parent && (ts.isClassLike(parent) || parent.kind === 218 /* InterfaceDeclaration */)) { + if (!(container.flags & 64 /* Static */) && + (container.kind !== 145 /* Constructor */ || ts.isNodeDescendentOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -17307,6 +19065,8 @@ var ts; function getTypeFromTypeNode(node) { switch (node.kind) { case 117 /* AnyKeyword */: + case 253 /* JSDocAllType */: + case 254 /* JSDocUnknownType */: return anyType; case 130 /* StringKeyword */: return stringType; @@ -17318,38 +19078,52 @@ var ts; return esSymbolType; case 103 /* VoidKeyword */: return voidType; - case 97 /* ThisKeyword */: + case 162 /* ThisType */: return getTypeFromThisTypeNode(node); - case 9 /* StringLiteral */: - return getTypeFromStringLiteral(node); - case 151 /* TypeReference */: + case 163 /* StringLiteralType */: + return getTypeFromStringLiteralTypeNode(node); + case 152 /* TypeReference */: + case 262 /* JSDocTypeReference */: return getTypeFromTypeReference(node); - case 150 /* TypePredicate */: + case 151 /* TypePredicate */: return booleanType; - case 188 /* ExpressionWithTypeArguments */: + case 191 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 154 /* TypeQuery */: + case 155 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 156 /* ArrayType */: + case 157 /* ArrayType */: + case 255 /* JSDocArrayType */: return getTypeFromArrayTypeNode(node); - case 157 /* TupleType */: + case 158 /* TupleType */: return getTypeFromTupleTypeNode(node); - case 158 /* UnionType */: + case 159 /* UnionType */: + case 256 /* JSDocUnionType */: return getTypeFromUnionTypeNode(node); - case 159 /* IntersectionType */: + case 160 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 160 /* ParenthesizedType */: + case 161 /* ParenthesizedType */: + case 258 /* JSDocNullableType */: + case 259 /* JSDocNonNullableType */: + case 266 /* JSDocConstructorType */: + case 267 /* JSDocThisType */: + case 263 /* JSDocOptionalType */: return getTypeFromTypeNode(node.type); - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - case 155 /* TypeLiteral */: + case 153 /* FunctionType */: + case 154 /* ConstructorType */: + case 156 /* TypeLiteral */: + case 264 /* JSDocFunctionType */: + case 260 /* JSDocRecordType */: 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 */: + case 136 /* QualifiedName */: var symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); + case 257 /* JSDocTupleType */: + return getTypeFromJSDocTupleType(node); + case 265 /* JSDocVariadicType */: + return getTypeFromJSDocVariadicType(node); default: return unknownType; } @@ -17357,8 +19131,8 @@ var ts; function instantiateList(items, mapper, instantiator) { if (items && items.length) { var result = []; - for (var _i = 0; _i < items.length; _i++) { - var v = items[_i]; + for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { + var v = items_1[_i]; result.push(instantiator(v, mapper)); } return result; @@ -17397,8 +19171,8 @@ var ts; case 2: return createBinaryTypeEraser(sources[0], sources[1]); } return function (t) { - for (var _i = 0; _i < sources.length; _i++) { - var source = sources[_i]; + for (var _i = 0, sources_1 = sources; _i < sources_1.length; _i++) { + var source = sources_1[_i]; if (t === source) { return anyType; } @@ -17406,18 +19180,22 @@ var ts; 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); + function getInferenceMapper(context) { + if (!context.mapper) { + var mapper = function (t) { + var typeParameters = context.typeParameters; + for (var i = 0; i < typeParameters.length; i++) { + if (t === typeParameters[i]) { + context.inferences[i].isFixed = true; + return getInferredType(context, i); + } } - } - return t; - }; - mapper.context = context; - return mapper; + return t; + }; + mapper.context = context; + context.mapper = mapper; + } + return context.mapper; } function identityMapper(type) { return type; @@ -17425,31 +19203,44 @@ var ts; function combineTypeMappers(mapper1, mapper2) { return function (t) { return instantiateType(mapper1(t), mapper2); }; } - function instantiateTypeParameter(typeParameter, mapper) { + function cloneTypeParameter(typeParameter) { var result = createType(512 /* TypeParameter */); result.symbol = typeParameter.symbol; - if (typeParameter.constraint) { - result.constraint = instantiateType(typeParameter.constraint, mapper); + result.target = typeParameter; + return result; + } + function cloneTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1 /* Identifier */, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; } else { - result.target = typeParameter; - result.mapper = mapper; + return { + kind: 0 /* This */, + type: instantiateType(predicate.type, mapper) + }; } - return result; } function instantiateSignature(signature, mapper, eraseTypeParameters) { var freshTypeParameters; var freshTypePredicate; if (signature.typeParameters && !eraseTypeParameters) { - freshTypeParameters = instantiateList(signature.typeParameters, mapper, instantiateTypeParameter); + // First create a fresh set of type parameters, then include a mapping from the old to the + // new type parameters in the mapper function. Finally store this mapper in the new type + // parameters such that we can use it when instantiating constraints. + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } } if (signature.typePredicate) { - freshTypePredicate = { - parameterName: signature.typePredicate.parameterName, - parameterIndex: signature.typePredicate.parameterIndex, - type: instantiateType(signature.typePredicate.type, mapper) - }; + freshTypePredicate = cloneTypePredicate(signature.typePredicate, 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; @@ -17521,27 +19312,27 @@ var ts; // 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)); + ts.Debug.assert(node.kind !== 144 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 176 /* FunctionExpression */: + case 177 /* ArrowFunction */: return isContextSensitiveFunctionLikeDeclaration(node); - case 165 /* ObjectLiteralExpression */: + case 168 /* ObjectLiteralExpression */: return ts.forEach(node.properties, isContextSensitive); - case 164 /* ArrayLiteralExpression */: + case 167 /* ArrayLiteralExpression */: return ts.forEach(node.elements, isContextSensitive); - case 182 /* ConditionalExpression */: + case 185 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 181 /* BinaryExpression */: + case 184 /* BinaryExpression */: return node.operatorToken.kind === 52 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 245 /* PropertyAssignment */: + case 248 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: return isContextSensitiveFunctionLikeDeclaration(node); - case 172 /* ParenthesizedExpression */: + case 175 /* ParenthesizedExpression */: return isContextSensitive(node.expression); } return false; @@ -17567,9 +19358,12 @@ var ts; function isTypeIdenticalTo(source, target) { return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined); } - function compareTypes(source, target) { + function compareTypesIdentical(source, target) { return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined) ? -1 /* True */ : 0 /* False */; } + function compareTypesAssignable(source, target) { + return checkTypeRelatedTo(source, target, assignableRelation, /*errorNode*/ undefined) ? -1 /* True */ : 0 /* False */; + } function isTypeSubtypeOf(source, target) { return checkTypeSubtypeOf(source, target, /*errorNode*/ undefined); } @@ -17582,10 +19376,127 @@ var ts; 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); + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + return compareSignaturesRelated(source, target, ignoreReturnTypes, /*reportErrors*/ false, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesRelated(source, target, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return -1 /* True */; + } + if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + 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 result = -1 /* True */; + var sourceMax = getNumNonRestParameters(source); + var targetMax = getNumNonRestParameters(target); + var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); + var sourceParams = source.parameters; + var targetParams = target.parameters; + for (var i = 0; i < checkCount; i++) { + var s = i < sourceMax ? getTypeOfSymbol(sourceParams[i]) : getRestTypeOfSignature(source); + var t = i < targetMax ? getTypeOfSymbol(targetParams[i]) : getRestTypeOfSignature(target); + var related = compareTypes(t, s, /*reportErrors*/ false) || compareTypes(s, t, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, sourceParams[i < sourceMax ? i : sourceMax].name, targetParams[i < targetMax ? i : targetMax].name); + } + return 0 /* False */; + } + result &= related; + } + if (!ignoreReturnTypes) { + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = getReturnTypeOfSignature(source); + // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions + if (target.typePredicate) { + if (source.typePredicate) { + result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); + } + else if (ts.isIdentifierTypePredicate(target.typePredicate)) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); + } + return 0 /* False */; + } + } + else { + result &= compareTypes(sourceReturnType, targetReturnType, reportErrors); + } + } + return result; + } + function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { + if (source.kind !== target.kind) { + if (reportErrors) { + errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + if (source.kind === 1 /* Identifier */) { + var sourceIdentifierPredicate = source; + var targetIdentifierPredicate = target; + if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + } + var related = compareTypes(source.type, target.type, reportErrors); + if (related === 0 /* False */ && reportErrors) { + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return related; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + // First see if the return types are compatible in either direction. + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || checkTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation, /*errorNode*/ undefined) + || checkTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation, /*errorNode*/ undefined)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); + } + return false; + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? + numParams - 1 : + numParams; + } + function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { + if (source.hasRestParameter === target.hasRestParameter) { + if (source.hasRestParameter) { + // If both have rest parameters, get the max and add 1 to + // compensate for the rest parameter. + return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; + } + else { + return Math.min(sourceNonRestParamCount, targetNonRestParamCount); + } + } + else { + // Return the count for whichever signature doesn't have rest parameters. + return source.hasRestParameter ? + targetNonRestParamCount : + sourceNonRestParamCount; + } } /** * Checks if 'source' is related to 'target' (e.g.: is a assignable to). @@ -17605,22 +19516,12 @@ var ts; 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); + var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, 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); } @@ -17628,6 +19529,7 @@ var ts; } return result !== 0 /* False */; function reportError(message, arg0, arg1, arg2) { + ts.Debug.assert(!!errorNode); errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); } function reportRelationError(message, source, target) { @@ -17659,6 +19561,11 @@ var ts; return -1 /* True */; if (source.flags & 128 /* Enum */ && target === numberType) return -1 /* True */; + if (source.flags & 128 /* Enum */ && target.flags & 128 /* Enum */) { + if (result = enumRelatedTo(source, target)) { + return result; + } + } if (source.flags & 256 /* StringLiteral */ && target === stringType) return -1 /* True */; if (relation === assignableRelation) { @@ -17667,6 +19574,9 @@ var ts; if (source === numberType && target.flags & 128 /* Enum */) return -1 /* True */; } + if (source.flags & 8 /* Boolean */ && target.flags & 8 /* Boolean */) { + return -1 /* True */; + } if (source.flags & 1048576 /* FreshObjectLiteral */) { if (hasExcessProperties(source, target, reportErrors)) { if (reportErrors) { @@ -17731,14 +19641,14 @@ var ts; } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var apparentType = getApparentType(source); + var apparentSource = 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 */) { + if (apparentSource.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)) { + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !(source.flags & 16777726 /* Primitive */); + if (result = objectTypeRelatedTo(apparentSource, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; return result; } @@ -17758,10 +19668,7 @@ var ts; return result; } } - return objectTypeRelatedTo(source, target, /*reportErrors*/ false); - } - if (source.flags & 512 /* TypeParameter */ && target.flags & 512 /* TypeParameter */) { - return typeParameterIdenticalTo(source, target); + return objectTypeRelatedTo(source, source, target, /*reportErrors*/ false); } if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { @@ -17784,40 +19691,42 @@ var ts; resolved.stringIndexType || resolved.numberIndexType || getPropertyOfType(type, name)) { return true; } - return false; } - if (type.flags & 49152 /* UnionOrIntersection */) { + else 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; + return false; } 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)); + if (!(target.flags & 67108864 /* ObjectLiteralPatternWithComputedProperties */) && someConstituentTypeHasKind(target, 80896 /* ObjectType */)) { + 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. + ts.Debug.assert(!!errorNode); + 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; } - return true; } } + return false; } 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); + for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { + var sourceType = sourceTypes_1[_i]; + var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false); if (!related) { return 0 /* False */; } @@ -17838,8 +19747,8 @@ var ts; 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]; + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var targetType = targetTypes_1[_i]; var related = isRelatedTo(source, targetType, reportErrors); if (!related) { return 0 /* False */; @@ -17861,8 +19770,8 @@ var ts; 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]; + for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { + var sourceType = sourceTypes_2[_i]; var related = isRelatedTo(sourceType, target, reportErrors); if (!related) { return 0 /* False */; @@ -17877,8 +19786,9 @@ var ts; if (sources.length !== targets.length && relation === identityRelation) { return 0 /* False */; } + var length = sources.length <= targets.length ? sources.length : targets.length; var result = -1 /* True */; - for (var i = 0; i < targets.length; i++) { + for (var i = 0; i < length; i++) { var related = isRelatedTo(sources[i], targets[i], reportErrors); if (!related) { return 0 /* False */; @@ -17887,34 +19797,24 @@ var ts; } 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) { + function objectTypeRelatedTo(source, originalSource, 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 */)) { + if (reportErrors && related === 2 /* Failed */) { + // We are elaborating errors and the cached result is an unreported failure. Record the result as a reported + // failure and continue computing the relation such that errors get reported. + relation[id] = 3 /* FailedAndReported */; + } + else { return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; } } @@ -17957,9 +19857,9 @@ var ts; if (result) { result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportErrors); if (result) { - result &= stringIndexTypesRelatedTo(source, target, reportErrors); + result &= stringIndexTypesRelatedTo(source, originalSource, target, reportErrors); if (result) { - result &= numberIndexTypesRelatedTo(source, target, reportErrors); + result &= numberIndexTypesRelatedTo(source, originalSource, target, reportErrors); } } } @@ -17987,8 +19887,8 @@ var ts; 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]; + for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { + var targetProp = properties_1[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { @@ -18002,23 +19902,23 @@ var ts; else if (!(targetProp.flags & 134217728 /* Prototype */)) { var sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); var targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); - if (sourcePropFlags & 32 /* Private */ || targetPropFlags & 32 /* Private */) { + if (sourcePropFlags & 16 /* Private */ || targetPropFlags & 16 /* Private */) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { - if (sourcePropFlags & 32 /* Private */ && targetPropFlags & 32 /* Private */) { + if (sourcePropFlags & 16 /* Private */ && targetPropFlags & 16 /* 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)); + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 16 /* Private */ ? source : target), typeToString(sourcePropFlags & 16 /* Private */ ? target : source)); } } return 0 /* False */; } } - else if (targetPropFlags & 64 /* Protected */) { + else if (targetPropFlags & 32 /* Protected */) { var sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & 32 /* Class */; - var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(sourceProp.parent) : undefined; - var targetClass = getDeclaredTypeOfSymbol(targetProp.parent); + var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(getParentOfSymbol(sourceProp)) : undefined; + var targetClass = getDeclaredTypeOfSymbol(getParentOfSymbol(targetProp)); 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)); @@ -18026,7 +19926,7 @@ var ts; return 0 /* False */; } } - else if (sourcePropFlags & 64 /* Protected */) { + else if (sourcePropFlags & 32 /* Protected */) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } @@ -18068,8 +19968,8 @@ var ts; return 0 /* False */; } var result = -1 /* True */; - for (var _i = 0; _i < sourceProperties.length; _i++) { - var sourceProp = sourceProperties[_i]; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.name); if (!targetProp) { return 0 /* False */; @@ -18091,154 +19991,51 @@ var ts; } 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; + if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length && + isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + // An abstract constructor type is not assignable to a non-abstract constructor type + // as it would otherwise be possible to new an abstract class. Note that the assignablity + // check we perform for an extends clause excludes construct signatures from the target, + // so this check never proceeds. + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); } + return 0 /* False */; } - outer: for (var _i = 0; _i < targetSignatures.length; _i++) { - var t = targetSignatures[_i]; + var result = -1 /* True */; + var saveErrorInfo = errorInfo; + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_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]; + // Only elaborate errors from the first failure + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; if (!s.hasStringLiterals || source.flags & 262144 /* FromSignature */) { - var related = signatureRelatedTo(s, t, localErrors); + var related = signatureRelatedTo(s, t, shouldElaborateErrors); if (related) { result &= related; errorInfo = saveErrorInfo; continue outer; } - // Only report errors from the first failure - localErrors = false; + shouldElaborateErrors = false; } } + // don't elaborate the primitive apparent types (like Number) + // because the actual primitives will have already been reported. + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } 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 */; - } } + /** + * See signatureAssignableTo, compareSignaturesIdentical + */ 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); + return compareSignaturesRelated(source, target, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -18247,8 +20044,8 @@ var ts; 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); + for (var i = 0, len = sourceSignatures.length; i < len; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); if (!related) { return 0 /* False */; } @@ -18256,12 +20053,17 @@ var ts; } return result; } - function stringIndexTypesRelatedTo(source, target, reportErrors) { + function stringIndexTypesRelatedTo(source, originalSource, target, reportErrors) { if (relation === identityRelation) { return indexTypesIdenticalTo(0 /* String */, source, target); } var targetType = getIndexTypeOfType(target, 0 /* String */); - if (targetType && !(targetType.flags & 1 /* Any */)) { + if (targetType) { + if ((targetType.flags & 1 /* Any */) && !(originalSource.flags & 16777726 /* Primitive */)) { + // non-primitive assignment to any is always allowed, eg + // `var x: { [index: string]: any } = { property: 12 };` + return -1 /* True */; + } var sourceType = getIndexTypeOfType(source, 0 /* String */); if (!sourceType) { if (reportErrors) { @@ -18280,12 +20082,17 @@ var ts; } return -1 /* True */; } - function numberIndexTypesRelatedTo(source, target, reportErrors) { + function numberIndexTypesRelatedTo(source, originalSource, target, reportErrors) { if (relation === identityRelation) { return indexTypesIdenticalTo(1 /* Number */, source, target); } var targetType = getIndexTypeOfType(target, 1 /* Number */); - if (targetType && !(targetType.flags & 1 /* Any */)) { + if (targetType) { + if ((targetType.flags & 1 /* Any */) && !(originalSource.flags & 16777726 /* Primitive */)) { + // non-primitive assignment to any is always allowed, eg + // `var x: { [index: number]: any } = { property: 12 };` + return -1 /* True */; + } var sourceStringType = getIndexTypeOfType(source, 0 /* String */); var sourceNumberType = getIndexTypeOfType(source, 1 /* Number */); if (!(sourceStringType || sourceNumberType)) { @@ -18294,10 +20101,10 @@ var ts; } return 0 /* False */; } - var related; + var related = void 0; 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); + related = isRelatedTo(sourceStringType, targetType, /*reportErrors*/ false) || isRelatedTo(sourceNumberType, targetType, reportErrors); } else { related = isRelatedTo(sourceStringType || sourceNumberType, targetType, reportErrors); @@ -18323,6 +20130,38 @@ var ts; } return 0 /* False */; } + function enumRelatedTo(source, target) { + if (source.symbol.name !== target.symbol.name || + source.symbol.flags & 128 /* ConstEnum */ || + target.symbol.flags & 128 /* ConstEnum */) { + return 0 /* False */; + } + var targetEnumType = getTypeOfSymbol(target.symbol); + for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(source.symbol)); _i < _a.length; _i++) { + var property = _a[_i]; + if (property.flags & 8 /* EnumMember */) { + var targetProperty = getPropertyOfType(targetEnumType, property.name); + if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, property.name, typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); + return 0 /* False */; + } + } + } + return -1 /* True */; + } + } + // Return true if the given type is the constructor type for an abstract class + function isAbstractConstructorType(type) { + if (type.flags & 65536 /* Anonymous */) { + var symbol = type.symbol; + if (symbol && symbol.flags & 32 /* Class */) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + if (declaration && declaration.flags & 128 /* Abstract */) { + return true; + } + } + } + return 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, @@ -18346,7 +20185,7 @@ var ts; return false; } function isPropertyIdenticalTo(sourceProp, targetProp) { - return compareProperties(sourceProp, targetProp, compareTypes) !== 0 /* False */; + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; } function compareProperties(sourceProp, targetProp, compareTypes) { // Two members are considered identical when @@ -18355,8 +20194,8 @@ var ts; if (sourceProp === targetProp) { return -1 /* True */; } - var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (32 /* Private */ | 64 /* Protected */); - var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (32 /* Private */ | 64 /* Protected */); + var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (16 /* Private */ | 32 /* Protected */); + var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (16 /* Private */ | 32 /* Protected */); if (sourcePropAccessibility !== targetPropAccessibility) { return 0 /* False */; } @@ -18372,39 +20211,47 @@ var ts; } return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } - function compareSignatures(source, target, partialMatch, ignoreReturnTypes, compareTypes) { + function isMatchingSignature(source, target, partialMatch) { + // A source signature matches a target signature if the two signatures have the same number of required, + // optional, and rest parameters. + if (source.parameters.length === target.parameters.length && + source.minArgumentCount === target.minArgumentCount && + source.hasRestParameter === target.hasRestParameter) { + return true; + } + // A source signature partially matches a target signature if the target signature has no fewer required + // parameters and no more overall parameters than the source signature (where a signature with a rest + // parameter is always considered to have more overall parameters than one without). + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (source.hasRestParameter && !target.hasRestParameter || + source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) { + return true; + } + return false; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesIdentical(source, target, partialMatch, ignoreReturnTypes, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. 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; - } + if (!(isMatchingSignature(source, target, partialMatch))) { + return 0 /* False */; } - else if (source.typeParameters || target.typeParameters) { + // Check that the two signatures have the same number of type parameters. We might consider + // also checking that any type parameter constraints match, but that would require instantiating + // the constraints with a common set of type arguments to get relatable entities in places where + // type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile, + // particularly as we're comparing erased versions of the signatures below. + if ((source.typeParameters ? source.typeParameters.length : 0) !== (target.typeParameters ? target.typeParameters.length : 0)) { 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 result = -1 /* True */; var targetLen = target.parameters.length; for (var i = 0; i < targetLen; i++) { var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]); @@ -18424,8 +20271,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; if (candidate !== type && !isTypeSubtypeOf(type, candidate)) return false; } @@ -18477,6 +20324,9 @@ var ts; function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } + function isStringLiteralType(type) { + return type.flags & 256 /* StringLiteral */; + } /** * Check if a Type was written as a tuple type literal. * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. @@ -18598,22 +20448,22 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 138 /* Parameter */: + case 139 /* 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 */: + case 216 /* FunctionDeclaration */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 176 /* FunctionExpression */: + case 177 /* ArrowFunction */: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; @@ -18660,13 +20510,7 @@ var ts; } } 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 - }); - } + var inferences = ts.map(typeParameters, createTypeInferencesObject); return { typeParameters: typeParameters, inferUnionTypes: inferUnionTypes, @@ -18674,6 +20518,13 @@ var ts; inferredTypes: new Array(typeParameters.length) }; } + function createTypeInferencesObject() { + return { + primary: undefined, + secondary: undefined, + isFixed: false + }; + } function inferTypes(context, source, target) { var sourceStack; var targetStack; @@ -18689,6 +20540,29 @@ var ts; return false; } function inferFromTypes(source, target) { + if (source.flags & 16384 /* Union */ && target.flags & 16384 /* Union */ || + source.flags & 32768 /* Intersection */ && target.flags & 32768 /* Intersection */) { + // Source and target are both unions or both intersections. First, find each + // target constituent type that has an identically matching source constituent + // type, and for each such target constituent type infer from the type to itself. + // When inferring from a type to itself we effectively find all type parameter + // occurrences within that type and infer themselves as their type arguments. + var matchingTypes = void 0; + for (var _i = 0, _a = target.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (typeIdenticalToSomeType(t, source.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + } + // Next, to improve the quality of inferences, reduce the source and target types by + // removing the identically matched constituents. For example, when inferring from + // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'. + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } 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). @@ -18741,10 +20615,10 @@ var ts; else if (target.flags & 49152 /* UnionOrIntersection */) { var targetTypes = target.types; var typeParameterCount = 0; - var typeParameter; + var typeParameter = void 0; // 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]; + for (var _b = 0, targetTypes_2 = targetTypes; _b < targetTypes_2.length; _b++) { + var t = targetTypes_2[_b]; if (t.flags & 512 /* TypeParameter */ && ts.contains(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; @@ -18766,8 +20640,8 @@ var ts; 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]; + for (var _c = 0, sourceTypes_3 = sourceTypes; _c < sourceTypes_3.length; _c++) { + var sourceType = sourceTypes_3[_c]; inferFromTypes(sourceType, target); } } @@ -18803,8 +20677,8 @@ var ts; } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0; _i < properties.length; _i++) { - var targetProp = properties[_i]; + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var targetProp = properties_2[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.name); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -18823,13 +20697,8 @@ var ts; } 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); - } + if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { + inferFromTypes(source.typePredicate.type, target.typePredicate.type); } else { inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); @@ -18845,6 +20714,29 @@ var ts; } } } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var t = types_7[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + /** + * Return a new union or intersection type computed by removing a given set of types + * from a given union or intersection type. + */ + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & 16384 /* Union */ ? getUnionType(reducedTypes, /*noSubtypeReduction*/ true) : getIntersectionType(reducedTypes); + } function getInferenceCandidates(context, index) { var inferences = context.inferences[index]; return inferences.primary || inferences.secondary || emptyArray; @@ -18868,10 +20760,16 @@ var ts; inferredType = emptyObjectType; inferenceSucceeded = true; } + context.inferredTypes[index] = inferredType; // 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; + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + context.inferredTypes[index] = inferredType = instantiatedConstraint; + } + } } 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). @@ -18879,7 +20777,6 @@ var ts; // 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; } @@ -18889,9 +20786,6 @@ var ts; } return context.inferredTypes; } - function hasAncestor(node, kind) { - return ts.getAncestor(node, kind) !== undefined; - } // EXPRESSION TYPE CHECKING function getResolvedSymbol(node) { var links = getNodeLinks(node); @@ -18906,10 +20800,10 @@ var ts; // The expression is restricted to a single identifier or a sequence of identifiers separated by periods while (node) { switch (node.kind) { - case 154 /* TypeQuery */: + case 155 /* TypeQuery */: return true; case 69 /* Identifier */: - case 135 /* QualifiedName */: + case 136 /* QualifiedName */: node = node.parent; continue; default: @@ -18918,26 +20812,6 @@ var ts; } 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)); } @@ -18956,10 +20830,7 @@ var ts; 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; - } + var n = skipParenthesizedNodes(node.left); if (n.kind === 69 /* Identifier */ && getResolvedSymbol(n) === symbol) { return true; } @@ -18974,55 +20845,55 @@ var ts; } function isAssignedIn(node) { switch (node.kind) { - case 181 /* BinaryExpression */: + case 184 /* BinaryExpression */: return isAssignedInBinaryExpression(node); - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 214 /* VariableDeclaration */: + case 166 /* 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 */: + case 164 /* ObjectBindingPattern */: + case 165 /* ArrayBindingPattern */: + case 167 /* ArrayLiteralExpression */: + case 168 /* ObjectLiteralExpression */: + case 169 /* PropertyAccessExpression */: + case 170 /* ElementAccessExpression */: + case 171 /* CallExpression */: + case 172 /* NewExpression */: + case 174 /* TypeAssertionExpression */: + case 192 /* AsExpression */: + case 175 /* ParenthesizedExpression */: + case 182 /* PrefixUnaryExpression */: + case 178 /* DeleteExpression */: + case 181 /* AwaitExpression */: + case 179 /* TypeOfExpression */: + case 180 /* VoidExpression */: + case 183 /* PostfixUnaryExpression */: + case 187 /* YieldExpression */: + case 185 /* ConditionalExpression */: + case 188 /* SpreadElementExpression */: + case 195 /* Block */: + case 196 /* VariableStatement */: + case 198 /* ExpressionStatement */: + case 199 /* IfStatement */: + case 200 /* DoStatement */: + case 201 /* WhileStatement */: + case 202 /* ForStatement */: + case 203 /* ForInStatement */: + case 204 /* ForOfStatement */: + case 207 /* ReturnStatement */: + case 208 /* WithStatement */: + case 209 /* SwitchStatement */: + case 244 /* CaseClause */: + case 245 /* DefaultClause */: + case 210 /* LabeledStatement */: + case 211 /* ThrowStatement */: + case 212 /* TryStatement */: + case 247 /* CatchClause */: + case 236 /* JsxElement */: + case 237 /* JsxSelfClosingElement */: + case 241 /* JsxAttribute */: + case 242 /* JsxSpreadAttribute */: + case 238 /* JsxOpeningElement */: + case 243 /* JsxExpression */: return ts.forEachChild(node, isAssignedIn); } return false; @@ -19034,59 +20905,73 @@ var ts; // 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 */)) { + var declaration = ts.getDeclarationOfKind(symbol, 214 /* VariableDeclaration */); + var top_1 = declaration && getDeclarationContainer(declaration); + var originalType = type; + var nodeStack = []; loop: while (node.parent) { var child = node; node = node.parent; - var narrowedType = type; switch (node.kind) { - case 196 /* IfStatement */: + case 199 /* IfStatement */: + case 185 /* ConditionalExpression */: + case 184 /* BinaryExpression */: + nodeStack.push({ node: node, child: child }); + break; + case 251 /* SourceFile */: + case 221 /* ModuleDeclaration */: + // Stop at the first containing file or module declaration + break loop; + } + if (node === top_1) { + break; + } + } + var nodes = void 0; + while (nodes = nodeStack.pop()) { + var node_1 = nodes.node, child = nodes.child; + switch (node_1.kind) { + case 199 /* 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); + if (child !== node_1.expression) { + type = narrowType(type, node_1.expression, /*assumeTrue*/ child === node_1.thenStatement); } break; - case 182 /* ConditionalExpression */: + case 185 /* 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); + if (child !== node_1.condition) { + type = narrowType(type, node_1.condition, /*assumeTrue*/ child === node_1.whenTrue); } break; - case 181 /* BinaryExpression */: + case 184 /* 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); + if (child === node_1.right) { + if (node_1.operatorToken.kind === 51 /* AmpersandAmpersandToken */) { + type = narrowType(type, node_1.left, /*assumeTrue*/ true); } - else if (node.operatorToken.kind === 52 /* BarBarToken */) { - narrowedType = narrowType(type, node.left, /*assumeTrue*/ false); + else if (node_1.operatorToken.kind === 52 /* BarBarToken */) { + type = narrowType(type, node_1.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; + default: + ts.Debug.fail("Unreachable!"); } - // Use narrowed type if construct contains no assignments to variable - if (narrowedType !== type) { - if (isVariableAssignedWithin(symbol, node)) { - break; - } - type = narrowedType; + // Use original type if construct contains assignments to variable + if (type !== originalType && isVariableAssignedWithin(symbol, node_1)) { + type = originalType; } } + // Preserve old top-level behavior - if the branch is really an empty set, revert to prior type + if (type === emptyUnionType) { + type = originalType; + } } } 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 */) { + if (expr.left.kind !== 179 /* TypeOfExpression */ || expr.right.kind !== 9 /* StringLiteral */) { return type; } var left = expr.left; @@ -19094,31 +20979,34 @@ var ts; 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); + var typeInfo = primitiveTypeInfo[right.text]; + // Don't narrow `undefined` + if (typeInfo && typeInfo.type === undefinedType) { + return type; + } + var flags; + if (typeInfo) { + flags = typeInfo.flags; } 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); + assumeTrue = !assumeTrue; + flags = 132 /* NumberLike */ | 258 /* StringLike */ | 16777216 /* ESSymbol */ | 8 /* Boolean */; + } + // At this point we can bail if it's not a union + if (!(type.flags & 16384 /* Union */)) { + // If we're on the true branch and the type is a subtype, we should return the primitive type + if (assumeTrue && typeInfo && isTypeSubtypeOf(typeInfo.type, type)) { + return typeInfo.type; } - // Otherwise we don't have enough information to do anything. - return type; + // If the active non-union type would be removed from a union by this type guard, return an empty union + return filterUnion(type) ? type : emptyUnionType; + } + return getUnionType(ts.filter(type.types, filterUnion), /*noSubtypeReduction*/ true); + function filterUnion(type) { + return assumeTrue === !!(type.flags & flags); } } function narrowTypeByAnd(type, expr, assumeTrue) { @@ -19131,7 +21019,7 @@ var ts; // 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) + narrowType(type, expr.right, /*assumeTrue*/ false) ]); } } @@ -19141,7 +21029,7 @@ var ts; // 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) + narrowType(type, expr.right, /*assumeTrue*/ true) ]); } else { @@ -19151,7 +21039,7 @@ var ts; } 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) { + if (isTypeAny(type) || expr.left.kind !== 69 /* Identifier */ || getResolvedSymbol(expr.left) !== symbol) { return type; } // Check that right operand is a function type with a prototype property @@ -19170,7 +21058,7 @@ var ts; } if (!targetType) { // Target type is type of construct signature - var constructSignatures; + var constructSignatures = void 0; if (rightType.flags & 2048 /* Interface */) { constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } @@ -19182,11 +21070,17 @@ var ts; } } if (targetType) { - return getNarrowedType(type, targetType); + return getNarrowedType(type, targetType, assumeTrue); } return type; } - function getNarrowedType(originalType, narrowedTypeCandidate) { + function getNarrowedType(originalType, narrowedTypeCandidate, assumeTrue) { + if (!assumeTrue) { + if (originalType.flags & 16384 /* Union */) { + return getUnionType(ts.filter(originalType.types, function (t) { return !isTypeSubtypeOf(t, narrowedTypeCandidate); })); + } + return originalType; + } // 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 */) { @@ -19201,33 +21095,54 @@ var ts; } return originalType; } - function narrowTypeByTypePredicate(type, expr, assumeTrue) { + function narrowTypeByTypePredicate(type, callExpression, 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; + var signature = getResolvedSignature(callExpression); + var predicate = signature.typePredicate; + if (!predicate) { + return type; + } + if (ts.isIdentifierTypePredicate(predicate)) { + if (callExpression.arguments[predicate.parameterIndex] && + getSymbolAtTypePredicatePosition(callExpression.arguments[predicate.parameterIndex]) === symbol) { + return getNarrowedType(type, predicate.type, assumeTrue); + } + } + else { + var invokedExpression = skipParenthesizedNodes(callExpression.expression); + return narrowTypeByThisTypePredicate(type, predicate, invokedExpression, assumeTrue); + } + return type; + } + function narrowTypeByThisTypePredicate(type, predicate, invokedExpression, assumeTrue) { + if (invokedExpression.kind === 170 /* ElementAccessExpression */ || invokedExpression.kind === 169 /* PropertyAccessExpression */) { + var accessExpression = invokedExpression; + var possibleIdentifier = skipParenthesizedNodes(accessExpression.expression); + if (possibleIdentifier.kind === 69 /* Identifier */ && getSymbolAtTypePredicatePosition(possibleIdentifier) === symbol) { + return getNarrowedType(type, predicate.type, assumeTrue); } - return getNarrowedType(type, signature.typePredicate.type); } return type; } + function getSymbolAtTypePredicatePosition(expr) { + expr = skipParenthesizedNodes(expr); + switch (expr.kind) { + case 69 /* Identifier */: + case 169 /* PropertyAccessExpression */: + return getSymbolOfEntityNameOrPropertyAccessExpression(expr); + } + } // 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 */: + case 171 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 172 /* ParenthesizedExpression */: + case 175 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 181 /* BinaryExpression */: + case 184 /* BinaryExpression */: var operator = expr.operatorToken.kind; if (operator === 32 /* EqualsEqualsEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { return narrowTypeByEquality(type, expr, assumeTrue); @@ -19242,7 +21157,7 @@ var ts; return narrowTypeByInstanceof(type, expr, assumeTrue); } break; - case 179 /* PrefixUnaryExpression */: + case 182 /* PrefixUnaryExpression */: if (expr.operator === 49 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } @@ -19251,6 +21166,12 @@ var ts; return type; } } + function skipParenthesizedNodes(expression) { + while (expression.kind === 175 /* ParenthesizedExpression */) { + expression = expression.expression; + } + return expression; + } function checkIdentifier(node) { var symbol = getResolvedSymbol(node); // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. @@ -19261,23 +21182,40 @@ var ts; // can explicitly bound arguments objects if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); - if (container.kind === 174 /* ArrowFunction */) { + if (container.kind === 177 /* 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 */; + getNodeLinks(container).flags |= 8192 /* CaptureArguments */; } } if (symbol.flags & 8388608 /* Alias */ && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } + var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + if (languageVersion === 2 /* ES6 */ + && localOrExportSymbol.flags & 32 /* Class */ + && localOrExportSymbol.valueDeclaration.kind === 217 /* ClassDeclaration */ + && ts.nodeIsDecorated(localOrExportSymbol.valueDeclaration)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === localOrExportSymbol.valueDeclaration && container.name !== node) { + getNodeLinks(container).flags |= 524288 /* ClassWithBodyScopedClassBinding */; + getNodeLinks(node).flags |= 1048576 /* BodyScopedClassBinding */; + break; + } + container = ts.getContainingClass(container); + } + } checkCollisionWithCapturedSuperVariable(node, node); checkCollisionWithCapturedThisVariable(node, node); - checkBlockScopedBindingCapturedInLoop(node, symbol); - return getNarrowedTypeOfSymbol(getExportSymbolOfValueSymbolIfExported(symbol), node); + checkNestedBlockScopedBinding(node, symbol); + return getNarrowedTypeOfSymbol(localOrExportSymbol, node); } function isInsideFunction(node, threshold) { var current = node; @@ -19289,44 +21227,79 @@ var ts; } return false; } - function checkBlockScopedBindingCapturedInLoop(node, symbol) { + function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES6 */ || - (symbol.flags & 2 /* BlockScopedVariable */) === 0 || - symbol.valueDeclaration.parent.kind === 244 /* CatchClause */) { + (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || + symbol.valueDeclaration.parent.kind === 247 /* 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); + // 1. walk from the use site up to the declaration and check + // if there is anything function like between declaration and use-site (is binding/class is captured in function). + // 2. walk from the declaration up to the boundary of lexical environment and check + // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + var usedInFunction = isInsideFunction(node.parent, container); var current = container; + var containedInIterationStatement = false; 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 */; + if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) { + containedInIterationStatement = true; break; } current = current.parent; } + if (containedInIterationStatement) { + if (usedInFunction) { + // mark iteration statement as containing block-scoped binding captured in some function + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } + // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. + // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. + if (container.kind === 202 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 215 /* VariableDeclarationList */).parent === container && + isAssignedInBodyOfForStatement(node, container)) { + getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + } + // set 'declared inside loop' bit on the block-scoped binding + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + } + if (usedInFunction) { + getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + } + } + function isAssignedInBodyOfForStatement(node, container) { + var current = node; + // skip parenthesized nodes + while (current.parent.kind === 175 /* ParenthesizedExpression */) { + current = current.parent; + } + // check if node is used as LHS in some assignment expression + var isAssigned = false; + if (current.parent.kind === 184 /* BinaryExpression */) { + isAssigned = current.parent.left === current && ts.isAssignmentOperator(current.parent.operatorToken.kind); + } + if ((current.parent.kind === 182 /* PrefixUnaryExpression */ || current.parent.kind === 183 /* PostfixUnaryExpression */)) { + var expr = current.parent; + isAssigned = expr.operator === 41 /* PlusPlusToken */ || expr.operator === 42 /* MinusMinusToken */; + } + if (!isAssigned) { + return false; + } + // at this point we know that node is the target of assignment + // now check that modification happens inside the statement part of the ForStatement + while (current !== container) { + if (current === container.statement) { + return true; + } + else { + current = current.parent; + } + } + return false; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 141 /* PropertyDeclaration */ || container.kind === 144 /* Constructor */) { + if (container.kind === 142 /* PropertyDeclaration */ || container.kind === 145 /* Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } @@ -19334,38 +21307,93 @@ var ts; getNodeLinks(container).flags |= 4 /* CaptureThis */; } } + function findFirstSuperCall(n) { + if (ts.isSuperCallExpression(n)) { + return n; + } + else if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findFirstSuperCall); + } + /** + * Return a cached result if super-statement is already found. + * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor + * + * @param constructor constructor-function to look for super statement + */ + function getSuperCallInConstructor(constructor) { + var links = getNodeLinks(constructor); + // Only trying to find super-call if we haven't yet tried to find one. Once we try, we will record the result + if (links.hasSuperCall === undefined) { + links.superCall = findFirstSuperCall(constructor.body); + links.hasSuperCall = links.superCall ? true : false; + } + return links.superCall; + } + /** + * Check if the given class-declaration extends null then return true. + * Otherwise, return false + * @param classDecl a class declaration to check if it extends null + */ + function classDeclarationExtendsNull(classDecl) { + var classSymbol = getSymbolOfNode(classDecl); + var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); + return baseConstructorType === nullType; + } 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; + if (container.kind === 145 /* Constructor */) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + // If a containing class does not have extends clause or the class extends null + // skip checking whether super statement is called before "this" accessing. + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + // We should give an error in the following cases: + // - No super-call + // - "this" is accessing before super-call. + // i.e super(this) + // this.x; super(); + // We want to make sure that super-call is done before accessing "this" so that + // "this" is not accessed as a parameter of the super-call. + if (!superCall || superCall.end > node.pos) { + // In ES6, super inside constructor of class-declaration has to precede "this" accessing + error(node, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + } + } + } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 174 /* ArrowFunction */) { + if (container.kind === 177 /* 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 */: + case 221 /* 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 */: + case 220 /* 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 */: + case 145 /* 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 */) { + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: + if (container.flags & 64 /* Static */) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; - case 136 /* ComputedPropertyName */: + case 137 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -19374,69 +21402,183 @@ var ts; } if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); - return container.flags & 128 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return container.flags & 64 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + } + if (ts.isInJavaScriptFile(node)) { + var type = getTypeForThisExpressionFromJSDoc(container); + if (type && type !== unknownType) { + return type; + } + // If this is a function in a JS file, it might be a class method. Check if it's the RHS + // of a x.prototype.y = function [name]() { .... } + if (container.kind === 176 /* FunctionExpression */) { + if (ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') + var className = container.parent // x.protoype.y = f + .left // x.prototype.y + .expression // x.prototype + .expression; // x + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { + return getInferredClassType(classSymbol); + } + } + } } return anyType; } + function getTypeForThisExpressionFromJSDoc(node) { + var typeTag = ts.getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && typeTag.typeExpression.type && typeTag.typeExpression.type.kind === 264 /* JSDocFunctionType */) { + var jsDocFunctionType = typeTag.typeExpression.type; + if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 267 /* JSDocThisType */) { + return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); + } + } + } function isInConstructorArgumentInitializer(node, constructorDecl) { for (var n = node; n && n !== constructorDecl; n = n.parent) { - if (n.kind === 138 /* Parameter */) { + if (n.kind === 139 /* 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 isCallExpression = node.parent.kind === 171 /* CallExpression */ && node.parent.expression === node; + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ 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); + while (container && container.kind === 177 /* ArrowFunction */) { + container = ts.getSuperContainer(container, /*stopOnFunctions*/ 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 */; + if (!canUseSuperExpression) { + // issue more specific error if super is used in computed property name + // class A { foo() { return "1" }} + // class B { + // [super.foo()]() {} + // } + var current = node; + while (current && current !== container && current.kind !== 137 /* ComputedPropertyName */) { + current = current.parent; } - else { - nodeCheckFlag = 256 /* SuperInstance */; + if (current && current.kind === 137 /* ComputedPropertyName */) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } - 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); + else if (isCallExpression) { + error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - } - if (!baseClassType) { - if (!classDeclaration || !ts.getClassExtendsHeritageClauseElement(classDeclaration)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 168 /* ObjectLiteralExpression */)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } + 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 (!canUseSuperExpression) { - if (container && container.kind === 136 /* ComputedPropertyName */) { - error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); + if ((container.flags & 64 /* Static */) || isCallExpression) { + nodeCheckFlag = 512 /* SuperStatic */; + } + else { + nodeCheckFlag = 256 /* SuperInstance */; + } + getNodeLinks(node).flags |= nodeCheckFlag; + // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference. + // This is due to the fact that we emit the body of an async function inside of a generator function. As generator + // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper + // uses an arrow function, which is permitted to reference `super`. + // + // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property + // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value + // of a property or indexed access, either as part of an assignment expression or destructuring assignment. + // + // The simplest case is reading a value, in which case we will emit something like the following: + // + // // ts + // ... + // async asyncMethod() { + // let x = await super.asyncMethod(); + // return x; + // } + // ... + // + // // js + // ... + // asyncMethod() { + // const _super = name => super[name]; + // return __awaiter(this, arguments, Promise, function *() { + // let x = yield _super("asyncMethod").call(this); + // return x; + // }); + // } + // ... + // + // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases + // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: + // + // // ts + // ... + // async asyncMethod(ar: Promise) { + // [super.a, super.b] = await ar; + // } + // ... + // + // // js + // ... + // asyncMethod(ar) { + // const _super = (function (geti, seti) { + // const cache = Object.create(null); + // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); + // })(name => super[name], (name, value) => super[name] = value); + // return __awaiter(this, arguments, Promise, function *() { + // [_super("a").value, _super("b").value] = yield ar; + // }); + // } + // ... + // + // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. + // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment + // while a property access can. + if (container.kind === 144 /* MethodDeclaration */ && container.flags & 256 /* Async */) { + if (ts.isSuperPropertyOrElementAccess(node.parent) && isAssignmentTarget(node.parent)) { + getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } - else if (isCallExpression) { - error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); + else { + getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */; + } + } + 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 (container.parent.kind === 168 /* ObjectLiteralExpression */) { + if (languageVersion < 2 /* ES6 */) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return unknownType; } else { - error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); + // for object literal assume that type of 'super' is 'any' + return anyType; + } + } + // at this point the only legal case for parent is ClassLikeDeclaration + var classLikeDeclaration = container.parent; + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); } return unknownType; } - if (container.kind === 144 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 145 /* 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; @@ -19451,29 +21593,29 @@ var ts; 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 */; + return container.kind === 145 /* 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 */; + // topmost container must be something that is directly nested in the class declaration\object literal expression + if (ts.isClassLike(container.parent) || container.parent.kind === 168 /* ObjectLiteralExpression */) { + if (container.flags & 64 /* Static */) { + return container.kind === 144 /* MethodDeclaration */ || + container.kind === 143 /* MethodSignature */ || + container.kind === 146 /* GetAccessor */ || + container.kind === 147 /* 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 container.kind === 144 /* MethodDeclaration */ || + container.kind === 143 /* MethodSignature */ || + container.kind === 146 /* GetAccessor */ || + container.kind === 147 /* SetAccessor */ || + container.kind === 142 /* PropertyDeclaration */ || + container.kind === 141 /* PropertySignature */ || + container.kind === 145 /* Constructor */; } } } @@ -19515,7 +21657,7 @@ var ts; if (declaration.type) { return getTypeFromTypeNode(declaration.type); } - if (declaration.kind === 138 /* Parameter */) { + if (declaration.kind === 139 /* Parameter */) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -19548,7 +21690,7 @@ var ts; } function isInParameterInitializerBeforeContainingFunction(node) { while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 138 /* Parameter */ && node.parent.initializer === node) { + if (node.parent.kind === 139 /* Parameter */ && node.parent.initializer === node) { return true; } node = node.parent; @@ -19559,8 +21701,8 @@ var ts; // 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 */))) { + functionDecl.kind === 145 /* Constructor */ || + functionDecl.kind === 146 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 147 /* SetAccessor */))) { return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); } // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature @@ -19582,7 +21724,7 @@ var ts; return undefined; } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 170 /* TaggedTemplateExpression */) { + if (template.parent.kind === 173 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -19605,6 +21747,11 @@ var ts; } return type; } + else if (operator === 51 /* AmpersandAmpersandToken */ || operator === 24 /* CommaToken */) { + if (node === binaryExpression.right) { + return getContextualType(binaryExpression); + } + } return undefined; } // Apply a mapping function to a contextual type and return the resulting type. If the contextual type @@ -19617,8 +21764,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var current = types_8[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -19643,6 +21790,9 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } + function contextualTypeIsStringLiteralType(type) { + return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isStringLiteralType) : isStringLiteralType(type)); + } // 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)); @@ -19664,7 +21814,7 @@ var ts; } function getContextualTypeForObjectLiteralElement(element) { var objectLiteral = element.parent; - var type = getContextualType(objectLiteral); + var type = getApparentTypeOfContextualType(objectLiteral); if (type) { if (!ts.hasDynamicName(element)) { // For a (non-symbol) computed property, there is no reason to look up the name @@ -19687,7 +21837,7 @@ var ts; // type of T. function getContextualTypeForElementExpression(node) { var arrayLiteral = node.parent; - var type = getContextualType(arrayLiteral); + var type = getApparentTypeOfContextualType(arrayLiteral); if (type) { var index = ts.indexOf(arrayLiteral.elements, node); return getTypeOfPropertyOfContextualType(type, "" + index) @@ -19701,30 +21851,45 @@ var ts; 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); + function getContextualTypeForJsxAttribute(attribute) { + var kind = attribute.kind; + var jsxElement = attribute.parent; + var attrsType = getJsxElementAttributesType(jsxElement); + if (attribute.kind === 241 /* JsxAttribute */) { if (!attrsType || isTypeAny(attrsType)) { return undefined; } - else { - return getTypeOfPropertyOfType(attrsType, attrib.name.text); - } + return getTypeOfPropertyOfType(attrsType, attribute.name.text); } - if (expr.kind === 239 /* JsxSpreadAttribute */) { - return getJsxElementAttributesType(expr.parent); + else if (attribute.kind === 242 /* JsxSpreadAttribute */) { + return attrsType; } - return undefined; + ts.Debug.fail("Expected JsxAttribute or JsxSpreadAttribute, got ts.SyntaxKind[" + kind + "]"); } // 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); + function getApparentTypeOfContextualType(node) { + var type = getContextualType(node); return type && getApparentType(type); } - function getContextualTypeWorker(node) { + /** + * Woah! Do you really want to use this function? + * + * Unless you're trying to get the *non-apparent* type for a + * value-literal type or you're authoring relevant portions of this algorithm, + * you probably meant to use 'getApparentTypeOfContextualType'. + * Otherwise this may not be very useful. + * + * In cases where you *are* working on this function, you should understand + * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContetxualType'. + * + * - Use 'getContextualType' when you are simply going to propagate the result to the expression. + * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type. + * + * @param node the expression whose contextual type will be returned. + * @returns the contextual type of an expression. + */ + function getContextualType(node) { if (isInsideWithStatementBody(node)) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; @@ -19734,39 +21899,41 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 211 /* VariableDeclaration */: - case 138 /* Parameter */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 163 /* BindingElement */: + case 214 /* VariableDeclaration */: + case 139 /* Parameter */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: + case 166 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 174 /* ArrowFunction */: - case 204 /* ReturnStatement */: + case 177 /* ArrowFunction */: + case 207 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 184 /* YieldExpression */: + case 187 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 171 /* CallExpression */: + case 172 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: + case 174 /* TypeAssertionExpression */: + case 192 /* AsExpression */: return getTypeFromTypeNode(parent.type); - case 181 /* BinaryExpression */: + case 184 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 245 /* PropertyAssignment */: + case 248 /* PropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 164 /* ArrayLiteralExpression */: + case 167 /* ArrayLiteralExpression */: return getContextualTypeForElementExpression(node); - case 182 /* ConditionalExpression */: + case 185 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 190 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 183 /* TemplateExpression */); + case 193 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 186 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 172 /* ParenthesizedExpression */: + case 175 /* ParenthesizedExpression */: return getContextualType(parent); - case 240 /* JsxExpression */: - case 239 /* JsxSpreadAttribute */: - return getContextualTypeForJsxExpression(parent); + case 243 /* JsxExpression */: + return getContextualType(parent); + case 241 /* JsxAttribute */: + case 242 /* JsxSpreadAttribute */: + return getContextualTypeForJsxAttribute(parent); } return undefined; } @@ -19782,7 +21949,7 @@ var ts; } } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 173 /* FunctionExpression */ || node.kind === 174 /* ArrowFunction */; + return node.kind === 176 /* FunctionExpression */ || node.kind === 177 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -19796,10 +21963,10 @@ var ts; // 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)); + ts.Debug.assert(node.kind !== 144 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var type = ts.isObjectLiteralMethod(node) ? getContextualTypeForObjectLiteralMethod(node) - : getContextualType(node); + : getApparentTypeOfContextualType(node); if (!type) { return undefined; } @@ -19808,15 +21975,15 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var current = types_9[_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)) { + else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true, compareTypesIdentical)) { // Signatures aren't identical, do not use return undefined; } @@ -19859,13 +22026,13 @@ var ts; // 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) { + if (parent.kind === 184 /* BinaryExpression */ && parent.operatorToken.kind === 56 /* EqualsToken */ && parent.left === node) { return true; } - if (parent.kind === 245 /* PropertyAssignment */) { + if (parent.kind === 248 /* PropertyAssignment */) { return isAssignmentTarget(parent.parent); } - if (parent.kind === 164 /* ArrayLiteralExpression */) { + if (parent.kind === 167 /* ArrayLiteralExpression */) { return isAssignmentTarget(parent); } return false; @@ -19881,17 +22048,17 @@ var ts; 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 */); + return (node.kind === 166 /* BindingElement */ && !!node.initializer) || + (node.kind === 184 /* 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 */) { + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var e = elements_1[_i]; + if (inDestructuringPattern && e.kind === 188 /* SpreadElementExpression */) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -19915,7 +22082,7 @@ var ts; var type = checkExpression(e, contextualMapper); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 185 /* SpreadElementExpression */; + hasSpreadElement = hasSpreadElement || e.kind === 188 /* SpreadElementExpression */; } if (!hasSpreadElement) { // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such @@ -19925,12 +22092,12 @@ var ts; type.pattern = node; return type; } - var contextualType = getContextualType(node); + var contextualType = getApparentTypeOfContextualType(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 */)) { + if (pattern && (pattern.kind === 165 /* ArrayBindingPattern */ || pattern.kind === 167 /* ArrayLiteralExpression */)) { var patternElements = pattern.elements; for (var i = elementTypes.length; i < patternElements.length; i++) { var patternElement = patternElements[i]; @@ -19938,7 +22105,7 @@ var ts; elementTypes.push(contextualType.elementTypes[i]); } else { - if (patternElement.kind !== 187 /* OmittedExpression */) { + if (patternElement.kind !== 190 /* OmittedExpression */) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(unknownType); @@ -19953,7 +22120,7 @@ var ts; return createArrayType(elementTypes.length ? getUnionType(elementTypes) : undefinedType); } function isNumericName(name) { - return name.kind === 136 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text); + return name.kind === 137 /* 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, @@ -20008,25 +22175,26 @@ var ts; checkGrammarObjectLiteralExpression(node, inDestructuringPattern); var propertiesTable = {}; var propertiesArray = []; - var contextualType = getContextualType(node); + var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 161 /* ObjectBindingPattern */ || contextualType.pattern.kind === 165 /* ObjectLiteralExpression */); + (contextualType.pattern.kind === 164 /* ObjectBindingPattern */ || contextualType.pattern.kind === 168 /* ObjectLiteralExpression */); var typeFlags = 0; + var patternWithComputedProperties = false; 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 */ || + if (memberDecl.kind === 248 /* PropertyAssignment */ || + memberDecl.kind === 249 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { var type = void 0; - if (memberDecl.kind === 245 /* PropertyAssignment */) { + if (memberDecl.kind === 248 /* PropertyAssignment */) { type = checkPropertyAssignment(memberDecl, contextualMapper); } - else if (memberDecl.kind === 143 /* MethodDeclaration */) { + else if (memberDecl.kind === 144 /* MethodDeclaration */) { type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - ts.Debug.assert(memberDecl.kind === 246 /* ShorthandPropertyAssignment */); + ts.Debug.assert(memberDecl.kind === 249 /* ShorthandPropertyAssignment */); type = checkExpression(memberDecl.name, contextualMapper); } typeFlags |= type.flags; @@ -20034,13 +22202,16 @@ var ts; 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); + var isOptional = (memberDecl.kind === 248 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 249 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 536870912 /* Optional */; } + if (ts.hasDynamicName(memberDecl)) { + patternWithComputedProperties = true; + } } - else if (contextualTypeHasPattern) { + else if (contextualTypeHasPattern && !(contextualType.flags & 67108864 /* ObjectLiteralPatternWithComputedProperties */)) { // 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); @@ -20066,7 +22237,7 @@ var ts; // 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 */); + ts.Debug.assert(memberDecl.kind === 146 /* GetAccessor */ || memberDecl.kind === 147 /* SetAccessor */); checkAccessorDeclaration(memberDecl); } if (!ts.hasDynamicName(memberDecl)) { @@ -20092,7 +22263,7 @@ var ts; 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 */); + result.flags |= 524288 /* ObjectLiteral */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */) | (patternWithComputedProperties ? 67108864 /* ObjectLiteralPatternWithComputedProperties */ : 0); if (inDestructuringPattern) { result.pattern = node; } @@ -20124,43 +22295,24 @@ var ts; 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); - } + // 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 */: + case 243 /* JsxExpression */: checkJsxExpression(child); break; - case 233 /* JsxElement */: + case 236 /* JsxElement */: checkJsxElement(child); break; - case 234 /* JsxSelfClosingElement */: + case 237 /* JsxSelfClosingElement */: checkJsxSelfClosingElement(child); break; - default: - // No checks for JSX Text - ts.Debug.assert(child.kind === 236 /* JsxText */); } } return jsxElementType || anyType; @@ -20176,7 +22328,7 @@ var ts; * 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 */) { + if (tagName.kind === 136 /* QualifiedName */) { return false; } else { @@ -20225,8 +22377,8 @@ var ts; 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]; + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_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]) { @@ -20240,12 +22392,11 @@ var ts; } 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; + function getJsxType(name) { + if (jsxTypes[name] === undefined) { + return jsxTypes[name] = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType; } - return jsxIntrinsicElementsType; + return jsxTypes[name]; } /// 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 @@ -20254,7 +22405,6 @@ var ts; /// 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)) { @@ -20266,7 +22416,7 @@ var ts; } return links.resolvedSymbol; function lookupIntrinsicTag(node) { - var intrinsicElementsType = getJsxIntrinsicElementsType(); + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { // Property case var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.text); @@ -20288,13 +22438,14 @@ var ts; if (compilerOptions.noImplicitAny) { error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, JsxNames.IntrinsicElements); } + return unknownSymbol; } } function lookupClassTag(node) { var valueSymbol = resolveJsxTagName(node); // Look up the value in the current scope if (valueSymbol && valueSymbol !== unknownSymbol) { - links.jsxFlags |= 4 /* ClassElement */; + links.jsxFlags |= 4 /* ValueElement */; if (valueSymbol.flags & 8388608 /* Alias */) { markAliasSymbolAsReferenced(valueSymbol); } @@ -20320,7 +22471,7 @@ var ts; 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"); + ts.Debug.assert(!!(getNodeLinks(node).jsxFlags & 4 /* ValueElement */), "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 @@ -20342,13 +22493,7 @@ var ts; 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; + return getUnionType(signatures.map(getReturnTypeOfSignature)); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesPropery doesn't exist (which means all @@ -20390,8 +22535,31 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedJsxType) { var sym = getJsxElementTagSymbol(node); - if (links.jsxFlags & 4 /* ClassElement */) { + if (links.jsxFlags & 4 /* ValueElement */) { + // Get the element instance type (the result of newing or invoking this tag) var elemInstanceType = getJsxElementInstanceType(node); + var elemClassType = getJsxGlobalElementClassType(); + if (!elemClassType || !isTypeAssignableTo(elemInstanceType, elemClassType)) { + // Is this is a stateless function component? See if its single signature's return type is + // assignable to the JSX Element Type + var elemType = getTypeOfSymbol(sym); + var callSignatures = elemType && getSignaturesOfType(elemType, 0 /* Call */); + var callSignature = callSignatures && callSignatures.length > 0 && callSignatures[0]; + var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); + var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + if (callReturnType && isTypeAssignableTo(callReturnType, jsxElementType)) { + // Intersect in JSX.IntrinsicAttributes if it exists + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttributes !== unknownType) { + paramType = intersectTypes(intrinsicAttributes, paramType); + } + return links.resolvedJsxType = paramType; + } + } + // Issue an error if this return type isn't assignable to JSX.ElementClass + if (elemClassType) { + checkTypeRelatedTo(elemInstanceType, elemClassType, assignableRelation, node, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } if (isTypeAny(elemInstanceType)) { return links.resolvedJsxType = elemInstanceType; } @@ -20411,14 +22579,34 @@ var ts; return links.resolvedJsxType = emptyObjectType; } else if (isTypeAny(attributesType) || (attributesType === unknownType)) { + // Props is of type 'any' or unknown 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)); + else if (attributesType.flags & 16384 /* Union */) { + // Props cannot be a union type + error(node.tagName, ts.Diagnostics.JSX_element_attributes_type_0_may_not_be_a_union_type, typeToString(attributesType)); return links.resolvedJsxType = anyType; } else { - return links.resolvedJsxType = attributesType; + // Normal case -- add in IntrinsicClassElements and IntrinsicElements + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + if (typeParams) { + if (typeParams.length === 1) { + apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); + } + } + else { + apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); + } + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return links.resolvedJsxType = apparentAttributesType; } } } @@ -20445,7 +22633,6 @@ var ts; var prop = getPropertyOfType(attributesType, attrib.name.text); return prop || unknownSymbol; } - var jsxElementClassType = undefined; function getJsxGlobalElementClassType() { if (!jsxElementClassType) { jsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); @@ -20454,7 +22641,7 @@ var ts; } /// Returns all the properties of the Jsx.IntrinsicElements interface function getJsxIntrinsicTagNames() { - var intrinsics = getJsxIntrinsicElementsType(); + var intrinsics = getJsxType(JsxNames.IntrinsicElements); return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; } function checkJsxPreconditions(errorNode) { @@ -20471,14 +22658,13 @@ var ts; 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; - } + // The reactNamespace symbol should be marked as 'used' so we don't incorrectly elide its import. And if there + // is no reactNamespace symbol in scope when targeting React emit, we should issue an error. + var reactRefErr = compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; + var reactSym = resolveName(node.tagName, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace); + if (reactSym) { + getSymbolLinks(reactSym).referenced = true; } var targetAttributesType = getJsxElementAttributesType(node); var nameTable = {}; @@ -20487,11 +22673,11 @@ var ts; // 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 */) { + if (node.attributes[i].kind === 241 /* JsxAttribute */) { checkJsxAttribute((node.attributes[i]), targetAttributesType, nameTable); } else { - ts.Debug.assert(node.attributes[i].kind === 239 /* JsxSpreadAttribute */); + ts.Debug.assert(node.attributes[i].kind === 242 /* JsxSpreadAttribute */); var spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable); if (isTypeAny(spreadType)) { sawSpreadedAny = true; @@ -20521,10 +22707,10 @@ var ts; // 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 */; + return s.valueDeclaration ? s.valueDeclaration.kind : 142 /* PropertyDeclaration */; } function getDeclarationFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 16 /* Public */ | 128 /* Static */ : 0; + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 8 /* Public */ | 64 /* Static */ : 0; } /** * Check whether the requested property access is valid. @@ -20536,9 +22722,9 @@ var ts; */ function checkClassPropertyAccess(node, left, type, prop) { var flags = getDeclarationFlagsFromSymbol(prop); - var declaringClass = getDeclaredTypeOfSymbol(prop.parent); + var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); if (left.kind === 95 /* SuperKeyword */) { - var errorNode = node.kind === 166 /* PropertyAccessExpression */ ? + var errorNode = node.kind === 169 /* PropertyAccessExpression */ ? node.name : node.right; // TS 1.0 spec (April 2014): 4.8.2 @@ -20548,13 +22734,13 @@ var ts; // - 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 */) { + if (languageVersion < 2 /* ES6 */ && getDeclarationKindFromSymbol(prop) !== 144 /* 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 */) { + if (flags & 128 /* 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 @@ -20564,7 +22750,7 @@ var ts; } } // Public properties are otherwise accessible. - if (!(flags & (32 /* Private */ | 64 /* Protected */))) { + if (!(flags & (16 /* Private */ | 32 /* Protected */))) { return true; } // Property is known to be private or protected at this point @@ -20572,7 +22758,7 @@ var ts; 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 (flags & 16 /* Private */) { if (declaringClass !== enclosingClass) { error(node, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass)); return false; @@ -20590,7 +22776,7 @@ var ts; return false; } // No further restrictions for static properties - if (flags & 128 /* Static */) { + if (flags & 64 /* Static */) { return true; } // An instance property must be accessed through an instance of the enclosing class @@ -20635,7 +22821,7 @@ var ts; return getTypeOfSymbol(prop); } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 166 /* PropertyAccessExpression */ + var left = node.kind === 169 /* PropertyAccessExpression */ ? node.expression : node.left; var type = checkExpression(left); @@ -20647,11 +22833,58 @@ var ts; } return true; } + /** + * Return the symbol of the for-in variable declared or referenced by the given for-in statement. + */ + function getForInVariableSymbol(node) { + var initializer = node.initializer; + if (initializer.kind === 215 /* VariableDeclarationList */) { + var variable = initializer.declarations[0]; + if (variable && !ts.isBindingPattern(variable.name)) { + return getSymbolOfNode(variable); + } + } + else if (initializer.kind === 69 /* Identifier */) { + return getResolvedSymbol(initializer); + } + return undefined; + } + /** + * Return true if the given type is considered to have numeric property names. + */ + function hasNumericPropertyNames(type) { + return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */); + } + /** + * Return true if given node is an expression consisting of an identifier (possibly parenthesized) + * that references a for-in variable for an object with numeric property names. + */ + function isForInVariableForNumericPropertyNames(expr) { + var e = skipParenthesizedNodes(expr); + if (e.kind === 69 /* Identifier */) { + var symbol = getResolvedSymbol(e); + if (symbol.flags & 3 /* Variable */) { + var child = expr; + var node = expr.parent; + while (node) { + if (node.kind === 203 /* ForInStatement */ && + child === node.statement && + getForInVariableSymbol(node) === symbol && + hasNumericPropertyNames(checkExpression(node.expression))) { + return true; + } + child = node; + node = node.parent; + } + } + } + return false; + } function checkIndexedAccess(node) { // Grammar checking if (!node.argumentExpression) { - var sourceFile = getSourceFile(node); - if (node.parent.kind === 169 /* NewExpression */ && node.parent.expression === node) { + var sourceFile = ts.getSourceFileOfNode(node); + if (node.parent.kind === 172 /* 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); @@ -20700,7 +22933,7 @@ var ts; // 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 */)) { + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 132 /* NumberLike */) || isForInVariableForNumericPropertyNames(node.argumentExpression)) { var numberIndexType = getIndexTypeOfType(objectType, 1 /* Number */); if (numberIndexType) { return numberIndexType; @@ -20713,7 +22946,9 @@ var ts; } // 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); + error(node, getIndexTypeOfType(objectType, 1 /* Number */) ? + ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number : + ts.Diagnostics.Index_signature_of_object_type_implicitly_has_an_any_type); } return anyType; } @@ -20732,7 +22967,7 @@ var ts; if (indexArgumentExpression.kind === 9 /* StringLiteral */ || indexArgumentExpression.kind === 8 /* NumericLiteral */) { return indexArgumentExpression.text; } - if (indexArgumentExpression.kind === 167 /* ElementAccessExpression */ || indexArgumentExpression.kind === 166 /* PropertyAccessExpression */) { + if (indexArgumentExpression.kind === 170 /* ElementAccessExpression */ || indexArgumentExpression.kind === 169 /* PropertyAccessExpression */) { var value = getConstantValue(indexArgumentExpression); if (value !== undefined) { return value.toString(); @@ -20787,10 +23022,10 @@ var ts; return true; } function resolveUntypedCall(node) { - if (node.kind === 170 /* TaggedTemplateExpression */) { + if (node.kind === 173 /* TaggedTemplateExpression */) { checkExpression(node.template); } - else if (node.kind !== 139 /* Decorator */) { + else if (node.kind !== 140 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -20807,7 +23042,7 @@ var ts; // 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; + // const b: B; // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] function reorderCandidates(signatures, result) { var lastParent; @@ -20817,16 +23052,16 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0; _i < signatures.length; _i++) { - var signature = signatures[_i]; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_5 = signature.declaration && signature.declaration.parent; + var parent_6 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_5 === lastParent) { + if (lastParent && parent_6 === lastParent) { index++; } else { - lastParent = parent_5; + lastParent = parent_6; index = cutoffIndex; } } @@ -20834,7 +23069,7 @@ var ts; // 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; + lastParent = parent_6; } lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless @@ -20856,7 +23091,7 @@ var ts; function getSpreadArgumentIndex(args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; - if (arg && arg.kind === 185 /* SpreadElementExpression */) { + if (arg && arg.kind === 188 /* SpreadElementExpression */) { return i; } } @@ -20868,13 +23103,13 @@ var ts; 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 */) { + if (node.kind === 173 /* 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 (tagExpression.template.kind === 186 /* 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; @@ -20891,7 +23126,7 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 139 /* Decorator */) { + else if (node.kind === 140 /* Decorator */) { isDecorator = true; typeArguments = undefined; adjustedArgCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); @@ -20900,7 +23135,7 @@ var ts; 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 */); + ts.Debug.assert(callExpression.kind === 172 /* NewExpression */); return signature.minArgumentCount === 0; } // For IDE scenarios we may have an incomplete call, so a trailing comma is tantamount to adding another argument. @@ -20952,7 +23187,7 @@ var ts; } function inferTypeArguments(node, signature, args, excludeArgument, context) { var typeParameters = signature.typeParameters; - var inferenceMapper = createInferenceMapper(context); + var inferenceMapper = getInferenceMapper(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 @@ -20979,7 +23214,7 @@ var ts; 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 */) { + if (arg === undefined || arg.kind !== 190 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i, arg); // If the effective argument type is 'undefined', there is no synthetic type @@ -21010,14 +23245,11 @@ var ts; } getInferredTypes(context); } - function checkTypeArguments(signature, typeArguments, typeArgumentResultTypes, reportErrors, headMessage) { + function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { var typeParameters = signature.typeParameters; var typeArgumentsAreAssignable = true; + var mapper; 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) { @@ -21027,7 +23259,11 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); typeArgumentHeadMessage = headMessage; } - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, constraint, reportErrors ? typeArgNode : undefined, typeArgumentHeadMessage, errorInfo); + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); } } } @@ -21038,7 +23274,7 @@ var ts; 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 */) { + if (arg === undefined || arg.kind !== 190 /* 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); @@ -21046,7 +23282,7 @@ var ts; // for the argument. In that case, we should check the argument. if (argType === undefined) { argType = arg.kind === 9 /* StringLiteral */ && !reportErrors - ? getStringLiteralType(arg) + ? getStringLiteralTypeForText(arg.text) : checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); } // Use argument expression as error location when reporting errors @@ -21070,16 +23306,16 @@ var ts; */ function getEffectiveCallArguments(node) { var args; - if (node.kind === 170 /* TaggedTemplateExpression */) { + if (node.kind === 173 /* TaggedTemplateExpression */) { var template = node.template; args = [undefined]; - if (template.kind === 183 /* TemplateExpression */) { + if (template.kind === 186 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args.push(span.expression); }); } } - else if (node.kind === 139 /* Decorator */) { + else if (node.kind === 140 /* 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. @@ -21104,19 +23340,19 @@ var ts; * Otherwise, the argument count is the length of the 'args' array. */ function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 139 /* Decorator */) { + if (node.kind === 140 /* Decorator */) { switch (node.parent.kind) { - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 217 /* ClassDeclaration */: + case 189 /* ClassExpression */: // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) return 1; - case 141 /* PropertyDeclaration */: + case 142 /* 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 */: + case 144 /* MethodDeclaration */: + case 146 /* GetAccessor */: + case 147 /* 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. @@ -21126,7 +23362,7 @@ var ts; // 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 */: + case 139 /* Parameter */: // A parameter declaration decorator will have three arguments (see // `ParameterDecorator` in core.d.ts) return 3; @@ -21150,25 +23386,25 @@ var ts; */ function getEffectiveDecoratorFirstArgumentType(node) { // The first argument to a decorator is its `target`. - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 217 /* 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 */) { + if (node.kind === 139 /* 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 */) { + if (node.kind === 145 /* 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 */) { + if (node.kind === 142 /* PropertyDeclaration */ || + node.kind === 144 /* MethodDeclaration */ || + node.kind === 146 /* GetAccessor */ || + node.kind === 147 /* 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 @@ -21195,21 +23431,21 @@ var ts; */ function getEffectiveDecoratorSecondArgumentType(node) { // The second argument to a decorator is its `propertyKey` - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 217 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); return unknownType; } - if (node.kind === 138 /* Parameter */) { + if (node.kind === 139 /* Parameter */) { node = node.parent; - if (node.kind === 144 /* Constructor */) { + if (node.kind === 145 /* 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 */) { + if (node.kind === 142 /* PropertyDeclaration */ || + node.kind === 144 /* MethodDeclaration */ || + node.kind === 146 /* GetAccessor */ || + node.kind === 147 /* 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 @@ -21219,8 +23455,8 @@ var ts; case 69 /* Identifier */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getStringLiteralType(element.name); - case 136 /* ComputedPropertyName */: + return getStringLiteralTypeForText(element.name.text); + case 137 /* ComputedPropertyName */: var nameType = checkComputedPropertyName(element.name); if (allConstituentTypesHaveKind(nameType, 16777216 /* ESSymbol */)) { return nameType; @@ -21246,21 +23482,21 @@ var ts; 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 */) { + if (node.kind === 217 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); return unknownType; } - if (node.kind === 138 /* Parameter */) { + if (node.kind === 139 /* Parameter */) { // The `parameterIndex` for a parameter decorator is always a number return numberType; } - if (node.kind === 141 /* PropertyDeclaration */) { + if (node.kind === 142 /* 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 */) { + if (node.kind === 144 /* MethodDeclaration */ || + node.kind === 146 /* GetAccessor */ || + node.kind === 147 /* SetAccessor */) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` // for the type of the member. var propertyType = getTypeOfNode(node); @@ -21292,10 +23528,10 @@ var ts; // 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 */) { + if (node.kind === 140 /* Decorator */) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 170 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 173 /* TaggedTemplateExpression */) { return globalTemplateStringsArrayType; } // This is not a synthetic argument, so we return 'undefined' @@ -21307,8 +23543,8 @@ var ts; */ 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 */)) { + if (node.kind === 140 /* Decorator */ || + (argIndex === 0 && node.kind === 173 /* TaggedTemplateExpression */)) { return undefined; } return args[argIndex]; @@ -21317,11 +23553,11 @@ var ts; * Gets the error node to use when reporting errors for an effective argument. */ function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 139 /* Decorator */) { + if (node.kind === 140 /* 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 */) { + else if (argIndex === 0 && node.kind === 173 /* TaggedTemplateExpression */) { // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. return node.template; } @@ -21330,8 +23566,8 @@ var ts; } } function resolveCall(node, signatures, candidatesOutArray, headMessage) { - var isTaggedTemplate = node.kind === 170 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 139 /* Decorator */; + var isTaggedTemplate = node.kind === 173 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 140 /* Decorator */; var typeArguments; if (!isTaggedTemplate && !isDecorator) { typeArguments = node.typeArguments; @@ -21437,7 +23673,8 @@ var ts; } else if (candidateForTypeArgumentError) { if (!isTaggedTemplate && !isDecorator && typeArguments) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, [], /*reportErrors*/ true, headMessage); + var typeArguments_2 = node.typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, headMessage); } else { ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); @@ -21460,8 +23697,8 @@ var ts; // declare function f(a: { xa: number; xb: number; }); // f({ | if (!produceDiagnostics) { - for (var _i = 0; _i < candidates.length; _i++) { - var candidate = candidates[_i]; + for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { + var candidate = candidates_1[_i]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -21480,8 +23717,8 @@ var ts; diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); } function chooseOverload(candidates, relation) { - for (var _i = 0; _i < candidates.length; _i++) { - var originalCandidate = candidates[_i]; + for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { + var originalCandidate = candidates_2[_i]; if (!hasCorrectArity(node, args, originalCandidate)) { continue; } @@ -21495,7 +23732,7 @@ var ts; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { - typeArgumentTypes = new Array(candidate.typeParameters.length); + typeArgumentTypes = ts.map(typeArguments, getTypeFromTypeNode); typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false); } else { @@ -21618,7 +23855,7 @@ var ts; // 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 */) { + if (valueDecl && valueDecl.flags & 128 /* Abstract */) { error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); return resolveErrorCall(node); } @@ -21676,16 +23913,16 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 217 /* ClassDeclaration */: + case 189 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 138 /* Parameter */: + case 139 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 141 /* PropertyDeclaration */: + case 142 /* 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 */: + case 144 /* MethodDeclaration */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; } } @@ -21704,7 +23941,7 @@ var ts; } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { - var errorInfo; + var errorInfo = void 0; 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)); @@ -21722,16 +23959,16 @@ var ts; // to correctly fill the candidatesOutArray. if (!links.resolvedSignature || candidatesOutArray) { links.resolvedSignature = anySignature; - if (node.kind === 168 /* CallExpression */) { + if (node.kind === 171 /* CallExpression */) { links.resolvedSignature = resolveCallExpression(node, candidatesOutArray); } - else if (node.kind === 169 /* NewExpression */) { + else if (node.kind === 172 /* NewExpression */) { links.resolvedSignature = resolveNewExpression(node, candidatesOutArray); } - else if (node.kind === 170 /* TaggedTemplateExpression */) { + else if (node.kind === 173 /* TaggedTemplateExpression */) { links.resolvedSignature = resolveTaggedTemplateExpression(node, candidatesOutArray); } - else if (node.kind === 139 /* Decorator */) { + else if (node.kind === 140 /* Decorator */) { links.resolvedSignature = resolveDecorator(node, candidatesOutArray); } else { @@ -21740,6 +23977,13 @@ var ts; } return links.resolvedSignature; } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(undefined, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); + } + return links.inferredClassType; + } /** * Syntactically and semantically checks a call or new expression. * @param node The call/new expression to be checked. @@ -21752,19 +23996,30 @@ var ts; if (node.expression.kind === 95 /* SuperKeyword */) { return voidType; } - if (node.kind === 169 /* NewExpression */) { + if (node.kind === 172 /* 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) { + declaration.kind !== 145 /* Constructor */ && + declaration.kind !== 149 /* ConstructSignature */ && + declaration.kind !== 154 /* ConstructorType */ && + !ts.isJSDocConstructSignature(declaration)) { + // When resolved signature is a call signature (and not a construct signature) the result type is any, unless + // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations + // in a JS file + var funcSymbol = checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 /* Function */)) { + return getInferredClassType(funcSymbol); + } + else if (compilerOptions.noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); } return anyType; } } + // In JavaScript files, calls to any identifier 'require' are treated as external module imports + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + return resolveExternalModuleTypeByLiteral(node.arguments[0]); + } return getReturnTypeOfSignature(signature); } function checkTaggedTemplateExpression(node) { @@ -21775,7 +24030,10 @@ var ts; var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { var widenedType = getWidenedType(exprType); - if (!(isTypeAssignableTo(targetType, widenedType))) { + // Permit 'number[] | "foo"' to be asserted to 'string'. + var bothAreStringLike = someConstituentTypeHasKind(targetType, 258 /* StringLike */) && + someConstituentTypeHasKind(widenedType, 258 /* StringLike */); + if (!bothAreStringLike && !(isTypeAssignableTo(targetType, widenedType))) { checkTypeAssignableTo(exprType, targetType, node, ts.Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other); } } @@ -21805,7 +24063,7 @@ var ts; 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.kind !== 190 /* OmittedExpression */) { if (element.name.kind === 69 /* Identifier */) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); } @@ -21853,6 +24111,13 @@ var ts; inferTypes(mapper.context, links.type, instantiateType(contextualType, mapper)); } } + function getReturnTypeFromJSDocComment(func) { + var returnTag = ts.getJSDocReturnTag(func); + if (returnTag && returnTag.typeExpression) { + return getTypeFromTypeNode(returnTag.typeExpression.type); + } + return undefined; + } function createPromiseType(promisedType) { // creates a `Promise` type where `T` is the promisedType argument var globalPromiseType = getGlobalPromiseType(); @@ -21870,7 +24135,7 @@ var ts; } var isAsync = ts.isAsyncFunctionLike(func); var type; - if (func.body.kind !== 192 /* Block */) { + if (func.body.kind !== 195 /* 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 @@ -21881,7 +24146,7 @@ var ts; } } else { - var types; + var types = void 0; var funcIsGenerator = !!func.asteriskToken; if (funcIsGenerator) { types = checkAndAggregateYieldOperandTypes(func.body, contextualMapper); @@ -21920,7 +24185,8 @@ var ts; } else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return unknownType; + // Defer to unioning the return types so we get a) downstream errors earlier and b) better Salsa experience + return getUnionType(types); } } if (funcIsGenerator) { @@ -21983,59 +24249,62 @@ var ts; }); 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) { + /** + * TypeScript Specification 1.0 (6.3) - July 2014 + * An explicitly typed function whose return type isn't the Void type, + * the Any type, or a union type containing the Void or Any type as a constituent + * 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. + * + * @param returnType - return type of the function, can be undefined if return type is not explicitly specified + */ + function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { if (!produceDiagnostics) { return; } - // Functions that return 'void' or 'any' don't need any return expressions. - if (returnType === voidType || isTypeAny(returnType)) { + // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. + if (returnType === voidType || isTypeAny(returnType) || (returnType && (returnType.flags & 16384 /* Union */) && someConstituentTypeHasKind(returnType, 1 /* Any */ | 16 /* Void */))) { 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 */) { + // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw + if (ts.nodeIsMissing(func.body) || func.body.kind !== 195 /* Block */ || !(func.flags & 524288 /* HasImplicitReturn */)) { 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; + var hasExplicitReturn = func.flags & 1048576 /* HasExplicitReturn */; + if (returnType && !hasExplicitReturn) { + // minimal check: function has syntactic return type annotation and no explicit return statements in the body + // this function does not conform to the specification. + // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present + error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + // If return type annotation is omitted check if function has any explicit return statements. + // If it does not have any - its inferred return type is void - don't do any checks. + // Otherwise get inferred return type from function body and report error only if it is not void / anytype + var inferredReturnType = hasExplicitReturn + ? getReturnTypeOfSignature(getSignatureFromDeclaration(func)) + : voidType; + if (inferredReturnType === voidType || isTypeAny(inferredReturnType)) { + return; + } + } + error(func.type || func, ts.Diagnostics.Not_all_code_paths_return_a_value); } - // 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)); + ts.Debug.assert(node.kind !== 144 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); // Grammar checking var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 173 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 176 /* FunctionExpression */) { checkGrammarForGenerator(node); } // The identityMapper object is used to indicate that function expressions are wildcards if (contextualMapper === identityMapper && isContextSensitive(node)) { + checkNodeDeferred(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); @@ -22065,28 +24334,23 @@ var ts; } if (!contextChecked) { checkSignatureDeclaration(node); + checkNodeDeferred(node); } } } - if (produceDiagnostics && node.kind !== 143 /* MethodDeclaration */ && node.kind !== 142 /* MethodSignature */) { + if (produceDiagnostics && node.kind !== 144 /* MethodDeclaration */ && node.kind !== 143 /* MethodSignature */) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } return type; } - function checkFunctionExpressionOrObjectLiteralMethodBody(node) { - ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { + ts.Debug.assert(node.kind !== 144 /* 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); + var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + if (!node.asteriskToken) { + // return is not necessary in the body of generators + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (node.body) { if (!node.type) { @@ -22097,7 +24361,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 192 /* Block */) { + if (node.body.kind === 195 /* Block */) { checkSourceElement(node.body); } else { @@ -22107,16 +24371,15 @@ var ts; // 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 (returnOrPromisedType) { 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); + checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } else { - checkTypeAssignableTo(exprType, returnType, node.body); + checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); } } - checkFunctionAndClassExpressionBodies(node.body); } } } @@ -22150,17 +24413,17 @@ var ts; // 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 */: { + case 169 /* 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 */: + case 170 /* ElementAccessExpression */: // old compiler doesn't check indexed access return true; - case 172 /* ParenthesizedExpression */: + case 175 /* ParenthesizedExpression */: return isReferenceOrErrorExpression(n.expression); default: return false; @@ -22169,21 +24432,21 @@ var ts; function isConstVariableReference(n) { switch (n.kind) { case 69 /* Identifier */: - case 166 /* PropertyAccessExpression */: { + case 169 /* PropertyAccessExpression */: { var symbol = findSymbol(n); - return symbol && (symbol.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 32768 /* Const */) !== 0; + return symbol && (symbol.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 16384 /* Const */) !== 0; } - case 167 /* ElementAccessExpression */: { + case 170 /* 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 prop && (prop.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(prop) & 16384 /* Const */) !== 0; } return false; } - case 172 /* ParenthesizedExpression */: + case 175 /* ParenthesizedExpression */: return isConstVariableReference(n.expression); default: return false; @@ -22264,8 +24527,8 @@ var ts; } if (type.flags & 49152 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var current = types_10[_i]; if (current.flags & kind) { return true; } @@ -22281,8 +24544,8 @@ var ts; } if (type.flags & 49152 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var current = types_11[_i]; if (!(current.flags & kind)) { return false; } @@ -22327,22 +24590,29 @@ var ts; } 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 + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var p = properties_3[_i]; + if (p.kind === 248 /* PropertyAssignment */ || p.kind === 249 /* ShorthandPropertyAssignment */) { var name_13 = p.name; + if (name_13.kind === 137 /* ComputedPropertyName */) { + checkComputedPropertyName(name_13); + } + if (isComputedNonLiteralName(name_13)) { + continue; + } + var text = getTextOfPropertyName(name_13); var type = isTypeAny(sourceType) ? sourceType - : getTypeOfPropertyOfType(sourceType, name_13.text) || - isNumericLiteralName(name_13.text) && getIndexTypeOfType(sourceType, 1 /* Number */) || + : getTypeOfPropertyOfType(sourceType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(sourceType, 1 /* Number */) || getIndexTypeOfType(sourceType, 0 /* String */); if (type) { - if (p.kind === 246 /* ShorthandPropertyAssignment */) { + if (p.kind === 249 /* ShorthandPropertyAssignment */) { checkDestructuringAssignment(p, type); } else { - checkDestructuringAssignment(p.initializer || name_13, type); + // non-shorthand property assignments should always have initializers + checkDestructuringAssignment(p.initializer, type); } } else { @@ -22363,8 +24633,8 @@ var ts; 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 */) { + if (e.kind !== 190 /* OmittedExpression */) { + if (e.kind !== 188 /* SpreadElementExpression */) { var propName = "" + i; var type = isTypeAny(sourceType) ? sourceType @@ -22389,7 +24659,7 @@ var ts; } else { var restExpression = e.expression; - if (restExpression.kind === 181 /* BinaryExpression */ && restExpression.operatorToken.kind === 56 /* EqualsToken */) { + if (restExpression.kind === 184 /* BinaryExpression */ && restExpression.operatorToken.kind === 56 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { @@ -22403,7 +24673,7 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, contextualMapper) { var target; - if (exprOrAssignment.kind === 246 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 249 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, contextualMapper); @@ -22413,14 +24683,14 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 181 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { + if (target.kind === 184 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { checkBinaryExpression(target, contextualMapper); target = target.left; } - if (target.kind === 165 /* ObjectLiteralExpression */) { + if (target.kind === 168 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType, contextualMapper); } - if (target.kind === 164 /* ArrayLiteralExpression */) { + if (target.kind === 167 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } return checkReferenceAssignment(target, sourceType, contextualMapper); @@ -22437,7 +24707,7 @@ var ts; } function checkBinaryLikeExpression(left, operatorToken, right, contextualMapper, errorNode) { var operator = operatorToken.kind; - if (operator === 56 /* EqualsToken */ && (left.kind === 165 /* ObjectLiteralExpression */ || left.kind === 164 /* ArrayLiteralExpression */)) { + if (operator === 56 /* EqualsToken */ && (left.kind === 168 /* ObjectLiteralExpression */ || left.kind === 167 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(left, checkExpression(right, contextualMapper), contextualMapper); } var leftType = checkExpression(left, contextualMapper); @@ -22475,7 +24745,7 @@ var ts; leftType = rightType; if (rightType.flags & (32 /* Undefined */ | 64 /* Null */)) rightType = leftType; - var suggestedOperator; + var suggestedOperator = void 0; // 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 */) && @@ -22502,7 +24772,7 @@ var ts; leftType = rightType; if (rightType.flags & (32 /* Undefined */ | 64 /* Null */)) rightType = leftType; - var resultType; + var resultType = void 0; 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. @@ -22543,6 +24813,10 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: + // Permit 'number[] | "foo"' to be asserted to 'string'. + if (someConstituentTypeHasKind(leftType, 258 /* StringLike */) && someConstituentTypeHasKind(rightType, 258 /* StringLike */)) { + return booleanType; + } if (!isTypeAssignableTo(leftType, rightType) && !isTypeAssignableTo(rightType, leftType)) { reportOperatorError(); } @@ -22638,7 +24912,7 @@ var ts; // we are in a yield context. if (func && func.asteriskToken) { var expressionType = checkExpressionCached(node.expression, /*contextualMapper*/ undefined); - var expressionElementType; + var expressionElementType = void 0; var nodeIsYieldStar = !!node.asteriskToken; if (nodeIsYieldStar) { expressionElementType = checkElementTypeOfIterable(expressionType, node.expression); @@ -22666,6 +24940,13 @@ var ts; var type2 = checkExpression(node.whenFalse, contextualMapper); return getUnionType([type1, type2]); } + function checkStringLiteralExpression(node) { + var contextualType = getContextualType(node); + if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { + return getStringLiteralTypeForText(node.text); + } + return stringType; + } 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. @@ -22695,7 +24976,7 @@ var ts; // 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 */) { + if (node.name.kind === 137 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpression(node.initializer, contextualMapper); @@ -22706,7 +24987,7 @@ var ts; // 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 */) { + if (node.name.kind === 137 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); @@ -22716,7 +24997,7 @@ var ts; if (isInferentialContext(contextualMapper)) { var signature = getSingleCallSignature(type); if (signature && signature.typeParameters) { - var contextualType = getContextualType(node); + var contextualType = getApparentTypeOfContextualType(node); if (contextualType) { var contextualSignature = getSingleCallSignature(contextualType); if (contextualSignature && !contextualSignature.typeParameters) { @@ -22736,7 +25017,7 @@ var ts; // contextually typed function and arrow expressions in the initial phase. function checkExpression(node, contextualMapper) { var type; - if (node.kind === 135 /* QualifiedName */) { + if (node.kind === 136 /* QualifiedName */) { type = checkQualifiedName(node); } else { @@ -22748,9 +25029,9 @@ var ts; // - '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)); + var ok = (node.parent.kind === 169 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 170 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 69 /* Identifier */ || node.kind === 136 /* 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); } @@ -22777,65 +25058,66 @@ var ts; return booleanType; case 8 /* NumericLiteral */: return checkNumericLiteral(node); - case 183 /* TemplateExpression */: + case 186 /* TemplateExpression */: return checkTemplateExpression(node); case 9 /* StringLiteral */: + return checkStringLiteralExpression(node); case 11 /* NoSubstitutionTemplateLiteral */: return stringType; case 10 /* RegularExpressionLiteral */: return globalRegExpType; - case 164 /* ArrayLiteralExpression */: + case 167 /* ArrayLiteralExpression */: return checkArrayLiteral(node, contextualMapper); - case 165 /* ObjectLiteralExpression */: + case 168 /* ObjectLiteralExpression */: return checkObjectLiteral(node, contextualMapper); - case 166 /* PropertyAccessExpression */: + case 169 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 167 /* ElementAccessExpression */: + case 170 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 171 /* CallExpression */: + case 172 /* NewExpression */: return checkCallExpression(node); - case 170 /* TaggedTemplateExpression */: + case 173 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 172 /* ParenthesizedExpression */: + case 175 /* ParenthesizedExpression */: return checkExpression(node.expression, contextualMapper); - case 186 /* ClassExpression */: + case 189 /* ClassExpression */: return checkClassExpression(node); - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 176 /* FunctionExpression */: + case 177 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); - case 176 /* TypeOfExpression */: + case 179 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 171 /* TypeAssertionExpression */: - case 189 /* AsExpression */: + case 174 /* TypeAssertionExpression */: + case 192 /* AsExpression */: return checkAssertion(node); - case 175 /* DeleteExpression */: + case 178 /* DeleteExpression */: return checkDeleteExpression(node); - case 177 /* VoidExpression */: + case 180 /* VoidExpression */: return checkVoidExpression(node); - case 178 /* AwaitExpression */: + case 181 /* AwaitExpression */: return checkAwaitExpression(node); - case 179 /* PrefixUnaryExpression */: + case 182 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 180 /* PostfixUnaryExpression */: + case 183 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 181 /* BinaryExpression */: + case 184 /* BinaryExpression */: return checkBinaryExpression(node, contextualMapper); - case 182 /* ConditionalExpression */: + case 185 /* ConditionalExpression */: return checkConditionalExpression(node, contextualMapper); - case 185 /* SpreadElementExpression */: + case 188 /* SpreadElementExpression */: return checkSpreadElementExpression(node, contextualMapper); - case 187 /* OmittedExpression */: + case 190 /* OmittedExpression */: return undefinedType; - case 184 /* YieldExpression */: + case 187 /* YieldExpression */: return checkYieldExpression(node); - case 240 /* JsxExpression */: + case 243 /* JsxExpression */: return checkJsxExpression(node); - case 233 /* JsxElement */: + case 236 /* JsxElement */: return checkJsxElement(node); - case 234 /* JsxSelfClosingElement */: + case 237 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node); - case 235 /* JsxOpeningElement */: + case 238 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } return unknownType; @@ -22847,11 +25129,10 @@ var ts; grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); } checkSourceElement(node.constraint); + getConstraintOfTypeParameter(getDeclaredTypeOfTypeParameter(getSymbolOfNode(node))); 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 @@ -22862,9 +25143,9 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (node.flags & 112 /* AccessibilityModifier */) { + if (node.flags & 56 /* AccessibilityModifier */) { func = ts.getContainingFunction(node); - if (!(func.kind === 144 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 145 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -22881,9 +25162,9 @@ var ts; if (!node.asteriskToken || !node.body) { return false; } - return node.kind === 143 /* MethodDeclaration */ || - node.kind === 213 /* FunctionDeclaration */ || - node.kind === 173 /* FunctionExpression */; + return node.kind === 144 /* MethodDeclaration */ || + node.kind === 216 /* FunctionDeclaration */ || + node.kind === 176 /* FunctionExpression */; } function getTypePredicateParameterIndex(parameterList, parameter) { if (parameterList) { @@ -22897,91 +25178,100 @@ var ts; } return -1; } - function isInLegalTypePredicatePosition(node) { + function checkTypePredicate(node) { + var parent = getTypePredicateParent(node); + if (!parent) { + // The parent must not be valid. + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + return; + } + var typePredicate = getSignatureFromDeclaration(parent).typePredicate; + if (!typePredicate) { + return; + } + var parameterName = node.parameterName; + if (ts.isThisTypePredicate(typePredicate)) { + getTypeFromThisTypeNode(parameterName); + } + else { + if (typePredicate.parameterIndex >= 0) { + if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type); + } + } + else if (parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { + var name_14 = _a[_i].name; + if (ts.isBindingPattern(name_14) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_14, parameterName, typePredicate.parameterName)) { + hasReportedError = true; + break; + } + } + if (!hasReportedError) { + error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + } + function getTypePredicateParent(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; + case 177 /* ArrowFunction */: + case 148 /* CallSignature */: + case 216 /* FunctionDeclaration */: + case 176 /* FunctionExpression */: + case 153 /* FunctionType */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + var parent_7 = node.parent; + if (node === parent_7.type) { + return parent_7; + } + } + } + function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var name_15 = _a[_i].name; + if (name_15.kind === 69 /* Identifier */ && + name_15.text === predicateVariableName) { + error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); + return true; + } + else if (name_15.kind === 165 /* ArrayBindingPattern */ || + name_15.kind === 164 /* ObjectBindingPattern */) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_15, predicateVariableNode, predicateVariableName)) { + return true; + } + } } - return false; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 149 /* IndexSignature */) { + if (node.kind === 150 /* 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 */) { + else if (node.kind === 153 /* FunctionType */ || node.kind === 216 /* FunctionDeclaration */ || node.kind === 154 /* ConstructorType */ || + node.kind === 148 /* CallSignature */ || node.kind === 145 /* Constructor */ || + node.kind === 149 /* 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); - } + checkSourceElement(node.type); } if (produceDiagnostics) { checkCollisionWithArgumentsInGeneratedCode(node); if (compilerOptions.noImplicitAny && !node.type) { switch (node.kind) { - case 148 /* ConstructSignature */: + case 149 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 147 /* CallSignature */: + case 148 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -23004,12 +25294,15 @@ var ts; checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); } } + else if (ts.isAsyncFunctionLike(node)) { + checkAsyncFunctionReturnType(node); + } } } checkSpecializedSignatureDeclaration(node); } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 215 /* InterfaceDeclaration */) { + if (node.kind === 218 /* 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 @@ -23059,10 +25352,10 @@ var ts; // Grammar checking checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration - checkFunctionLikeDeclaration(node); + checkFunctionOrMethodDeclaration(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) { + if (node.flags & 128 /* Abstract */ && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -23085,35 +25378,17 @@ var ts; 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 */) { + else if (n.kind !== 176 /* FunctionExpression */ && n.kind !== 216 /* FunctionDeclaration */) { ts.forEachChild(n, markThisReferencesAsErrors); } } function isInstancePropertyWithInitializer(n) { - return n.kind === 141 /* PropertyDeclaration */ && - !(n.flags & 128 /* Static */) && + return n.kind === 142 /* PropertyDeclaration */ && + !(n.flags & 64 /* Static */) && !!n.initializer; } // TS 1.0 spec (April 2014): 8.3.2 @@ -23121,12 +25396,11 @@ var ts; // 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); + var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + var superCall = getSuperCallInConstructor(node); + if (superCall) { + if (classExtendsNull) { + error(superCall, 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: @@ -23134,15 +25408,15 @@ var ts; // - 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 */); }); + ts.forEach(node.parameters, function (p) { return p.flags & (8 /* Public */ | 16 /* Private */ | 32 /* 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)) { + var superCallStatement = void 0; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; + if (statement.kind === 198 /* ExpressionStatement */ && ts.isSuperCallExpression(statement.expression)) { superCallStatement = statement; break; } @@ -23153,13 +25427,9 @@ var ts; 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) { + else if (!classExtendsNull) { error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); } } @@ -23168,18 +25438,33 @@ var ts; 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); + checkDecorators(node); + checkSignatureDeclaration(node); + if (node.kind === 146 /* GetAccessor */) { + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 524288 /* HasImplicitReturn */)) { + if (node.flags & 1048576 /* HasExplicitReturn */) { + if (compilerOptions.noImplicitReturns) { + error(node.name, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + else { + error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); + } } } + // 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 === 137 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } 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 otherKind = node.kind === 146 /* GetAccessor */ ? 147 /* SetAccessor */ : 146 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if (((node.flags & 112 /* AccessibilityModifier */) !== (otherAccessor.flags & 112 /* AccessibilityModifier */))) { + if (((node.flags & 56 /* AccessibilityModifier */) !== (otherAccessor.flags & 56 /* AccessibilityModifier */))) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } var currentAccessorType = getAnnotatedAccessorType(node); @@ -23195,18 +25480,32 @@ var ts; } getTypeOfAccessors(getSymbolOfNode(node)); } - checkFunctionLikeDeclaration(node); + if (node.parent.kind !== 168 /* ObjectLiteralExpression */) { + checkSourceElement(node.body); + } + else { + checkNodeDeferred(node); + } + } + function checkAccessorDeferred(node) { + checkSourceElement(node.body); } function checkMissingDeclaration(node) { checkDecorators(node); } - function checkTypeArgumentConstraints(typeParameters, typeArguments) { + function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) { + var typeArguments; + var mapper; var result = true; for (var i = 0; i < typeParameters.length; i++) { var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { + if (!typeArguments) { + typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + mapper = createTypeMapper(typeParameters, typeArguments); + } var typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(getTypeFromTypeNode(typeArgument), constraint, typeArgument, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } return result; @@ -23250,7 +25549,7 @@ var ts; ts.forEach(node.types, checkSourceElement); } function isPrivateWithinAmbient(node) { - return (node.flags & 32 /* Private */) && ts.isInAmbientContext(node); + return (node.flags & 16 /* Private */) && ts.isInAmbientContext(node); } function checkSpecializedSignatureDeclaration(signatureDeclarationNode) { if (!produceDiagnostics) { @@ -23272,9 +25571,9 @@ var ts; 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 */; + if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === 218 /* InterfaceDeclaration */) { + ts.Debug.assert(signatureDeclarationNode.kind === 148 /* CallSignature */ || signatureDeclarationNode.kind === 149 /* ConstructSignature */); + var signatureKind = signatureDeclarationNode.kind === 148 /* CallSignature */ ? 0 /* Call */ : 1 /* Construct */; var containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); var containingType = getDeclaredTypeOfSymbol(containingSymbol); signaturesToCheck = getSignaturesOfType(containingType, signatureKind); @@ -23282,9 +25581,9 @@ var ts; else { signaturesToCheck = getSignaturesOfSymbol(getSymbolOfNode(signatureDeclarationNode)); } - for (var _i = 0; _i < signaturesToCheck.length; _i++) { - var otherSignature = signaturesToCheck[_i]; - if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature)) { + for (var _i = 0, signaturesToCheck_1 = signaturesToCheck; _i < signaturesToCheck_1.length; _i++) { + var otherSignature = signaturesToCheck_1[_i]; + if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature, /*ignoreReturnTypes*/ false)) { return; } } @@ -23294,15 +25593,15 @@ var ts; 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 */ && + if (n.parent.kind !== 218 /* InterfaceDeclaration */ && + n.parent.kind !== 217 /* ClassDeclaration */ && + n.parent.kind !== 189 /* ClassExpression */ && ts.isInAmbientContext(n)) { - if (!(flags & 2 /* Ambient */)) { + if (!(flags & 4 /* Ambient */)) { // It is nested in an ambient context, which means it is automatically exported - flags |= 1 /* Export */; + flags |= 2 /* Export */; } - flags |= 2 /* Ambient */; + flags |= 4 /* Ambient */; } return flags & flagsToCheck; } @@ -23324,19 +25623,19 @@ var ts; // deviations, we XOR someOverloadFlags with allOverloadFlags var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; if (someButNotAllOverloadFlags !== 0) { - var canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); + var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); ts.forEach(overloads, function (o) { - var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; - if (deviation & 1 /* Export */) { + var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; + if (deviation & 2 /* Export */) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_not_exported); } - else if (deviation & 2 /* Ambient */) { + else if (deviation & 4 /* Ambient */) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } - else if (deviation & (32 /* Private */ | 64 /* Protected */)) { + else if (deviation & (16 /* Private */ | 32 /* Protected */)) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } - else if (deviation & 256 /* Abstract */) { + else if (deviation & 128 /* Abstract */) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_not_abstract); } }); @@ -23344,16 +25643,16 @@ var ts; } function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { if (someHaveQuestionToken !== allHaveQuestionToken) { - var canonicalHasQuestionToken = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); + var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); ts.forEach(overloads, function (o) { - var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken; + var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; 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 flagsToCheck = 2 /* Export */ | 4 /* Ambient */ | 16 /* Private */ | 32 /* Protected */ | 128 /* Abstract */; var someNodeFlags = 0; var allNodeFlags = flagsToCheck; var someHaveQuestionToken = false; @@ -23377,19 +25676,21 @@ var ts; seen = c === node; } }); - if (subsequentNode) { + // We may be here because of some extra junk between overloads that could not be parsed into a valid node. + // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here. + if (subsequentNode && subsequentNode.pos === node.end) { 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 */); + var reportError = (node.kind === 144 /* MethodDeclaration */ || node.kind === 143 /* MethodSignature */) && + (node.flags & 64 /* Static */) !== (subsequentNode.flags & 64 /* 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 + // 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; + var diagnostic = node.flags & 64 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); } return; @@ -23407,7 +25708,7 @@ var ts; else { // Report different errors regarding non-consecutive blocks of declarations depending on whether // the node in question is abstract. - if (node.flags & 256 /* Abstract */) { + if (node.flags & 128 /* Abstract */) { error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); } else { @@ -23420,11 +25721,11 @@ var ts; 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]; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 215 /* InterfaceDeclaration */ || node.parent.kind === 155 /* TypeLiteral */ || inAmbientContext; + var inAmbientContextOrInterface = node.parent.kind === 218 /* InterfaceDeclaration */ || node.parent.kind === 156 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -23435,7 +25736,7 @@ var ts; // 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 */) { + if (node.kind === 216 /* FunctionDeclaration */ || node.kind === 144 /* MethodDeclaration */ || node.kind === 143 /* MethodSignature */ || node.kind === 145 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -23478,7 +25779,7 @@ var ts; } // Abstract methods can't have an implementation -- in particular, they don't need one. if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(lastSeenNonAmbientDeclaration.flags & 256 /* Abstract */)) { + !(lastSeenNonAmbientDeclaration.flags & 128 /* Abstract */)) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { @@ -23504,9 +25805,9 @@ var ts; // 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)) { + for (var _a = 0, signatures_3 = signatures; _a < signatures_3.length; _a++) { + var signature = signatures_3[_a]; + if (!signature.hasStringLiterals && !isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; } @@ -23542,9 +25843,9 @@ var ts; 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 */) { + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 2 /* Export */ | 512 /* Default */); + if (effectiveDeclarationFlags & 2 /* Export */) { + if (effectiveDeclarationFlags & 512 /* Default */) { defaultExportedDeclarationSpaces |= declarationSpaces; } else { @@ -23575,20 +25876,20 @@ var ts; } function getDeclarationSpaces(d) { switch (d.kind) { - case 215 /* InterfaceDeclaration */: + case 218 /* InterfaceDeclaration */: return 2097152 /* ExportType */; - case 218 /* ModuleDeclaration */: - return d.name.kind === 9 /* StringLiteral */ || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ + case 221 /* ModuleDeclaration */: + return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4194304 /* ExportNamespace */ | 1048576 /* ExportValue */ : 4194304 /* ExportNamespace */; - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: + case 217 /* ClassDeclaration */: + case 220 /* EnumDeclaration */: return 2097152 /* ExportType */ | 1048576 /* ExportValue */; - case 221 /* ImportEqualsDeclaration */: - var result = 0; + case 224 /* ImportEqualsDeclaration */: + var result_2 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result |= getDeclarationSpaces(d); }); - return result; + ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); + return result_2; default: return 1048576 /* ExportValue */; } @@ -23745,6 +26046,33 @@ var ts; } } } + /** + * Checks that the return type provided is an instantiation of the global Promise type + * and returns the awaited type of the return type. + * + * @param returnType The return type of a FunctionLikeDeclaration + * @param location The node on which to report the error. + */ + function checkCorrectPromiseType(returnType, location) { + if (returnType === unknownType) { + // The return type already had some other error, so we ignore and return + // the unknown type. + return unknownType; + } + var globalPromiseType = getGlobalPromiseType(); + if (globalPromiseType === emptyGenericType + || globalPromiseType === getTargetType(returnType)) { + // Either we couldn't resolve the global promise type, which would have already + // reported an error, or we could resolve it and the return type is a valid type + // reference to the global type. In either case, we return the awaited type for + // the return type. + return checkAwaitedType(returnType, location, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + } + // The promise type was not a valid type reference to the global promise type, so we + // report an error and return the unknown type. + error(location, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return unknownType; + } /** * Checks the return type of an async function to ensure it is a compatible * Promise implementation. @@ -23759,6 +26087,10 @@ var ts; * callable `then` signature. */ function checkAsyncFunctionReturnType(node) { + if (compilerOptions.noCustomAsyncPromise && languageVersion >= 2 /* ES6 */) { + var returnType = getTypeFromTypeNode(node.type); + return checkCorrectPromiseType(returnType, node.type); + } var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); if (globalPromiseConstructorLikeType === emptyObjectType) { // If we couldn't resolve the global PromiseConstructorLike type we cannot verify @@ -23805,6 +26137,8 @@ var ts; error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); return unknownType; } + // If the Promise constructor, resolved locally, is an alias symbol we should mark it as referenced. + checkReturnTypeAnnotationAsExpression(node); // 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)) { @@ -23812,10 +26146,10 @@ var ts; } // 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 */); + var promiseNameOrNamespaceRoot = getFirstIdentifier(promiseName); + var rootSymbol = getSymbol(node.locals, promiseNameOrNamespaceRoot.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)); + error(rootSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, promiseNameOrNamespaceRoot.text, getFullyQualifiedName(promiseConstructor)); return unknownType; } // Get and return the awaited type of the return type. @@ -23832,22 +26166,22 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 214 /* ClassDeclaration */: + case 217 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 138 /* Parameter */: + case 139 /* 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 */: + case 142 /* 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 */: + case 144 /* MethodDeclaration */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -23860,9 +26194,9 @@ var ts; // 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 */) { + if (node && node.kind === 152 /* TypeReference */) { var root = getFirstIdentifier(node.typeName); - var meaning = root.parent.kind === 151 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */; + var meaning = root.parent.kind === 152 /* 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 @@ -23880,23 +26214,10 @@ var ts; * 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; - } + checkTypeNodeAsExpression(node.type); + } + function checkReturnTypeAnnotationAsExpression(node) { + checkTypeNodeAsExpression(node.type); } /** Checks the type annotation of the parameters of a function/method or the constructor of a class as expressions */ function checkParameterTypeAnnotationsAsExpressions(node) { @@ -23917,53 +26238,48 @@ var ts; 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); + error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_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 */: + case 217 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { checkParameterTypeAnnotationsAsExpressions(constructor); } break; - case 143 /* MethodDeclaration */: + case 144 /* MethodDeclaration */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: checkParameterTypeAnnotationsAsExpressions(node); - // fall-through - case 146 /* SetAccessor */: - case 145 /* GetAccessor */: - case 141 /* PropertyDeclaration */: - case 138 /* Parameter */: + checkReturnTypeAnnotationAsExpression(node); + break; + case 142 /* PropertyDeclaration */: + case 139 /* 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); + checkFunctionOrMethodDeclaration(node) || checkGrammarForGenerator(node); checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } - function checkFunctionLikeDeclaration(node) { + function checkFunctionOrMethodDeclaration(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 */) { + if (node.name && node.name.kind === 137 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); @@ -23974,7 +26290,13 @@ var ts; // - 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); + // Since the javascript won't do semantic analysis like typescript, + // if the javascript file comes before the typescript file and both contain same name functions, + // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. + var firstDeclaration = ts.forEach(localSymbol.declarations, + // Get first non javascript function declaration + function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)) ? + declaration : undefined; }); // Only type check the symbol once if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); @@ -23988,13 +26310,9 @@ var ts; } } 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 (!node.asteriskToken) { + var returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } 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 @@ -24012,13 +26330,10 @@ var ts; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 192 /* Block */) { + if (node.kind === 195 /* 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 @@ -24035,12 +26350,12 @@ var ts; 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 */) { + if (node.kind === 142 /* PropertyDeclaration */ || + node.kind === 141 /* PropertySignature */ || + node.kind === 144 /* MethodDeclaration */ || + node.kind === 143 /* MethodSignature */ || + node.kind === 146 /* GetAccessor */ || + node.kind === 147 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } @@ -24049,7 +26364,7 @@ var ts; return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 138 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 139 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } @@ -24102,16 +26417,34 @@ var ts; return; } // Uninstantiated modules shouldnt do this check - if (node.kind === 218 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + if (node.kind === 221 /* 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 (parent.kind === 251 /* SourceFile */ && ts.isExternalOrCommonJsModule(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 checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { + if (!compilerOptions.noCustomAsyncPromise) { + return; + } + if (!needCollisionCheckForIdentifier(node, name, "Promise")) { + return; + } + // Uninstantiated modules shouldnt do this check + if (node.kind === 221 /* 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 === 251 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 33554432 /* HasAsyncFunctions */) { + // If the declaration happens to be in external module, report error that Promise is a reserved identifier. + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } function checkVarDeclaredNamesNotShadowed(node) { // - ScriptBody : StatementList // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList @@ -24125,24 +26458,24 @@ var ts; // 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 + // Only consider declarations with initializers, uninitialized const declarations will not // step on a let/const variable. - // Do not consider let and const declarations, as duplicate block-scoped declarations + // Do not consider const 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 + // We are only looking for const 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' + // const 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)) { + if ((ts.getCombinedNodeFlags(node) & 24576 /* 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) { + if (node.kind === 214 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -24151,25 +26484,25 @@ var ts; 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 + if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 24576 /* BlockScoped */) { + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 215 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 196 /* 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 */); + (container.kind === 195 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 222 /* ModuleBlock */ || + container.kind === 221 /* ModuleDeclaration */ || + container.kind === 251 /* 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); + var name_16 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_16, name_16); } } } @@ -24177,7 +26510,7 @@ var ts; } // 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 */) { + if (ts.getRootDeclaration(node).kind !== 139 /* Parameter */) { return; } var func = ts.getContainingFunction(node); @@ -24188,7 +26521,7 @@ var ts; // 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.kind === 139 /* Parameter */) { if (referencedSymbol.valueDeclaration === node) { error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); return; @@ -24214,24 +26547,31 @@ var ts; // 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 */) { + if (node.name.kind === 137 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } + if (node.kind === 166 /* BindingElement */) { + // check computed properties inside property names of binding elements + if (node.propertyName && node.propertyName.kind === 137 /* ComputedPropertyName */) { + checkComputedPropertyName(node.propertyName); + } + } // 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)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 139 /* 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) { + // Don't validate for-in initializer as it is already an error + if (node.initializer && node.parent.parent.kind !== 203 /* ForInStatement */) { checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); checkParameterInitializer(node); } @@ -24241,7 +26581,8 @@ var ts; var type = getTypeOfVariableOrParameterOrProperty(symbol); if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer - if (node.initializer) { + // Don't validate for-in initializer as it is already an error + if (node.initializer && node.parent.parent.kind !== 203 /* ForInStatement */) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined); checkParameterInitializer(node); } @@ -24257,15 +26598,16 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); } } - if (node.kind !== 141 /* PropertyDeclaration */ && node.kind !== 140 /* PropertySignature */) { + if (node.kind !== 142 /* PropertyDeclaration */ && node.kind !== 141 /* 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 */) { + if (node.kind === 214 /* VariableDeclaration */ || node.kind === 166 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } function checkVariableDeclaration(node) { @@ -24283,7 +26625,7 @@ var ts; } 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 (node.modifiers && node.parent.kind === 168 /* ObjectLiteralExpression */) { if (ts.isAsyncFunctionLike(node)) { if (node.modifiers.length > 1) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -24304,6 +26646,9 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); + if (node.thenStatement.kind === 197 /* EmptyStatement */) { + error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); + } checkSourceElement(node.elseStatement); } function checkDoStatement(node) { @@ -24321,12 +26666,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 215 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 215 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -24346,14 +26691,14 @@ var ts; // 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 */) { + if (node.initializer.kind === 215 /* 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 */) { + if (varExpr.kind === 167 /* ArrayLiteralExpression */ || varExpr.kind === 168 /* 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. @@ -24382,7 +26727,7 @@ var ts; // 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 */) { + if (node.initializer.kind === 215 /* 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); @@ -24396,7 +26741,7 @@ var ts; // 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 */) { + if (varExpr.kind === 167 /* ArrayLiteralExpression */ || varExpr.kind === 168 /* 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 */)) { @@ -24592,7 +26937,13 @@ var ts; 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 arrayType = arrayOrStringType; + if (arrayOrStringType.flags & 16384 /* Union */) { + arrayType = getUnionType(ts.filter(arrayOrStringType.types, function (t) { return !(t.flags & 258 /* StringLike */); })); + } + else if (arrayOrStringType.flags & 258 /* StringLike */) { + arrayType = emptyUnionType; + } var hasStringConstituent = arrayOrStringType !== arrayType; var reportedError = false; if (hasStringConstituent) { @@ -24635,7 +26986,7 @@ var ts; // TODO: Check that target label is valid } function isGetAccessorWithAnnotatatedSetAccessor(node) { - return !!(node.kind === 145 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 146 /* SetAccessor */))); + return !!(node.kind === 146 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 147 /* SetAccessor */))); } function checkReturnStatement(node) { // Grammar checking @@ -24658,15 +27009,15 @@ var ts; // for generators. return; } - if (func.kind === 146 /* SetAccessor */) { + if (func.kind === 147 /* SetAccessor */) { error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); } - else if (func.kind === 144 /* Constructor */) { - if (!isTypeAssignableTo(exprType, returnType)) { + else if (func.kind === 145 /* Constructor */) { + if (!checkTypeAssignableTo(exprType, returnType, node.expression)) { 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) { + else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func)) { 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); @@ -24700,9 +27051,10 @@ var ts; var firstDefaultClause; var hasDuplicateDefaultClause = false; var expressionType = checkExpression(node.expression); + var expressionTypeIsStringLike = someConstituentTypeHasKind(expressionType, 258 /* StringLike */); 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 (clause.kind === 245 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -24714,13 +27066,17 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 241 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 244 /* 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 + var expressionTypeIsAssignableToCaseType = + // Permit 'number[] | "foo"' to be asserted to 'string'. + (expressionTypeIsStringLike && someConstituentTypeHasKind(caseType, 258 /* StringLike */)) || + isTypeAssignableTo(expressionType, caseType); + if (!expressionTypeIsAssignableToCaseType) { + // 'expressionType is not assignable to caseType', try the reversed check and report errors if it fails checkTypeAssignableTo(caseType, expressionType, caseClause.expression, /*headMessage*/ undefined); } } @@ -24735,7 +27091,7 @@ var ts; if (ts.isFunctionLike(current)) { break; } - if (current.kind === 207 /* LabeledStatement */ && current.label.text === node.label.text) { + if (current.kind === 210 /* 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; @@ -24809,7 +27165,7 @@ var ts; // 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)) { + if (!(member.flags & 64 /* 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 */); @@ -24840,7 +27196,7 @@ var ts; // 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) { + if (prop.valueDeclaration.name.kind === 137 /* ComputedPropertyName */ || prop.parent === containingType.symbol) { errorNode = prop.valueDeclaration; } else if (indexDeclaration) { @@ -24892,10 +27248,14 @@ var ts; } function checkClassExpression(node) { checkClassLikeDeclaration(node); + checkNodeDeferred(node); return getTypeOfSymbol(getSymbolOfNode(node)); } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + } function checkClassDeclaration(node) { - if (!node.name && !(node.flags & 1024 /* Default */)) { + if (!node.name && !(node.flags & 512 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); @@ -24908,6 +27268,7 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } checkTypeParameters(node.typeParameters); checkExportsOnMergedDeclarations(node); @@ -24917,10 +27278,9 @@ var ts; 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 baseType_1 = baseTypes[0]; var staticBaseType = getBaseConstructorTypeOfClass(type); checkSourceElement(baseTypeNode.expression); if (baseTypeNode.typeArguments) { @@ -24932,7 +27292,7 @@ var ts; } } } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, 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 @@ -24940,17 +27300,17 @@ var ts; // 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; })) { + if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } - checkKindsOfPropertyMemberOverrides(type, baseType); + checkKindsOfPropertyMemberOverrides(type, baseType_1); } } var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); if (implementedTypeNodes) { - for (var _b = 0; _b < implementedTypeNodes.length; _b++) { - var typeRefNode = implementedTypeNodes[_b]; + for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { + var typeRefNode = implementedTypeNodes_1[_b]; if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } @@ -24998,8 +27358,8 @@ var ts; // 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]; + for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; var base = getTargetSymbol(baseProperty); if (base.flags & 134217728 /* Prototype */) { continue; @@ -25017,8 +27377,8 @@ var ts; // 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 */) { + if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(derivedClassDecl.flags & 128 /* Abstract */))) { + if (derivedClassDecl.kind === 189 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -25029,11 +27389,11 @@ var ts; else { // derived overrides base. var derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); - if ((baseDeclarationFlags & 32 /* Private */) || (derivedDeclarationFlags & 32 /* Private */)) { + if ((baseDeclarationFlags & 16 /* Private */) || (derivedDeclarationFlags & 16 /* Private */)) { // either base or derived property is private - not override, skip it continue; } - if ((baseDeclarationFlags & 128 /* Static */) !== (derivedDeclarationFlags & 128 /* Static */)) { + if ((baseDeclarationFlags & 64 /* Static */) !== (derivedDeclarationFlags & 64 /* Static */)) { // value of 'static' is not the same for properties - not override, skip it continue; } @@ -25066,7 +27426,7 @@ var ts; } } function isAccessor(kind) { - return kind === 145 /* GetAccessor */ || kind === 146 /* SetAccessor */; + return kind === 146 /* GetAccessor */ || kind === 147 /* SetAccessor */; } function areTypeParametersIdentical(list1, list2) { if (!list1 && !list2) { @@ -25104,11 +27464,11 @@ var ts; 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]; + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0; _a < properties.length; _a++) { - var prop = properties[_a]; + for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { + var prop = properties_4[_a]; if (!ts.hasProperty(seen, prop.name)) { seen[prop.name] = { prop: prop, containingType: base }; } @@ -25136,7 +27496,7 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 215 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 218 /* 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); @@ -25175,7 +27535,7 @@ var ts; } function computeEnumMemberValues(node) { var nodeLinks = getNodeLinks(node); - if (!(nodeLinks.flags & 8192 /* EnumValuesComputed */)) { + if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) { var enumSymbol = getSymbolOfNode(node); var enumType = getDeclaredTypeOfSymbol(enumSymbol); var autoValue = 0; // set to undefined when enum member is non-constant @@ -25183,11 +27543,14 @@ var ts; 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 */) { + if (isComputedNonLiteralName(member.name)) { 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); + else { + var text = getTextOfPropertyName(member.name); + if (isNumericLiteralName(text)) { + error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); + } } var previousEnumMemberIsNonConstant = autoValue === undefined; var initializer = member.initializer; @@ -25207,10 +27570,11 @@ var ts; error(member.name, ts.Diagnostics.Enum_member_must_have_initializer); } if (autoValue !== undefined) { - getNodeLinks(member).enumMemberValue = autoValue++; + getNodeLinks(member).enumMemberValue = autoValue; + autoValue++; } } - nodeLinks.flags |= 8192 /* EnumValuesComputed */; + nodeLinks.flags |= 16384 /* EnumValuesComputed */; } function computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient) { // Controls if error should be reported after evaluation of constant value is completed @@ -25242,7 +27606,7 @@ var ts; return value; function evalConstant(e) { switch (e.kind) { - case 179 /* PrefixUnaryExpression */: + case 182 /* PrefixUnaryExpression */: var value_1 = evalConstant(e.operand); if (value_1 === undefined) { return undefined; @@ -25253,7 +27617,7 @@ var ts; case 50 /* TildeToken */: return ~value_1; } return undefined; - case 181 /* BinaryExpression */: + case 184 /* BinaryExpression */: var left = evalConstant(e.left); if (left === undefined) { return undefined; @@ -25278,15 +27642,15 @@ var ts; return undefined; case 8 /* NumericLiteral */: return +e.text; - case 172 /* ParenthesizedExpression */: + case 175 /* ParenthesizedExpression */: return evalConstant(e.expression); case 69 /* Identifier */: - case 167 /* ElementAccessExpression */: - case 166 /* PropertyAccessExpression */: + case 170 /* ElementAccessExpression */: + case 169 /* PropertyAccessExpression */: var member = initializer.parent; var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); var enumType_1; - var propertyName; + var propertyName = void 0; 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 @@ -25294,8 +27658,8 @@ var ts; propertyName = e.text; } else { - var expression; - if (e.kind === 167 /* ElementAccessExpression */) { + var expression = void 0; + if (e.kind === 170 /* ElementAccessExpression */) { if (e.argumentExpression === undefined || e.argumentExpression.kind !== 9 /* StringLiteral */) { return undefined; @@ -25313,7 +27677,7 @@ var ts; if (current.kind === 69 /* Identifier */) { break; } - else if (current.kind === 166 /* PropertyAccessExpression */) { + else if (current.kind === 169 /* PropertyAccessExpression */) { current = current.expression; } else { @@ -25358,6 +27722,7 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); computeEnumMemberValues(node); var enumIsConst = ts.isConst(node); @@ -25381,10 +27746,10 @@ var ts; } }); } - var seenEnumMissingInitialInitializer = false; + var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 217 /* EnumDeclaration */) { + if (declaration.kind !== 220 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -25393,11 +27758,11 @@ var ts; } var firstEnumMember = enumDeclaration.members[0]; if (!firstEnumMember.initializer) { - if (seenEnumMissingInitialInitializer) { + if (seenEnumMissingInitialInitializer_1) { 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; + seenEnumMissingInitialInitializer_1 = true; } } }); @@ -25405,10 +27770,10 @@ var ts; } 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))) && + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var declaration = declarations_5[_i]; + if ((declaration.kind === 217 /* ClassDeclaration */ || + (declaration.kind === 216 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } @@ -25431,7 +27796,12 @@ var ts; function checkModuleDeclaration(node) { if (produceDiagnostics) { // Grammar checking - var isAmbientExternalModule = node.name.kind === 9 /* StringLiteral */; + var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); + var inAmbientContext = ts.isInAmbientContext(node); + if (isGlobalAugmentation && !inAmbientContext) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); + } + var isAmbientExternalModule = ts.isAmbientModule(node); 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; @@ -25440,18 +27810,19 @@ var ts; return; } if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { - if (!ts.isInAmbientContext(node) && node.name.kind === 9 /* StringLiteral */) { + if (!inAmbientContext && 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); + checkCollisionWithGlobalPromiseInGeneratedCode(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) + && !inAmbientContext && ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { @@ -25464,30 +27835,120 @@ var ts; } // 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 */); + var mergedClass = ts.getDeclarationOfKind(symbol, 217 /* 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.isExternalModuleAugmentation(node)) { + // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module) + // otherwise we'll be swamped in cascading errors. + // We can detect if augmentation was applied using following rules: + // - augmentation for a global scope is always applied + // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Merged */); + if (checkBody) { + // body of ambient external module is always a module block + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + checkModuleAugmentationElement(statement, isGlobalAugmentation); + } + } } - if (ts.isExternalModuleNameRelative(node.name.text)) { - error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + else if (isGlobalSourceFile(node.parent)) { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else if (ts.isExternalModuleNameRelative(node.name.text)) { + error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } + } + else { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else { + // Node is not an augmentation and is not located on the script level. + // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited. + error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + } } } } checkSourceElement(node.body); } + function checkModuleAugmentationElement(node, isGlobalAugmentation) { + switch (node.kind) { + case 196 /* VariableStatement */: + // error each individual name in variable statement instead of marking the entire variable statement + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + checkModuleAugmentationElement(decl, isGlobalAugmentation); + } + break; + case 230 /* ExportAssignment */: + case 231 /* ExportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); + break; + case 224 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind !== 9 /* StringLiteral */) { + error(node.name, ts.Diagnostics.Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope); + break; + } + // fallthrough + case 225 /* ImportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); + break; + case 166 /* BindingElement */: + case 214 /* VariableDeclaration */: + var name_17 = node.name; + if (ts.isBindingPattern(name_17)) { + for (var _b = 0, _c = name_17.elements; _b < _c.length; _b++) { + var el = _c[_b]; + // mark individual names in binding pattern + checkModuleAugmentationElement(el, isGlobalAugmentation); + } + break; + } + // fallthrough + case 217 /* ClassDeclaration */: + case 220 /* EnumDeclaration */: + case 216 /* FunctionDeclaration */: + case 218 /* InterfaceDeclaration */: + case 221 /* ModuleDeclaration */: + case 219 /* TypeAliasDeclaration */: + var symbol = getSymbolOfNode(node); + if (symbol) { + // module augmentations cannot introduce new names on the top level scope of the module + // this is done it two steps + // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error + // 2. main check - report error if value declaration of the parent symbol is module augmentation) + var reportError = !(symbol.flags & 33554432 /* Merged */); + if (!reportError) { + if (isGlobalAugmentation) { + // global symbol should not have parent since it is not explicitly exported + reportError = symbol.parent !== undefined; + } + else { + // symbol should not originate in augmentation + reportError = ts.isExternalModuleAugmentation(symbol.parent.valueDeclaration); + } + } + if (reportError) { + error(node, ts.Diagnostics.Module_augmentation_cannot_introduce_new_names_in_the_top_level_scope); + } + } + break; + } + } function getFirstIdentifier(node) { while (true) { - if (node.kind === 135 /* QualifiedName */) { + if (node.kind === 136 /* QualifiedName */) { node = node.left; } - else if (node.kind === 166 /* PropertyAccessExpression */) { + else if (node.kind === 169 /* PropertyAccessExpression */) { node = node.expression; } else { @@ -25503,20 +27964,24 @@ var ts; 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 */ ? + var inAmbientExternalModule = node.parent.kind === 222 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 251 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 231 /* 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; + // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration + // no need to do this again. + if (!isTopLevelInExternalModuleAugmentation(node)) { + // 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; } @@ -25528,7 +27993,7 @@ var ts; (symbol.flags & 793056 /* Type */ ? 793056 /* Type */ : 0) | (symbol.flags & 1536 /* Namespace */ ? 1536 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 230 /* ExportSpecifier */ ? + var message = node.kind === 233 /* 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)); @@ -25538,6 +28003,7 @@ var ts; function checkImportBinding(node) { checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkAliasSymbol(node); } function checkImportDeclaration(node) { @@ -25545,7 +28011,7 @@ var ts; // 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 */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022 /* Modifier */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -25555,7 +28021,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 227 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { @@ -25573,7 +28039,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (node.flags & 1 /* Export */) { + if (node.flags & 2 /* Export */) { markExportAsReferenced(node); } if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -25604,7 +28070,7 @@ var ts; // 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 */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022 /* Modifier */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { @@ -25612,29 +28078,38 @@ var ts; // 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) { + var inAmbientExternalModule = node.parent.kind === 222 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 251 /* 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="]) { + if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { 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 */) { + if (node.parent.kind !== 251 /* SourceFile */ && node.parent.kind !== 222 /* ModuleBlock */ && node.parent.kind !== 221 /* ModuleDeclaration */) { return grammarErrorOnFirstToken(node, errorMessage); } } function checkExportSpecifier(node) { checkAliasSymbol(node); if (!node.parent.parent.moduleSpecifier) { - markExportAsReferenced(node); + var exportedName = node.propertyName || node.name; + // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) + var symbol = resolveName(exportedName, exportedName.text, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */, + /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + error(exportedName, ts.Diagnostics.Cannot_re_export_name_that_is_not_defined_in_the_module); + } + else { + markExportAsReferenced(node); + } } } function checkExportAssignment(node) { @@ -25642,13 +28117,13 @@ var ts; // 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 */) { + var container = node.parent.kind === 251 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 221 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { 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 */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022 /* Modifier */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 69 /* Identifier */) { @@ -25669,15 +28144,6 @@ var ts; } } } - 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=") { @@ -25693,14 +28159,32 @@ var ts; 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); + if (!isTopLevelInExternalModuleAugmentation(declaration)) { + error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + } + // Checks for export * conflicts + var exports = getExportsOfModule(moduleSymbol); + for (var id in exports) { + if (id === "__export") { + continue; + } + var _a = exports[id], declarations = _a.declarations, flags = _a.flags; + // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. (TS Exceptions: namespaces, function overloads, enums, and interfaces) + if (!(flags & (1536 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) && (flags & 524288 /* TypeAlias */ ? declarations.length - 1 : declarations.length) > 1) { + var exportedDeclarations = ts.filter(declarations, isNotOverload); + if (exportedDeclarations.length > 1) { + for (var _i = 0, exportedDeclarations_1 = exportedDeclarations; _i < exportedDeclarations_1.length; _i++) { + var declaration = exportedDeclarations_1[_i]; + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, id)); + } + } + } } 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 isNotOverload(declaration) { + return declaration.kind !== 216 /* FunctionDeclaration */ || !!declaration.body; } } function checkSourceElement(node) { @@ -25712,226 +28196,153 @@ var ts; // 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 */: + case 221 /* ModuleDeclaration */: + case 217 /* ClassDeclaration */: + case 218 /* InterfaceDeclaration */: + case 216 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 137 /* TypeParameter */: + case 138 /* TypeParameter */: return checkTypeParameter(node); - case 138 /* Parameter */: + case 139 /* Parameter */: return checkParameter(node); - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: return checkPropertyDeclaration(node); - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: + case 153 /* FunctionType */: + case 154 /* ConstructorType */: + case 148 /* CallSignature */: + case 149 /* ConstructSignature */: return checkSignatureDeclaration(node); - case 149 /* IndexSignature */: + case 150 /* IndexSignature */: return checkSignatureDeclaration(node); - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: return checkMethodDeclaration(node); - case 144 /* Constructor */: + case 145 /* Constructor */: return checkConstructorDeclaration(node); - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: return checkAccessorDeclaration(node); - case 151 /* TypeReference */: + case 152 /* TypeReference */: return checkTypeReferenceNode(node); - case 150 /* TypePredicate */: + case 151 /* TypePredicate */: return checkTypePredicate(node); - case 154 /* TypeQuery */: + case 155 /* TypeQuery */: return checkTypeQuery(node); - case 155 /* TypeLiteral */: + case 156 /* TypeLiteral */: return checkTypeLiteral(node); - case 156 /* ArrayType */: + case 157 /* ArrayType */: return checkArrayType(node); - case 157 /* TupleType */: + case 158 /* TupleType */: return checkTupleType(node); - case 158 /* UnionType */: - case 159 /* IntersectionType */: + case 159 /* UnionType */: + case 160 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 160 /* ParenthesizedType */: + case 161 /* ParenthesizedType */: return checkSourceElement(node.type); - case 213 /* FunctionDeclaration */: + case 216 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 195 /* Block */: + case 222 /* ModuleBlock */: return checkBlock(node); - case 193 /* VariableStatement */: + case 196 /* VariableStatement */: return checkVariableStatement(node); - case 195 /* ExpressionStatement */: + case 198 /* ExpressionStatement */: return checkExpressionStatement(node); - case 196 /* IfStatement */: + case 199 /* IfStatement */: return checkIfStatement(node); - case 197 /* DoStatement */: + case 200 /* DoStatement */: return checkDoStatement(node); - case 198 /* WhileStatement */: + case 201 /* WhileStatement */: return checkWhileStatement(node); - case 199 /* ForStatement */: + case 202 /* ForStatement */: return checkForStatement(node); - case 200 /* ForInStatement */: + case 203 /* ForInStatement */: return checkForInStatement(node); - case 201 /* ForOfStatement */: + case 204 /* ForOfStatement */: return checkForOfStatement(node); - case 202 /* ContinueStatement */: - case 203 /* BreakStatement */: + case 205 /* ContinueStatement */: + case 206 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 204 /* ReturnStatement */: + case 207 /* ReturnStatement */: return checkReturnStatement(node); - case 205 /* WithStatement */: + case 208 /* WithStatement */: return checkWithStatement(node); - case 206 /* SwitchStatement */: + case 209 /* SwitchStatement */: return checkSwitchStatement(node); - case 207 /* LabeledStatement */: + case 210 /* LabeledStatement */: return checkLabeledStatement(node); - case 208 /* ThrowStatement */: + case 211 /* ThrowStatement */: return checkThrowStatement(node); - case 209 /* TryStatement */: + case 212 /* TryStatement */: return checkTryStatement(node); - case 211 /* VariableDeclaration */: + case 214 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 163 /* BindingElement */: + case 166 /* BindingElement */: return checkBindingElement(node); - case 214 /* ClassDeclaration */: + case 217 /* ClassDeclaration */: return checkClassDeclaration(node); - case 215 /* InterfaceDeclaration */: + case 218 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 216 /* TypeAliasDeclaration */: + case 219 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 217 /* EnumDeclaration */: + case 220 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 218 /* ModuleDeclaration */: + case 221 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 222 /* ImportDeclaration */: + case 225 /* ImportDeclaration */: return checkImportDeclaration(node); - case 221 /* ImportEqualsDeclaration */: + case 224 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 228 /* ExportDeclaration */: + case 231 /* ExportDeclaration */: return checkExportDeclaration(node); - case 227 /* ExportAssignment */: + case 230 /* ExportAssignment */: return checkExportAssignment(node); - case 194 /* EmptyStatement */: + case 197 /* EmptyStatement */: checkGrammarStatementInAmbientContext(node); return; - case 210 /* DebuggerStatement */: + case 213 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 231 /* MissingDeclaration */: + case 234 /* 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(); + // const foo = function () { + // const 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 checkNodeDeferred(node) { + if (deferredNodes) { + deferredNodes.push(node); + } + } + function checkDeferredNodes() { + for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { + var node = deferredNodes_1[_i]; + switch (node.kind) { + case 176 /* FunctionExpression */: + case 177 /* ArrowFunction */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + checkAccessorDeferred(node); + break; + case 189 /* ClassExpression */: + checkClassExpressionDeferred(node); + break; + } } } function checkSourceFile(node) { @@ -25945,39 +28356,27 @@ var ts; 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; + if (compilerOptions.skipDefaultLibCheck) { + // If the user specified '--noLib' and a file has a '/// ', + // then we should treat that file as a default lib. + if (node.hasNoDefaultLib) { + return; + } } // Grammar checking checkGrammarSourceFile(node); - emitExtends = false; - emitDecorate = false; - emitParam = false; potentialThisCollisions.length = 0; + deferredNodes = []; ts.forEach(node.statements, checkSourceElement); - checkFunctionAndClassExpressionBodies(node); - if (ts.isExternalModule(node)) { + checkDeferredNodes(); + deferredNodes = undefined; + if (ts.isExternalOrCommonJsModule(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 */; } } @@ -26015,7 +28414,7 @@ var ts; function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 205 /* WithStatement */ && node.parent.statement === node) { + if (node.parent.kind === 208 /* WithStatement */ && node.parent.statement === node) { return true; } node = node.parent; @@ -26038,34 +28437,34 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 248 /* SourceFile */: - if (!ts.isExternalModule(location)) { + case 251 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) { break; } - case 218 /* ModuleDeclaration */: + case 221 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8914931 /* ModuleMember */); break; - case 217 /* EnumDeclaration */: + case 220 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 186 /* ClassExpression */: + case 189 /* 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 */: + case 217 /* ClassDeclaration */: + case 218 /* 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 */)) { + if (!(memberFlags & 64 /* Static */)) { copySymbols(getSymbolOfNode(location).members, meaning & 793056 /* Type */); } break; - case 173 /* FunctionExpression */: + case 176 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -26114,37 +28513,37 @@ var ts; } function isTypeDeclaration(node) { switch (node.kind) { - case 137 /* TypeParameter */: - case 214 /* ClassDeclaration */: - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 217 /* EnumDeclaration */: + case 138 /* TypeParameter */: + case 217 /* ClassDeclaration */: + case 218 /* InterfaceDeclaration */: + case 219 /* TypeAliasDeclaration */: + case 220 /* 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 */) { + while (node.parent && node.parent.kind === 136 /* QualifiedName */) { node = node.parent; } - return node.parent && node.parent.kind === 151 /* TypeReference */; + return node.parent && node.parent.kind === 152 /* TypeReference */; } function isHeritageClauseElementIdentifier(entityName) { var node = entityName; - while (node.parent && node.parent.kind === 166 /* PropertyAccessExpression */) { + while (node.parent && node.parent.kind === 169 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent && node.parent.kind === 188 /* ExpressionWithTypeArguments */; + return node.parent && node.parent.kind === 191 /* ExpressionWithTypeArguments */; } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 135 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 136 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 221 /* ImportEqualsDeclaration */) { + if (nodeOnRightSide.parent.kind === 224 /* ImportEqualsDeclaration */) { return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 227 /* ExportAssignment */) { + if (nodeOnRightSide.parent.kind === 230 /* ExportAssignment */) { return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; } return undefined; @@ -26156,11 +28555,23 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (entityName.parent.kind === 227 /* ExportAssignment */) { + if (ts.isInJavaScriptFile(entityName) && entityName.parent.kind === 169 /* PropertyAccessExpression */) { + var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + switch (specialPropertyAssignmentKind) { + case 1 /* ExportsProperty */: + case 3 /* PrototypeProperty */: + return getSymbolOfNode(entityName.parent); + case 4 /* ThisProperty */: + case 2 /* ModuleExports */: + return getSymbolOfNode(entityName.parent.parent); + default: + } + } + if (entityName.parent.kind === 230 /* ExportAssignment */) { return resolveEntityName(entityName, /*all meanings*/ 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); } - if (entityName.kind !== 166 /* PropertyAccessExpression */) { + if (entityName.kind !== 169 /* PropertyAccessExpression */) { if (isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import return getSymbolOfPartOfRightHandSideOfImportEquals(entityName); @@ -26172,7 +28583,7 @@ var ts; 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 */) { + if (entityName.parent.kind === 191 /* ExpressionWithTypeArguments */) { meaning = 793056 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { @@ -26185,9 +28596,9 @@ var ts; meaning |= 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } - else if ((entityName.parent.kind === 235 /* JsxOpeningElement */) || - (entityName.parent.kind === 234 /* JsxSelfClosingElement */) || - (entityName.parent.kind === 237 /* JsxClosingElement */)) { + else if ((entityName.parent.kind === 238 /* JsxOpeningElement */) || + (entityName.parent.kind === 237 /* JsxSelfClosingElement */) || + (entityName.parent.kind === 240 /* JsxClosingElement */)) { return getJsxElementTagSymbol(entityName.parent); } else if (ts.isExpression(entityName)) { @@ -26201,14 +28612,14 @@ var ts; var meaning = 107455 /* Value */ | 8388608 /* Alias */; return resolveEntityName(entityName, meaning); } - else if (entityName.kind === 166 /* PropertyAccessExpression */) { + else if (entityName.kind === 169 /* PropertyAccessExpression */) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); } return getNodeLinks(entityName).resolvedSymbol; } - else if (entityName.kind === 135 /* QualifiedName */) { + else if (entityName.kind === 136 /* QualifiedName */) { var symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkQualifiedName(entityName); @@ -26217,16 +28628,16 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 151 /* TypeReference */ ? 793056 /* Type */ : 1536 /* Namespace */; + var meaning = entityName.parent.kind === 152 /* 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 */) { + else if (entityName.parent.kind === 241 /* JsxAttribute */) { return getJsxAttributePropertySymbol(entityName.parent); } - if (entityName.parent.kind === 150 /* TypePredicate */) { + if (entityName.parent.kind === 151 /* TypePredicate */) { return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); } // Do we want to return undefined here? @@ -26243,12 +28654,12 @@ var ts; } if (node.kind === 69 /* Identifier */) { if (isInRightSideOfImportOrExportAssignment(node)) { - return node.parent.kind === 227 /* ExportAssignment */ + return node.parent.kind === 230 /* ExportAssignment */ ? getSymbolOfEntityNameOrPropertyAccessExpression(node) : getSymbolOfPartOfRightHandSideOfImportEquals(node); } - else if (node.parent.kind === 163 /* BindingElement */ && - node.parent.parent.kind === 161 /* ObjectBindingPattern */ && + else if (node.parent.kind === 166 /* BindingElement */ && + node.parent.parent.kind === 164 /* ObjectBindingPattern */ && node === node.parent.propertyName) { var typeOfPattern = getTypeOfNode(node.parent.parent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); @@ -26259,17 +28670,19 @@ var ts; } switch (node.kind) { case 69 /* Identifier */: - case 166 /* PropertyAccessExpression */: - case 135 /* QualifiedName */: + case 169 /* PropertyAccessExpression */: + case 136 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 97 /* ThisKeyword */: case 95 /* SuperKeyword */: var type = ts.isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; + case 162 /* ThisType */: + return getTypeFromTypeNode(node).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 */) { + if (constructorDeclaration && constructorDeclaration.kind === 145 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; @@ -26277,14 +28690,14 @@ var ts; // 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.kind === 225 /* ImportDeclaration */ || node.parent.kind === 231 /* 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) { + if (node.parent.kind === 170 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { var objectType = checkExpression(node.parent.expression); if (objectType === unknownType) return undefined; @@ -26301,11 +28714,17 @@ var ts; // 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 */); + if (location && location.kind === 249 /* ShorthandPropertyAssignment */) { + return resolveEntityName(location.name, 107455 /* Value */ | 8388608 /* Alias */); } return undefined; } + /** Returns the target of an export specifier without following aliases */ + function getExportSpecifierLocalTargetSymbol(node) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : + resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793056 /* Type */ | 1536 /* Namespace */ | 8388608 /* Alias */); + } function getTypeOfNode(node) { if (isInsideWithStatementBody(node)) { // We cannot answer semantic questions within a with block, do not proceed any further @@ -26362,7 +28781,7 @@ var ts; */ function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return node.flags & 128 /* Static */ + return node.flags & 64 /* Static */ ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -26382,15 +28801,15 @@ var ts; } function getRootSymbols(symbol) { if (symbol.flags & 268435456 /* SyntheticProperty */) { - var symbols = []; - var name_15 = symbol.name; + var symbols_3 = []; + var name_18 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_15); + var symbol = getPropertyOfType(t, name_18); if (symbol) { - symbols.push(symbol); + symbols_3.push(symbol); } }); - return symbols; + return symbols_3; } else if (symbol.flags & 67108864 /* Transient */) { var target = getSymbolLinks(symbol).target; @@ -26401,6 +28820,33 @@ var ts; return [symbol]; } // Emitter support + function isArgumentsLocalBinding(node) { + return getReferencedValueSymbol(node) === argumentsSymbol; + } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol) { + // module not found - be conservative + return true; + } + var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); + // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment + // otherwise it will return moduleSymbol itself + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + // for export assignments - check if resolved symbol for RHS is itself a value + // otherwise - check if at least one export is value + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 107455 /* Value */) + : ts.forEachValue(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 107455 /* Value */); + } + } // 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) { @@ -26418,11 +28864,11 @@ var ts; } var parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { - if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 248 /* SourceFile */) { + if (parentSymbol.flags & 512 /* ValueModule */ && parentSymbol.valueDeclaration.kind === 251 /* 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) { + if ((n.kind === 221 /* ModuleDeclaration */ || n.kind === 220 /* EnumDeclaration */) && getSymbolOfNode(n) === parentSymbol) { return n; } } @@ -26435,58 +28881,77 @@ var ts; 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) { + function isSymbolOfDeclarationWithCollidingName(symbol) { if (symbol.flags & 418 /* BlockScoped */) { var links = getSymbolLinks(symbol); - if (links.isNestedRedeclaration === undefined) { + if (links.isDeclaratonWithCollidingName === undefined) { var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - links.isNestedRedeclaration = isStatementWithLocals(container) && - !!resolveName(container.parent, symbol.name, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (ts.isStatementWithLocals(container)) { + var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); + if (!!resolveName(container.parent, symbol.name, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)) { + // redeclaration - always should be renamed + links.isDeclaratonWithCollidingName = true; + } + else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + // binding is captured in the function + // should be renamed if: + // - binding is not top level - top level bindings never collide with anything + // AND + // - binding is not declared in loop, should be renamed to avoid name reuse across siblings + // let a, b + // { let x = 1; a = () => x; } + // { let x = 100; b = () => x; } + // console.log(a()); // should print '1' + // console.log(b()); // should print '100' + // OR + // - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body + // * variables from initializer are passed to rewritted loop body as parameters so they are not captured directly + // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus + // they will not collide with anything + var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; + var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 195 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + links.isDeclaratonWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); + } + else { + links.isDeclaratonWithCollidingName = false; + } + } } - return links.isNestedRedeclaration; + return links.isDeclaratonWithCollidingName; } 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) { + // a name that either hides an existing name or might hide it when compiled downlevel, + // return the declaration of that entity. Otherwise, return undefined. + function getReferencedDeclarationWithCollidingName(node) { var symbol = getReferencedValueSymbol(node); - return symbol && isNestedRedeclarationSymbol(symbol) ? symbol.valueDeclaration : undefined; + return symbol && isSymbolOfDeclarationWithCollidingName(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)); + // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an + // existing name or might hide a name when compiled downlevel + function isDeclarationWithCollidingName(node) { + return isSymbolOfDeclarationWithCollidingName(getSymbolOfNode(node)); } function isValueAliasDeclaration(node) { switch (node.kind) { - case 221 /* ImportEqualsDeclaration */: - case 223 /* ImportClause */: - case 224 /* NamespaceImport */: - case 226 /* ImportSpecifier */: - case 230 /* ExportSpecifier */: + case 224 /* ImportEqualsDeclaration */: + case 226 /* ImportClause */: + case 227 /* NamespaceImport */: + case 229 /* ImportSpecifier */: + case 233 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node)); - case 228 /* ExportDeclaration */: + case 231 /* ExportDeclaration */: var exportClause = node.exportClause; return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 227 /* ExportAssignment */: + case 230 /* 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)) { + if (node.parent.kind !== 251 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -26548,7 +29013,7 @@ var ts; return getNodeLinks(node).enumMemberValue; } function getConstantValue(node) { - if (node.kind === 247 /* EnumMember */) { + if (node.kind === 250 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; @@ -26640,23 +29105,12 @@ var ts; 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, + getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, + isDeclarationWithCollidingName: isDeclarationWithCollidingName, isValueAliasDeclaration: isValueAliasDeclaration, hasGlobalName: hasGlobalName, isReferencedAliasDeclaration: isReferencedAliasDeclaration, @@ -26673,25 +29127,51 @@ var ts; collectLinkedAliases: collectLinkedAliases, getReferencedValueDeclaration: getReferencedValueDeclaration, getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, - isOptionalParameter: isOptionalParameter + isOptionalParameter: isOptionalParameter, + moduleExportsSomeValue: moduleExportsSomeValue, + isArgumentsLocalBinding: isArgumentsLocalBinding, + getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration }; } + function getExternalModuleFileFromDeclaration(declaration) { + var specifier = ts.getExternalModuleName(declaration); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); + if (!moduleSymbol) { + return undefined; + } + return ts.getDeclarationOfKind(moduleSymbol, 251 /* SourceFile */); + } function initializeTypeChecker() { // Bind all source files and propagate errors ts.forEach(host.getSourceFiles(), function (file) { - ts.bindSourceFile(file); + ts.bindSourceFile(file, compilerOptions); }); + var augmentations; // Initialize global symbol table ts.forEach(host.getSourceFiles(), function (file) { - if (!ts.isExternalModule(file)) { + if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file.moduleAugmentations); + } }); - // Initialize special symbols + if (augmentations) { + // merge module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed + for (var _i = 0, augmentations_1 = augmentations; _i < augmentations_1.length; _i++) { + var list = augmentations_1[_i]; + for (var _a = 0, list_2 = list; _a < list_2.length; _a++) { + var augmentation = list_2[_a]; + mergeModuleAugmentation(augmentation); + } + } + } + // Setup global builtins + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); 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"); @@ -26760,9 +29240,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node)) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + if (node.kind === 144 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } } - else if (node.kind === 145 /* GetAccessor */ || node.kind === 146 /* SetAccessor */) { + else if (node.kind === 146 /* GetAccessor */ || node.kind === 147 /* 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); @@ -26772,38 +29257,38 @@ var ts; } 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 */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 145 /* Constructor */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 150 /* IndexSignature */: + case 221 /* ModuleDeclaration */: + case 225 /* ImportDeclaration */: + case 224 /* ImportEqualsDeclaration */: + case 231 /* ExportDeclaration */: + case 230 /* ExportAssignment */: + case 139 /* Parameter */: break; - case 213 /* FunctionDeclaration */: + case 216 /* FunctionDeclaration */: if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 118 /* AsyncKeyword */) && - node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 248 /* SourceFile */) { + node.parent.kind !== 222 /* ModuleBlock */ && node.parent.kind !== 251 /* 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 */) { + case 217 /* ClassDeclaration */: + case 218 /* InterfaceDeclaration */: + case 196 /* VariableStatement */: + case 219 /* TypeAliasDeclaration */: + if (node.modifiers && node.parent.kind !== 222 /* ModuleBlock */ && node.parent.kind !== 251 /* SourceFile */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; - case 217 /* EnumDeclaration */: + case 220 /* EnumDeclaration */: if (node.modifiers && (node.modifiers.length > 1 || node.modifiers[0].kind !== 74 /* ConstKeyword */) && - node.parent.kind !== 219 /* ModuleBlock */ && node.parent.kind !== 248 /* SourceFile */) { + node.parent.kind !== 222 /* ModuleBlock */ && node.parent.kind !== 251 /* SourceFile */) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); } break; @@ -26818,6 +29303,11 @@ var ts; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; switch (modifier.kind) { + case 74 /* ConstKeyword */: + if (node.kind !== 220 /* EnumDeclaration */ && node.parent.kind === 217 /* ClassDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(74 /* ConstKeyword */)); + } + break; case 112 /* PublicKeyword */: case 111 /* ProtectedKeyword */: case 110 /* PrivateKeyword */: @@ -26833,19 +29323,19 @@ var ts; text = "private"; lastPrivate = modifier; } - if (flags & 112 /* AccessibilityModifier */) { + if (flags & 56 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } - else if (flags & 128 /* Static */) { + else if (flags & 64 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } - else if (flags & 512 /* Async */) { + else if (flags & 256 /* 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 */) { + else if (node.parent.kind === 222 /* ModuleBlock */ || node.parent.kind === 251 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); } - else if (flags & 256 /* Abstract */) { + else if (flags & 128 /* Abstract */) { if (modifier.kind === 110 /* PrivateKeyword */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } @@ -26856,124 +29346,124 @@ var ts; flags |= ts.modifierToFlag(modifier.kind); break; case 113 /* StaticKeyword */: - if (flags & 128 /* Static */) { + if (flags & 64 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } - else if (flags & 512 /* Async */) { + else if (flags & 256 /* 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 */) { + else if (node.parent.kind === 222 /* ModuleBlock */ || node.parent.kind === 251 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, "static"); } - else if (node.kind === 138 /* Parameter */) { + else if (node.kind === 139 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } - else if (flags & 256 /* Abstract */) { + else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - flags |= 128 /* Static */; + flags |= 64 /* Static */; lastStatic = modifier; break; case 82 /* ExportKeyword */: - if (flags & 1 /* Export */) { + if (flags & 2 /* Export */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } - else if (flags & 2 /* Ambient */) { + else if (flags & 4 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); } - else if (flags & 256 /* Abstract */) { + else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); } - else if (flags & 512 /* Async */) { + else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 214 /* ClassDeclaration */) { + else if (node.parent.kind === 217 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 138 /* Parameter */) { + else if (node.kind === 139 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } - flags |= 1 /* Export */; + flags |= 2 /* Export */; break; case 122 /* DeclareKeyword */: - if (flags & 2 /* Ambient */) { + if (flags & 4 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } - else if (flags & 512 /* Async */) { + else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 214 /* ClassDeclaration */) { + else if (node.parent.kind === 217 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 138 /* Parameter */) { + else if (node.kind === 139 /* 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 */) { + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 222 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } - flags |= 2 /* Ambient */; + flags |= 4 /* Ambient */; lastDeclare = modifier; break; case 115 /* AbstractKeyword */: - if (flags & 256 /* Abstract */) { + if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 214 /* ClassDeclaration */) { - if (node.kind !== 143 /* MethodDeclaration */) { + if (node.kind !== 217 /* ClassDeclaration */) { + if (node.kind !== 144 /* 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 */)) { + if (!(node.parent.kind === 217 /* ClassDeclaration */ && node.parent.flags & 128 /* Abstract */)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } - if (flags & 128 /* Static */) { + if (flags & 64 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - if (flags & 32 /* Private */) { + if (flags & 16 /* Private */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); } } - flags |= 256 /* Abstract */; + flags |= 128 /* Abstract */; break; case 118 /* AsyncKeyword */: - if (flags & 512 /* Async */) { + if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } - else if (flags & 2 /* Ambient */ || ts.isInAmbientContext(node.parent)) { + else if (flags & 4 /* 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 */) { + else if (node.kind === 139 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } - flags |= 512 /* Async */; + flags |= 256 /* Async */; lastAsync = modifier; break; } } - if (node.kind === 144 /* Constructor */) { - if (flags & 128 /* Static */) { + if (node.kind === 145 /* Constructor */) { + if (flags & 64 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } - if (flags & 256 /* Abstract */) { + if (flags & 128 /* Abstract */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); } - else if (flags & 64 /* Protected */) { + else if (flags & 32 /* Protected */) { return grammarErrorOnNode(lastProtected, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "protected"); } - else if (flags & 32 /* Private */) { + else if (flags & 16 /* Private */) { return grammarErrorOnNode(lastPrivate, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "private"); } - else if (flags & 512 /* Async */) { + else if (flags & 256 /* 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 */) { + else if ((node.kind === 225 /* ImportDeclaration */ || node.kind === 224 /* ImportEqualsDeclaration */) && flags & 4 /* 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)) { + else if (node.kind === 139 /* Parameter */ && (flags & 56 /* AccessibilityModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); } - if (flags & 512 /* Async */) { + if (flags & 256 /* Async */) { return checkGrammarAsyncModifier(node, lastAsync); } } @@ -26982,10 +29472,10 @@ var ts; 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 */: + case 144 /* MethodDeclaration */: + case 216 /* FunctionDeclaration */: + case 176 /* FunctionExpression */: + case 177 /* ArrowFunction */: if (!node.asteriskToken) { return false; } @@ -27051,7 +29541,7 @@ var ts; checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node, file) { - if (node.kind === 174 /* ArrowFunction */) { + if (node.kind === 177 /* ArrowFunction */) { var arrowFunction = node; var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; @@ -27074,7 +29564,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (parameter.flags & 2035 /* Modifier */) { + if (parameter.flags & 1022 /* Modifier */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -27094,7 +29584,7 @@ var ts; } } function checkGrammarForIndexSignatureModifier(node) { - if (node.flags & 2035 /* Modifier */) { + if (node.flags & 1022 /* Modifier */) { grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_not_permitted_on_index_signature_members); } } @@ -27117,9 +29607,9 @@ var ts; 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 */) { + for (var _i = 0, args_1 = args; _i < args_1.length; _i++) { + var arg = args_1[_i]; + if (arg.kind === 190 /* OmittedExpression */) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -27193,19 +29683,19 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 136 /* ComputedPropertyName */) { + if (node.kind !== 137 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 181 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 24 /* CommaToken */) { + if (computedPropertyName.expression.kind === 184 /* 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 */); + ts.Debug.assert(node.kind === 216 /* FunctionDeclaration */ || + node.kind === 176 /* FunctionExpression */ || + node.kind === 144 /* MethodDeclaration */); if (ts.isInAmbientContext(node)) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } @@ -27228,20 +29718,25 @@ var ts; 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 */) { + var _loop_1 = function(prop) { + var name_19 = prop.name; + if (prop.kind === 190 /* OmittedExpression */ || + name_19.kind === 137 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it - checkGrammarComputedPropertyName(name_16); - continue; + checkGrammarComputedPropertyName(name_19); + return "continue"; } - if (prop.kind === 246 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 249 /* 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); + return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; } + // Modifiers are never allowed on properties except for 'async' on a method declaration + ts.forEach(prop.modifiers, function (mod) { + if (mod.kind !== 118 /* AsyncKeyword */ || prop.kind !== 144 /* MethodDeclaration */) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + }); // 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 @@ -27251,65 +29746,71 @@ var ts; // 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 */) { + if (prop.kind === 248 /* PropertyAssignment */ || prop.kind === 249 /* 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); + if (name_19.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(name_19); } currentKind = Property; } - else if (prop.kind === 143 /* MethodDeclaration */) { + else if (prop.kind === 144 /* MethodDeclaration */) { currentKind = Property; } - else if (prop.kind === 145 /* GetAccessor */) { + else if (prop.kind === 146 /* GetAccessor */) { currentKind = GetAccessor; } - else if (prop.kind === 146 /* SetAccessor */) { + else if (prop.kind === 147 /* SetAccessor */) { currentKind = SetAccesor; } else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - if (!ts.hasProperty(seen, name_16.text)) { - seen[name_16.text] = currentKind; + if (!ts.hasProperty(seen, name_19.text)) { + seen[name_19.text] = currentKind; } else { - var existingKind = seen[name_16.text]; + var existingKind = seen[name_19.text]; if (currentKind === Property && existingKind === Property) { - continue; + return "continue"; } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen[name_16.text] = currentKind | existingKind; + seen[name_19.text] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_16, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return { value: grammarErrorOnNode(name_19, 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); + return { value: grammarErrorOnNode(name_19, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; } } + }; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_1(prop); + if (typeof state_2 === "object") return state_2.value; + if (state_2 === "continue") continue; } } 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 */) { + if (attr.kind === 242 /* JsxSpreadAttribute */) { continue; } var jsxAttr = attr; - var name_17 = jsxAttr.name; - if (!ts.hasProperty(seen, name_17.text)) { - seen[name_17.text] = true; + var name_20 = jsxAttr.name; + if (!ts.hasProperty(seen, name_20.text)) { + seen[name_20.text] = true; } else { - return grammarErrorOnNode(name_17, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_20, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 240 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 243 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -27318,24 +29819,35 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.initializer.kind === 212 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 215 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { - if (variableList.declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 200 /* ForInStatement */ + var declarations = variableList.declarations; + // declarations.length can be zero if there is an error in variable declaration in for-of or for-in + // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details + // For example: + // var let = 10; + // for (let of [1,2,3]) {} // this is invalid ES6 syntax + // for (let in [1,2,3]) {} // this is invalid ES6 syntax + // We will then want to skip on grammar checking on variableList declaration + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 203 /* 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]; + var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 200 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 203 /* 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 */ + var diagnostic = forInOrOfStatement.kind === 203 /* 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); @@ -27358,10 +29870,10 @@ var ts; else if (accessor.typeParameters) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } - else if (kind === 145 /* GetAccessor */ && accessor.parameters.length) { + else if (kind === 146 /* GetAccessor */ && accessor.parameters.length) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_get_accessor_cannot_have_parameters); } - else if (kind === 146 /* SetAccessor */) { + else if (kind === 147 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -27373,7 +29885,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); } - else if (parameter.flags & 2035 /* Modifier */) { + else if (parameter.flags & 1022 /* Modifier */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } else if (parameter.questionToken) { @@ -27386,7 +29898,7 @@ var ts; } } function checkGrammarForNonSymbolComputedProperty(node, message) { - if (node.kind === 136 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(node.expression)) { + if (ts.isDynamicName(node)) { return grammarErrorOnNode(node, message); } } @@ -27396,12 +29908,12 @@ var ts; checkGrammarForGenerator(node)) { return true; } - if (node.parent.kind === 165 /* ObjectLiteralExpression */) { + if (node.parent.kind === 168 /* 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, "{"); + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } } if (ts.isClassLike(node.parent)) { @@ -27420,26 +29932,13 @@ var ts; 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 */) { + else if (node.parent.kind === 218 /* 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 */) { + else if (node.parent.kind === 156 /* 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) { @@ -27447,26 +29946,26 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 207 /* LabeledStatement */: + case 210 /* 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); + var isMisplacedContinueLabel = node.kind === 205 /* ContinueStatement */ + && !ts.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) { + case 209 /* SwitchStatement */: + if (node.kind === 206 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } break; default: - if (isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) { + if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) { // unlabeled break or continue within iteration statement - ok return false; } @@ -27475,13 +29974,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 203 /* BreakStatement */ + var message = node.kind === 206 /* 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 */ + var message = node.kind === 206 /* 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); @@ -27493,7 +29992,7 @@ var ts; 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 */) { + if (node.name.kind === 165 /* ArrayBindingPattern */ || node.name.kind === 164 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.initializer) { @@ -27503,7 +30002,7 @@ var ts; } } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 200 /* ForInStatement */ && node.parent.parent.kind !== 201 /* ForOfStatement */) { + if (node.parent.parent.kind !== 203 /* ForInStatement */ && node.parent.parent.kind !== 204 /* ForOfStatement */) { if (ts.isInAmbientContext(node)) { if (node.initializer) { // Error on equals token which immediate precedes the initializer @@ -27520,7 +30019,7 @@ var ts; } } } - var checkLetConstNames = languageVersion >= 2 /* ES6 */ && (ts.isLet(node) || ts.isConst(node)); + var checkLetConstNames = (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 @@ -27531,15 +30030,15 @@ var ts; } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 69 /* Identifier */) { - if (name.text === "let") { + if (name.originalKeywordKind === 108 /* LetKeyword */) { 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 */) { + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; + if (element.kind !== 190 /* OmittedExpression */) { checkGrammarNameInLetOrConstDeclarations(element.name); } } @@ -27556,15 +30055,15 @@ var ts; } 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 */: + case 199 /* IfStatement */: + case 200 /* DoStatement */: + case 201 /* WhileStatement */: + case 208 /* WithStatement */: + case 202 /* ForStatement */: + case 203 /* ForInStatement */: + case 204 /* ForOfStatement */: return false; - case 207 /* LabeledStatement */: + case 210 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -27579,23 +30078,6 @@ var ts; } } } - 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; } @@ -27620,10 +30102,6 @@ var ts; 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); @@ -27641,15 +30119,21 @@ var ts; return true; } } - else if (node.parent.kind === 215 /* InterfaceDeclaration */) { + else if (node.parent.kind === 218 /* InterfaceDeclaration */) { if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { return true; } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } } - else if (node.parent.kind === 155 /* TypeLiteral */) { + else if (node.parent.kind === 156 /* 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 (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } } if (ts.isInAmbientContext(node) && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); @@ -27662,17 +30146,20 @@ var ts; // DeclarationElement: // ExportAssignment // export_opt InterfaceDeclaration + // export_opt TypeAliasDeclaration // 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 */))) { + // TODO: The spec needs to be amended to reflect this grammar. + if (node.kind === 218 /* InterfaceDeclaration */ || + node.kind === 219 /* TypeAliasDeclaration */ || + node.kind === 225 /* ImportDeclaration */ || + node.kind === 224 /* ImportEqualsDeclaration */ || + node.kind === 231 /* ExportDeclaration */ || + node.kind === 230 /* ExportAssignment */ || + (node.flags & 4 /* Ambient */) || + (node.flags & (2 /* Export */ | 512 /* Default */))) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -27680,7 +30167,7 @@ var ts; 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 (ts.isDeclaration(decl) || decl.kind === 196 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -27706,7 +30193,7 @@ var ts; // 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 */) { + if (node.parent.kind === 195 /* Block */ || node.parent.kind === 222 /* ModuleBlock */ || node.parent.kind === 251 /* SourceFile */) { var links_1 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_1.hasReportedStatementInAmbientContext) { @@ -27719,7 +30206,7 @@ var ts; } function checkGrammarNumericLiteral(node) { // Grammar checking - if (node.flags & 65536 /* OctalLiteral */ && languageVersion >= 1 /* ES5 */) { + if (node.flags & 32768 /* OctalLiteral */ && languageVersion >= 1 /* ES5 */) { return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); } } @@ -27731,21 +30218,345 @@ var ts; return true; } } + var _a; } ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); /// /* @internal */ var ts; +(function (ts) { + var nullSourceMapWriter; + // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans + var defaultLastEncodedSourceMapSpan = { + emittedLine: 1, + emittedColumn: 1, + sourceLine: 1, + sourceColumn: 1, + sourceIndex: 0 + }; + function getNullSourceMapWriter() { + if (nullSourceMapWriter === undefined) { + nullSourceMapWriter = { + getSourceMapData: function () { return undefined; }, + setSourceFile: function (sourceFile) { }, + emitStart: function (range) { }, + emitEnd: function (range, stopOverridingSpan) { }, + emitPos: function (pos) { }, + changeEmitSourcePos: function () { }, + getText: function () { return undefined; }, + getSourceMappingURL: function () { return undefined; }, + initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, + reset: function () { } + }; + } + return nullSourceMapWriter; + } + ts.getNullSourceMapWriter = getNullSourceMapWriter; + function createSourceMapWriter(host, writer) { + var compilerOptions = host.getCompilerOptions(); + var currentSourceFile; + var sourceMapDir; // The directory in which sourcemap will be + var stopOverridingSpan = false; + var modifyLastSourcePos = false; + // Current source map file and its index in the sources list + var sourceMapSourceIndex; + // Last recorded and encoded spans + var lastRecordedSourceMapSpan; + var lastEncodedSourceMapSpan; + var lastEncodedNameIndex; + // Source map data + var sourceMapData; + return { + getSourceMapData: function () { return sourceMapData; }, + setSourceFile: setSourceFile, + emitPos: emitPos, + emitStart: emitStart, + emitEnd: emitEnd, + changeEmitSourcePos: changeEmitSourcePos, + getText: getText, + getSourceMappingURL: getSourceMappingURL, + initialize: initialize, + reset: reset + }; + function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (sourceMapData) { + reset(); + } + currentSourceFile = undefined; + // Current source map file and its index in the sources list + sourceMapSourceIndex = -1; + // Last recorded and encoded spans + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; + lastEncodedNameIndex = 0; + // Initialize source map data + sourceMapData = { + sourceMapFilePath: sourceMapFilePath, + jsSourceMappingURL: !compilerOptions.inlineSourceMap ? ts.getBaseFileName(ts.normalizeSlashes(sourceMapFilePath)) : undefined, + sourceMapFile: ts.getBaseFileName(ts.normalizeSlashes(filePath)), + sourceMapSourceRoot: compilerOptions.sourceRoot || "", + sourceMapSources: [], + inputSourceFileNames: [], + sourceMapNames: [], + sourceMapMappings: "", + sourceMapSourcesContent: compilerOptions.inlineSources ? [] : 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 (!isBundledEmit) { + ts.Debug.assert(sourceFiles.length === 1); + // 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(sourceFiles[0], 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(filePath)), // 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(filePath)); + } + } + function reset() { + currentSourceFile = undefined; + sourceMapDir = undefined; + sourceMapSourceIndex = undefined; + lastRecordedSourceMapSpan = undefined; + lastEncodedSourceMapSpan = undefined; + lastEncodedNameIndex = undefined; + sourceMapData = undefined; + } + function updateLastEncodedAndRecordedSpans() { + if (modifyLastSourcePos) { + // Reset the source pos + modifyLastSourcePos = false; + // Change Last recorded Map with last encoded emit line and character + lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; + lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; + // Pop sourceMapDecodedMappings to remove last entry + sourceMapData.sourceMapDecodedMappings.pop(); + // Point the lastEncodedSourceMapSpace to the previous encoded sourceMapSpan + // If the list is empty which indicates that we are at the beginning of the file, + // we have to reset it to default value (same value when we first initialize sourceMapWriter) + lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? + sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : + defaultLastEncodedSourceMapSpan; + // TODO: Update lastEncodedNameIndex + // Since we dont support this any more, lets not worry about it right now. + // When we start supporting nameIndex, we will get back to this + // Change the encoded source map + var sourceMapMappings = sourceMapData.sourceMapMappings; + var lenthToSet = sourceMapMappings.length - 1; + for (; lenthToSet >= 0; lenthToSet--) { + var currentChar = sourceMapMappings.charAt(lenthToSet); + if (currentChar === ",") { + // Separator for the entry found + break; + } + if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { + // Last line separator found + break; + } + } + sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); + } + } + // 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) { + ts.Debug.assert(false, "We do not support name index right now, Make sure to update updateLastEncodedAndRecordedSpans when we start using this"); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); + lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; + } + lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; + sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); + } + function emitPos(pos) { + if (pos === -1) { + return; + } + 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, + sourceIndex: sourceMapSourceIndex + }; + stopOverridingSpan = false; + } + else if (!stopOverridingSpan) { + // 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; + } + updateLastEncodedAndRecordedSpans(); + } + function getStartPos(range) { + var rangeHasDecorators = !!range.decorators; + return range.pos !== -1 ? ts.skipTrivia(currentSourceFile.text, rangeHasDecorators ? range.decorators.end : range.pos) : -1; + } + function emitStart(range) { + emitPos(getStartPos(range)); + } + function emitEnd(range, stopOverridingEnd) { + emitPos(range.end); + stopOverridingSpan = stopOverridingEnd; + } + function changeEmitSourcePos() { + ts.Debug.assert(!modifyLastSourcePos); + modifyLastSourcePos = true; + } + function setSourceFile(sourceFile) { + currentSourceFile = sourceFile; + // 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; + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSourceFile.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + if (sourceMapSourceIndex === -1) { + sourceMapSourceIndex = sourceMapData.sourceMapSources.length; + sourceMapData.sourceMapSources.push(source); + // The one that can be used from program to get the actual source file + sourceMapData.inputSourceFileNames.push(sourceFile.fileName); + if (compilerOptions.inlineSources) { + sourceMapData.sourceMapSourcesContent.push(sourceFile.text); + } + } + } + function getText() { + encodeLastRecordedSourceMapSpan(); + return ts.stringify({ + version: 3, + file: sourceMapData.sourceMapFile, + sourceRoot: sourceMapData.sourceMapSourceRoot, + sources: sourceMapData.sourceMapSources, + names: sourceMapData.sourceMapNames, + mappings: sourceMapData.sourceMapMappings, + sourcesContent: sourceMapData.sourceMapSourcesContent + }); + } + function getSourceMappingURL() { + if (compilerOptions.inlineSourceMap) { + // Encode the sourceMap into the sourceMap url + var base64SourceMapText = ts.convertToBase64(getText()); + return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; + } + else { + return sourceMapData.jsSourceMappingURL; + } + } + } + ts.createSourceMapWriter = createSourceMapWriter; + var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + function base64FormatEncode(inValue) { + if (inValue < 64) { + return base64Chars.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + } + function base64VLQFormatEncode(inValue) { + // 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; + } +})(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; + var declarationDiagnostics = ts.createDiagnosticCollection(); + ts.forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile); + return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); + function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { + var declarationFilePath = _a.declarationFilePath; + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, diagnostics, jsFilePath, root) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -27755,85 +30566,106 @@ var ts; var writeTextOfNode; var writer = createAndSetNewTextWriterWithSymbolWriter(); var enclosingDeclaration; - var currentSourceFile; + var resultHasExternalModuleIndicator; + var currentText; + var currentLineMap; + var currentIdentifiers; + var isCurrentFileExternalModule; var reportedDeclarationError = false; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { } : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; + var noDeclare; 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 + // Emit references corresponding to each file + var emittedReferencedFiles = []; + var addedGlobalFileReference = false; + var allSourcesModuleElementDeclarationEmitInfo = []; + ts.forEach(sourceFiles, function (sourceFile) { + // Dont emit for javascript file + if (ts.isSourceFileJavaScript(sourceFile)) { + return; + } + // Check what references need to be added 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)) { + ts.forEach(sourceFile.referencedFiles, function (fileReference) { + var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); + // Emit reference in dts, if the file reference was not already emitted + if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { + // Add a reference to generated dts file, + // global file reference is added only + // - if it is not bundled emit (because otherwise it would be self reference) + // - and it is not already added + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { addedGlobalFileReference = true; } + emittedReferencedFiles.push(referencedFile); } }); } - emitSourceFile(root); + resultHasExternalModuleIndicator = false; + if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { + noDeclare = false; + emitSourceFile(sourceFile); + } + else if (ts.isExternalModule(sourceFile)) { + noDeclare = true; + write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); + writeLine(); + increaseIndent(); + emitSourceFile(sourceFile); + decreaseIndent(); + write("}"); + writeLine(); + } // 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 */); + if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { + ts.Debug.assert(aliasEmitInfo.node.kind === 225 /* ImportDeclaration */); createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 0); + ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); + for (var i = 0; i < aliasEmitInfo.indent; i++) { + increaseIndent(); + } writeImportDeclaration(aliasEmitInfo.node); aliasEmitInfo.asynchronousOutput = writer.getText(); + for (var i = 0; i < aliasEmitInfo.indent; i++) { + decreaseIndent(); + } } }); setWriter(oldWriter); + allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); + moduleElementDeclarationEmitInfo = []; + } + if (!isBundledEmit && ts.isExternalModule(sourceFile) && sourceFile.moduleAugmentations.length && !resultHasExternalModuleIndicator) { + // if file was external module with augmentations - this fact should be preserved in .d.ts as well. + // in case if we didn't write any external module specifiers in .d.ts we need to emit something + // that will force compiler to think that this file is an external module - 'export {}' is a reasonable choice here. + write("export {};"); + writeLine(); } - } - 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, + moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, synchronousDeclarationOutput: writer.getText(), referencePathsOutput: referencePathsOutput }; function hasInternalAnnotation(range) { - var text = currentSourceFile.text; - var comment = text.substring(range.pos, range.end); + var comment = currentText.substring(range.pos, range.end); return comment.indexOf("@internal") >= 0; } function stripInternal(node) { if (node) { - var leadingCommentRanges = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); + var leadingCommentRanges = ts.getLeadingCommentRanges(currentText, node.pos); if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { return; } @@ -27866,10 +30698,10 @@ var ts; var oldWriter = writer; ts.forEach(nodes, function (declaration) { var nodeToCheck; - if (declaration.kind === 211 /* VariableDeclaration */) { + if (declaration.kind === 214 /* VariableDeclaration */) { nodeToCheck = declaration.parent.parent; } - else if (declaration.kind === 225 /* NamedImports */ || declaration.kind === 226 /* ImportSpecifier */ || declaration.kind === 223 /* ImportClause */) { + else if (declaration.kind === 228 /* NamedImports */ || declaration.kind === 229 /* ImportSpecifier */ || declaration.kind === 226 /* ImportClause */) { ts.Debug.fail("We should be getting ImportDeclaration instead to write"); } else { @@ -27887,7 +30719,7 @@ var ts; // 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 */) { + if (moduleElementEmitInfo.node.kind === 225 /* 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; @@ -27897,12 +30729,12 @@ var ts; for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { increaseIndent(); } - if (nodeToCheck.kind === 218 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 221 /* ModuleDeclaration */) { ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); asynchronousSubModuleDeclarationEmitInfo = []; } writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 218 /* ModuleDeclaration */) { + if (nodeToCheck.kind === 221 /* ModuleDeclaration */) { moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; asynchronousSubModuleDeclarationEmitInfo = undefined; } @@ -27925,10 +30757,10 @@ var ts; 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)); + emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); } else { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); } } } @@ -27938,7 +30770,8 @@ var ts; } 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))); + reportedDeclarationError = true; + emitterDiagnostics.add(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) { @@ -27968,15 +30801,15 @@ var ts; } } function emitLines(nodes) { - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_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]; + for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { + var node = nodes_3[_i]; if (!canEmitFn || canEmitFn(node)) { if (currentWriterPos !== writer.getTextPos()) { write(separator); @@ -27991,10 +30824,10 @@ var ts; } function writeJsDocComments(declaration) { if (declaration) { - var jsDocComments = ts.getJsDocComments(declaration, currentSourceFile); - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, declaration, jsDocComments); + var jsDocComments = ts.getJsDocCommentsFromText(declaration, currentText); + ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); // jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentSourceFile, writer, jsDocComments, /*trailingSeparator*/ true, newLine, ts.writeCommentRange); + ts.emitComments(currentText, currentLineMap, writer, jsDocComments, /*trailingSeparator*/ true, newLine, ts.writeCommentRange); } } function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { @@ -28009,59 +30842,59 @@ var ts; case 120 /* BooleanKeyword */: case 131 /* SymbolKeyword */: case 103 /* VoidKeyword */: - case 97 /* ThisKeyword */: - case 9 /* StringLiteral */: - return writeTextOfNode(currentSourceFile, type); - case 188 /* ExpressionWithTypeArguments */: + case 162 /* ThisType */: + case 163 /* StringLiteralType */: + return writeTextOfNode(currentText, type); + case 191 /* ExpressionWithTypeArguments */: return emitExpressionWithTypeArguments(type); - case 151 /* TypeReference */: + case 152 /* TypeReference */: return emitTypeReference(type); - case 154 /* TypeQuery */: + case 155 /* TypeQuery */: return emitTypeQuery(type); - case 156 /* ArrayType */: + case 157 /* ArrayType */: return emitArrayType(type); - case 157 /* TupleType */: + case 158 /* TupleType */: return emitTupleType(type); - case 158 /* UnionType */: + case 159 /* UnionType */: return emitUnionType(type); - case 159 /* IntersectionType */: + case 160 /* IntersectionType */: return emitIntersectionType(type); - case 160 /* ParenthesizedType */: + case 161 /* ParenthesizedType */: return emitParenType(type); - case 152 /* FunctionType */: - case 153 /* ConstructorType */: + case 153 /* FunctionType */: + case 154 /* ConstructorType */: return emitSignatureDeclarationWithJsDocComments(type); - case 155 /* TypeLiteral */: + case 156 /* TypeLiteral */: return emitTypeLiteral(type); case 69 /* Identifier */: return emitEntityName(type); - case 135 /* QualifiedName */: + case 136 /* QualifiedName */: return emitEntityName(type); - case 150 /* TypePredicate */: + case 151 /* TypePredicate */: return emitTypePredicate(type); } function writeEntityName(entityName) { if (entityName.kind === 69 /* Identifier */) { - writeTextOfNode(currentSourceFile, entityName); + writeTextOfNode(currentText, entityName); } else { - var left = entityName.kind === 135 /* QualifiedName */ ? entityName.left : entityName.expression; - var right = entityName.kind === 135 /* QualifiedName */ ? entityName.right : entityName.name; + var left = entityName.kind === 136 /* QualifiedName */ ? entityName.left : entityName.expression; + var right = entityName.kind === 136 /* QualifiedName */ ? entityName.right : entityName.name; writeEntityName(left); write("."); - writeTextOfNode(currentSourceFile, right); + writeTextOfNode(currentText, 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); + entityName.parent.kind === 224 /* 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 */); + ts.Debug.assert(node.expression.kind === 69 /* Identifier */ || node.expression.kind === 169 /* PropertyAccessExpression */); emitEntityName(node.expression); if (node.typeArguments) { write("<"); @@ -28079,7 +30912,7 @@ var ts; } } function emitTypePredicate(type) { - writeTextOfNode(currentSourceFile, type.parameterName); + writeTextOfNode(currentText, type.parameterName); write(" is "); emitType(type.type); } @@ -28120,8 +30953,12 @@ var ts; } } function emitSourceFile(node) { - currentSourceFile = node; + currentText = node.text; + currentLineMap = ts.getLineStarts(node); + currentIdentifiers = node.identifiers; + isCurrentFileExternalModule = ts.isExternalModule(node); enclosingDeclaration = node; + ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true /* remove comments */); emitLines(node.statements); } // Return a temp variable name to be used in `export default` statements. @@ -28130,21 +30967,22 @@ var ts; // do not need to keep track of created temp names. function getExportDefaultTempVariableName() { var baseName = "_default"; - if (!ts.hasProperty(currentSourceFile.identifiers, baseName)) { + if (!ts.hasProperty(currentIdentifiers, baseName)) { return baseName; } var count = 0; while (true) { - var name_18 = baseName + "_" + (++count); - if (!ts.hasProperty(currentSourceFile.identifiers, name_18)) { - return name_18; + count++; + var name_21 = baseName + "_" + count; + if (!ts.hasProperty(currentIdentifiers, name_21)) { + return name_21; } } } function emitExportAssignment(node) { if (node.expression.kind === 69 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); - writeTextOfNode(currentSourceFile, node.expression); + writeTextOfNode(currentText, node.expression); } else { // Expression @@ -28181,10 +31019,10 @@ var ts; 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 */) { + else if (node.kind === 224 /* ImportEqualsDeclaration */ || + (node.parent.kind === 251 /* SourceFile */ && isCurrentFileExternalModule)) { + var isVisible = void 0; + if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 251 /* SourceFile */) { // Import declaration of another module that is visited async so lets put it in right spot asynchronousSubModuleDeclarationEmitInfo.push({ node: node, @@ -28194,7 +31032,7 @@ var ts; }); } else { - if (node.kind === 222 /* ImportDeclaration */) { + if (node.kind === 225 /* ImportDeclaration */) { var importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || @@ -28212,23 +31050,23 @@ var ts; } function writeModuleElement(node) { switch (node.kind) { - case 213 /* FunctionDeclaration */: + case 216 /* FunctionDeclaration */: return writeFunctionDeclaration(node); - case 193 /* VariableStatement */: + case 196 /* VariableStatement */: return writeVariableStatement(node); - case 215 /* InterfaceDeclaration */: + case 218 /* InterfaceDeclaration */: return writeInterfaceDeclaration(node); - case 214 /* ClassDeclaration */: + case 217 /* ClassDeclaration */: return writeClassDeclaration(node); - case 216 /* TypeAliasDeclaration */: + case 219 /* TypeAliasDeclaration */: return writeTypeAliasDeclaration(node); - case 217 /* EnumDeclaration */: + case 220 /* EnumDeclaration */: return writeEnumDeclaration(node); - case 218 /* ModuleDeclaration */: + case 221 /* ModuleDeclaration */: return writeModuleDeclaration(node); - case 221 /* ImportEqualsDeclaration */: + case 224 /* ImportEqualsDeclaration */: return writeImportEqualsDeclaration(node); - case 222 /* ImportDeclaration */: + case 225 /* ImportDeclaration */: return writeImportDeclaration(node); default: ts.Debug.fail("Unknown symbol kind"); @@ -28236,30 +31074,30 @@ var ts; } 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 (node.parent.kind === 251 /* SourceFile */) { // If the node is exported - if (node.flags & 1 /* Export */) { + if (node.flags & 2 /* Export */) { write("export "); } - if (node.flags & 1024 /* Default */) { + if (node.flags & 512 /* Default */) { write("default "); } - else if (node.kind !== 215 /* InterfaceDeclaration */) { + else if (node.kind !== 218 /* InterfaceDeclaration */ && !noDeclare) { write("declare "); } } } function emitClassMemberDeclarationFlags(node) { - if (node.flags & 32 /* Private */) { + if (node.flags & 16 /* Private */) { write("private "); } - else if (node.flags & 64 /* Protected */) { + else if (node.flags & 32 /* Protected */) { write("protected "); } - if (node.flags & 128 /* Static */) { + if (node.flags & 64 /* Static */) { write("static "); } - if (node.flags & 256 /* Abstract */) { + if (node.flags & 128 /* Abstract */) { write("abstract "); } } @@ -28267,11 +31105,11 @@ var ts; // 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 */) { + if (node.flags & 2 /* Export */) { write("export "); } write("import "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); write(" = "); if (ts.isInternalModuleImportEqualsDeclaration(node)) { emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError); @@ -28279,7 +31117,7 @@ var ts; } else { write("require("); - writeTextOfNode(currentSourceFile, ts.getExternalModuleImportEqualsDeclarationExpression(node)); + emitExternalModuleSpecifier(node); write(");"); } writer.writeLine(); @@ -28293,7 +31131,7 @@ var ts; } function isVisibleNamedBinding(namedBindings) { if (namedBindings) { - if (namedBindings.kind === 224 /* NamespaceImport */) { + if (namedBindings.kind === 227 /* NamespaceImport */) { return resolver.isDeclarationVisible(namedBindings); } else { @@ -28302,28 +31140,24 @@ var ts; } } 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 */) { + if (node.flags & 2 /* 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); + writeTextOfNode(currentText, 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 */) { + if (node.importClause.namedBindings.kind === 227 /* NamespaceImport */) { write("* as "); - writeTextOfNode(currentSourceFile, node.importClause.namedBindings.name); + writeTextOfNode(currentText, node.importClause.namedBindings.name); } else { write("{ "); @@ -28333,16 +31167,45 @@ var ts; } write(" from "); } - writeTextOfNode(currentSourceFile, node.moduleSpecifier); + emitExternalModuleSpecifier(node); write(";"); writer.writeLine(); } + function emitExternalModuleSpecifier(parent) { + // emitExternalModuleSpecifier is usually called when we emit something in the.d.ts file that will make it an external module (i.e. import/export declarations). + // the only case when it is not true is when we call it to emit correct name for module augmentation - d.ts files with just module augmentations are not considered + // external modules since they are indistingushable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}' + // so compiler will treat them as external modules. + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 221 /* ModuleDeclaration */; + var moduleSpecifier; + if (parent.kind === 224 /* ImportEqualsDeclaration */) { + var node = parent; + moduleSpecifier = ts.getExternalModuleImportEqualsDeclarationExpression(node); + } + else if (parent.kind === 221 /* ModuleDeclaration */) { + moduleSpecifier = parent.name; + } + else { + var node = parent; + moduleSpecifier = node.moduleSpecifier; + } + if (moduleSpecifier.kind === 9 /* StringLiteral */ && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { + var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, parent); + if (moduleName) { + write("\""); + write(moduleName); + write("\""); + return; + } + } + writeTextOfNode(currentText, moduleSpecifier); + } function emitImportOrExportSpecifier(node) { if (node.propertyName) { - writeTextOfNode(currentSourceFile, node.propertyName); + writeTextOfNode(currentText, node.propertyName); write(" as "); } - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } function emitExportSpecifier(node) { emitImportOrExportSpecifier(node); @@ -28364,7 +31227,7 @@ var ts; } if (node.moduleSpecifier) { write(" from "); - writeTextOfNode(currentSourceFile, node.moduleSpecifier); + emitExternalModuleSpecifier(node); } write(";"); writer.writeLine(); @@ -28372,17 +31235,27 @@ var ts; function writeModuleDeclaration(node) { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & 131072 /* Namespace */) { - write("namespace "); + if (ts.isGlobalScopeAugmentation(node)) { + write("global "); } else { - write("module "); + if (node.flags & 65536 /* Namespace */) { + write("namespace "); + } + else { + write("module "); + } + if (ts.isExternalModuleAugmentation(node)) { + emitExternalModuleSpecifier(node); + } + else { + writeTextOfNode(currentText, node.name); + } } - writeTextOfNode(currentSourceFile, node.name); - while (node.body.kind !== 219 /* ModuleBlock */) { + while (node.body.kind !== 222 /* ModuleBlock */) { node = node.body; write("."); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; @@ -28401,7 +31274,7 @@ var ts; emitJsDocComments(node); emitModuleElementDeclarationFlags(node); write("type "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); emitTypeParameters(node.typeParameters); write(" = "); emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError); @@ -28423,7 +31296,7 @@ var ts; write("const "); } write("enum "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); write(" {"); writeLine(); increaseIndent(); @@ -28434,7 +31307,7 @@ var ts; } function emitEnumMemberDeclaration(node) { emitJsDocComments(node); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); var enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); @@ -28444,26 +31317,26 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 143 /* MethodDeclaration */ && (node.parent.flags & 32 /* Private */); + return node.parent.kind === 144 /* MethodDeclaration */ && (node.parent.flags & 16 /* Private */); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { increaseIndent(); emitJsDocComments(node); decreaseIndent(); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, 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 */); + if (node.parent.kind === 153 /* FunctionType */ || + node.parent.kind === 154 /* ConstructorType */ || + (node.parent.parent && node.parent.parent.kind === 156 /* TypeLiteral */)) { + ts.Debug.assert(node.parent.kind === 144 /* MethodDeclaration */ || + node.parent.kind === 143 /* MethodSignature */ || + node.parent.kind === 153 /* FunctionType */ || + node.parent.kind === 154 /* ConstructorType */ || + node.parent.kind === 148 /* CallSignature */ || + node.parent.kind === 149 /* ConstructSignature */); emitType(node.constraint); } else { @@ -28474,31 +31347,31 @@ var ts; // 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 */: + case 217 /* ClassDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; break; - case 215 /* InterfaceDeclaration */: + case 218 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; - case 148 /* ConstructSignature */: + case 149 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; - case 147 /* CallSignature */: + case 148 /* 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 */) { + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + if (node.parent.flags & 64 /* 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 */) { + else if (node.parent.parent.kind === 217 /* 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 */: + case 216 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; default: @@ -28532,7 +31405,7 @@ var ts; function getHeritageClauseVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 214 /* ClassDeclaration */) { + if (node.parent.parent.kind === 217 /* 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 : @@ -28554,7 +31427,7 @@ var ts; function emitParameterProperties(constructorDeclaration) { if (constructorDeclaration) { ts.forEach(constructorDeclaration.parameters, function (param) { - if (param.flags & 112 /* AccessibilityModifier */) { + if (param.flags & 56 /* AccessibilityModifier */) { emitPropertyDeclaration(param); } }); @@ -28562,11 +31435,11 @@ var ts; } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & 256 /* Abstract */) { + if (node.flags & 128 /* Abstract */) { write("abstract "); } write("class "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); @@ -28589,7 +31462,7 @@ var ts; emitJsDocComments(node); emitModuleElementDeclarationFlags(node); write("interface "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); var prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); @@ -28616,7 +31489,7 @@ var ts; 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 (node.kind !== 214 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { if (ts.isBindingPattern(node.name)) { emitBindingPattern(node.name); } @@ -28624,37 +31497,37 @@ var ts; // 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); + writeTextOfNode(currentText, node.name); // If optional property emit ? - if ((node.kind === 141 /* PropertyDeclaration */ || node.kind === 140 /* PropertySignature */) && ts.hasQuestionToken(node)) { + if ((node.kind === 142 /* PropertyDeclaration */ || node.kind === 141 /* PropertySignature */) && ts.hasQuestionToken(node)) { write("?"); } - if ((node.kind === 141 /* PropertyDeclaration */ || node.kind === 140 /* PropertySignature */) && node.parent.kind === 155 /* TypeLiteral */) { + if ((node.kind === 142 /* PropertyDeclaration */ || node.kind === 141 /* PropertySignature */) && node.parent.kind === 156 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.flags & 32 /* Private */)) { + else if (!(node.flags & 16 /* Private */)) { writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); } } } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { - if (node.kind === 211 /* VariableDeclaration */) { + if (node.kind === 214 /* 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 */) { + else if (node.kind === 142 /* PropertyDeclaration */ || node.kind === 141 /* PropertySignature */) { // TODO(jfreeman): Deal with computed properties in error reporting. - if (node.flags & 128 /* Static */) { + if (node.flags & 64 /* 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 */) { + else if (node.parent.kind === 217 /* 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 : @@ -28686,7 +31559,7 @@ var ts; var elements = []; for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { var element = _a[_i]; - if (element.kind !== 187 /* OmittedExpression */) { + if (element.kind !== 190 /* OmittedExpression */) { elements.push(element); } } @@ -28706,7 +31579,7 @@ var ts; emitBindingPattern(bindingElement.name); } else { - writeTextOfNode(currentSourceFile, bindingElement.name); + writeTextOfNode(currentText, bindingElement.name); writeTypeOfDeclaration(bindingElement, /*type*/ undefined, getBindingElementTypeVisibilityError); } } @@ -28750,13 +31623,13 @@ var ts; emitJsDocComments(accessors.getAccessor); emitJsDocComments(accessors.setAccessor); emitClassMemberDeclarationFlags(node); - writeTextOfNode(currentSourceFile, node.name); - if (!(node.flags & 32 /* Private */)) { + writeTextOfNode(currentText, node.name); + if (!(node.flags & 16 /* 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; + var anotherAccessor = node.kind === 146 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -28769,7 +31642,7 @@ var ts; } function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 145 /* GetAccessor */ + return accessor.kind === 146 /* GetAccessor */ ? accessor.type // Getter - return type : accessor.parameters.length > 0 ? accessor.parameters[0].type // Setter parameter type @@ -28778,9 +31651,9 @@ var ts; } function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 146 /* SetAccessor */) { + if (accessorWithTypeAnnotation.kind === 147 /* SetAccessor */) { // Setters have to have type named and cannot infer it so, the type should always be named - if (accessorWithTypeAnnotation.parent.flags & 128 /* Static */) { + if (accessorWithTypeAnnotation.parent.flags & 64 /* 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; @@ -28798,7 +31671,7 @@ var ts; }; } else { - if (accessorWithTypeAnnotation.flags & 128 /* Static */) { + if (accessorWithTypeAnnotation.flags & 64 /* 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 : @@ -28828,21 +31701,21 @@ var ts; // so no need to verify if the declaration is visible if (!resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 216 /* FunctionDeclaration */) { emitModuleElementDeclarationFlags(node); } - else if (node.kind === 143 /* MethodDeclaration */) { + else if (node.kind === 144 /* MethodDeclaration */) { emitClassMemberDeclarationFlags(node); } - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 216 /* FunctionDeclaration */) { write("function "); - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); } - else if (node.kind === 144 /* Constructor */) { + else if (node.kind === 145 /* Constructor */) { write("constructor"); } else { - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, node.name); if (ts.hasQuestionToken(node)) { write("?"); } @@ -28855,37 +31728,37 @@ var ts; emitSignatureDeclaration(node); } function emitSignatureDeclaration(node) { + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; // Construct signature or constructor type write new Signature - if (node.kind === 148 /* ConstructSignature */ || node.kind === 153 /* ConstructorType */) { + if (node.kind === 149 /* ConstructSignature */ || node.kind === 154 /* ConstructorType */) { write("new "); } emitTypeParameters(node.typeParameters); - if (node.kind === 149 /* IndexSignature */) { + if (node.kind === 150 /* IndexSignature */) { write("["); } else { write("("); } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; // Parameters emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 149 /* IndexSignature */) { + if (node.kind === 150 /* 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 */) { + var isFunctionTypeOrConstructorType = node.kind === 153 /* FunctionType */ || node.kind === 154 /* ConstructorType */; + if (isFunctionTypeOrConstructorType || node.parent.kind === 156 /* 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 */)) { + else if (node.kind !== 145 /* Constructor */ && !(node.flags & 16 /* Private */)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -28896,34 +31769,34 @@ var ts; function getReturnTypeVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; switch (node.kind) { - case 148 /* ConstructSignature */: + case 149 /* 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 */: + case 148 /* 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 */: + case 150 /* 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 */) { + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + if (node.flags & 64 /* 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 */) { + else if (node.parent.kind === 217 /* 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 : @@ -28937,7 +31810,7 @@ var ts; ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; } break; - case 213 /* FunctionDeclaration */: + case 216 /* 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 : @@ -28966,18 +31839,18 @@ var ts; emitBindingPattern(node.name); } else { - writeTextOfNode(currentSourceFile, node.name); + writeTextOfNode(currentText, 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 */) { + if (node.parent.kind === 153 /* FunctionType */ || + node.parent.kind === 154 /* ConstructorType */ || + node.parent.parent.kind === 156 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.parent.flags & 32 /* Private */)) { + else if (!(node.parent.flags & 16 /* Private */)) { writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); } function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult) { @@ -28990,32 +31863,32 @@ var ts; } function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult) { switch (node.parent.kind) { - case 144 /* Constructor */: + case 145 /* 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 */: + case 149 /* 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 */: + case 148 /* 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 */) { + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + if (node.parent.flags & 64 /* 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 */) { + else if (node.parent.parent.kind === 217 /* 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 : @@ -29028,7 +31901,7 @@ var ts; 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 */: + case 216 /* 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 : @@ -29040,12 +31913,12 @@ var ts; } 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 */) { + if (bindingPattern.kind === 164 /* ObjectBindingPattern */) { write("{"); emitCommaList(bindingPattern.elements, emitBindingElement); write("}"); } - else if (bindingPattern.kind === 162 /* ArrayBindingPattern */) { + else if (bindingPattern.kind === 165 /* ArrayBindingPattern */) { write("["); var elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); @@ -29056,15 +31929,7 @@ var ts; } } 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.kind === 190 /* 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) @@ -29073,7 +31938,7 @@ var ts; // emit : function foo([ , x, , ]) {} write(" "); } - else if (bindingElement.kind === 163 /* BindingElement */) { + else if (bindingElement.kind === 166 /* 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" @@ -29081,7 +31946,7 @@ var ts; // 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); + writeTextOfNode(currentText, bindingElement.propertyName); write(": "); } if (bindingElement.name) { @@ -29104,7 +31969,7 @@ var ts; if (bindingElement.dotDotDotToken) { write("..."); } - writeTextOfNode(currentSourceFile, bindingElement.name); + writeTextOfNode(currentText, bindingElement.name); } } } @@ -29112,64 +31977,86 @@ var ts; } 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 */: + case 216 /* FunctionDeclaration */: + case 221 /* ModuleDeclaration */: + case 224 /* ImportEqualsDeclaration */: + case 218 /* InterfaceDeclaration */: + case 217 /* ClassDeclaration */: + case 219 /* TypeAliasDeclaration */: + case 220 /* EnumDeclaration */: return emitModuleElement(node, isModuleElementVisible(node)); - case 193 /* VariableStatement */: + case 196 /* VariableStatement */: return emitModuleElement(node, isVariableStatementVisible(node)); - case 222 /* ImportDeclaration */: + case 225 /* ImportDeclaration */: // Import declaration without import clause is visible, otherwise it is not visible return emitModuleElement(node, /*isModuleElementVisible*/ !node.importClause); - case 228 /* ExportDeclaration */: + case 231 /* ExportDeclaration */: return emitExportDeclaration(node); - case 144 /* Constructor */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 145 /* Constructor */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: return writeFunctionDeclaration(node); - case 148 /* ConstructSignature */: - case 147 /* CallSignature */: - case 149 /* IndexSignature */: + case 149 /* ConstructSignature */: + case 148 /* CallSignature */: + case 150 /* IndexSignature */: return emitSignatureDeclarationWithJsDocComments(node); - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: return emitAccessorDeclaration(node); - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: return emitPropertyDeclaration(node); - case 247 /* EnumMember */: + case 250 /* EnumMember */: return emitEnumMemberDeclaration(node); - case 227 /* ExportAssignment */: + case 230 /* ExportAssignment */: return emitExportAssignment(node); - case 248 /* SourceFile */: + case 251 /* 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; + /** + * Adds the reference to referenced file, returns true if global file reference was emitted + * @param referencedFile + * @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not + */ + function writeReferencePath(referencedFile, addBundledFileReference) { + var declFileName; + var addedBundledEmitReference = false; + if (ts.isDeclarationFile(referencedFile)) { + // Declaration file, use declaration file name + declFileName = referencedFile.fileName; + } + else { + // Get the declaration file path + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + } + if (declFileName) { + declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ false); + referencePathsOutput += "/// " + newLine; + } + return addedBundledEmitReference; + function getDeclFileName(emitFileNames, sourceFiles, isBundledEmit) { + // Dont add reference path to this file if it is a bundled emit and caller asked not emit bundled file path + if (isBundledEmit && !addBundledFileReference) { + return; + } + ts.Debug.assert(!!emitFileNames.declarationFilePath || ts.isSourceFileJavaScript(referencedFile), "Declaration file is not present only for javascript files"); + declFileName = emitFileNames.declarationFilePath || emitFileNames.jsFilePath; + addedBundledEmitReference = isBundledEmit; + } } } /* @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) { + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; + if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencePathsOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); - ts.writeFile(host, diagnostics, ts.removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, host.getCompilerOptions().emitBOM); + ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM); } + return emitSkipped; function getDeclarationOutput(synchronousDeclarationOutput, moduleElementDeclarationEmitInfo) { var appliedSyncOutputPos = 0; var declarationOutput = ""; @@ -29188,14 +32075,29 @@ var ts; ts.writeDeclarationFile = writeDeclarationFile; })(ts || (ts = {})); /// +/// /// /* @internal */ var ts; (function (ts) { - function isExternalModuleOrDeclarationFile(sourceFile) { - return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile); + function getResolvedExternalModuleName(host, file) { + return file.moduleName || ts.getExternalModuleNameFromPath(host, file.fileName); } - ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile; + ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getExternalModuleNameFromDeclaration(host, resolver, declaration) { + var file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || ts.isDeclarationFile(file)) { + return undefined; + } + return getResolvedExternalModuleName(host, file); + } + ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; + var Jump; + (function (Jump) { + Jump[Jump["Break"] = 2] = "Break"; + Jump[Jump["Continue"] = 4] = "Continue"; + Jump[Jump["Return"] = 8] = "Return"; + })(Jump || (Jump = {})); var entities = { "quot": 0x0022, "amp": 0x0026, @@ -29458,6 +32360,11 @@ var ts; TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); + var CopyDirection; + (function (CopyDirection) { + CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; + CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter"; + })(CopyDirection || (CopyDirection = {})); // 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 @@ -29468,41 +32375,19 @@ var ts; 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 awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\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 languageVersion = ts.getEmitScriptTarget(compilerOptions); + var modulekind = ts.getEmitModuleKind(compilerOptions); var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; - var diagnostics = []; + var emitterDiagnostics = ts.createDiagnosticCollection(); + var emitSkipped = false; 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); + var emitJavaScript = createFileEmitter(); + ts.forEachExpectedEmitFile(host, emitFile, targetSourceFile); return { - emitSkipped: false, - diagnostics: diagnostics, + emitSkipped: emitSkipped, + diagnostics: emitterDiagnostics.getDiagnostics(), sourceMaps: sourceMapDataList }; function isUniqueLocalName(name, container) { @@ -29516,10 +32401,49 @@ var ts; } return true; } - function emitJavaScript(jsFilePath, root) { + function setLabeledJump(state, isBreak, labelText, labelMarker) { + if (isBreak) { + if (!state.labeledNonLocalBreaks) { + state.labeledNonLocalBreaks = {}; + } + state.labeledNonLocalBreaks[labelText] = labelMarker; + } + else { + if (!state.labeledNonLocalContinues) { + state.labeledNonLocalContinues = {}; + } + state.labeledNonLocalContinues[labelText] = labelMarker; + } + } + function hoistVariableDeclarationFromLoop(state, declaration) { + if (!state.hoistedLocalVariables) { + state.hoistedLocalVariables = []; + } + visit(declaration.name); + function visit(node) { + if (node.kind === 69 /* Identifier */) { + state.hoistedLocalVariables.push(node); + } + else { + for (var _a = 0, _b = node.elements; _a < _b.length; _a++) { + var element = _b[_a]; + visit(element.name); + } + } + } + } + function createFileEmitter() { var writer = ts.createTextWriter(newLine); var write = writer.write, writeTextOfNode = writer.writeTextOfNode, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; + var sourceMap = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? ts.createSourceMapWriter(host, writer) : ts.getNullSourceMapWriter(); + var setSourceFile = sourceMap.setSourceFile, emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitPos = sourceMap.emitPos; var currentSourceFile; + var currentText; + var currentLineMap; + var currentFileIdentifiers; + var renamedDependencies; + var isEs6Module; + var isCurrentFileExternalModule; // name of an exporter function if file is a System external module // System.register([...], function () {...}) // exporting in System modules looks like: @@ -29527,47 +32451,31 @@ var ts; // => // var x;... exporter("x", x = 1) var exportFunctionForFile; - var generatedNameSet = {}; - var nodeToGeneratedName = []; + var contextObjectForFile; + var generatedNameSet; + var nodeToGeneratedName; var computedPropertyNamesToGeneratedNames; - var extendsEmitted = false; - var decorateEmitted = false; - var paramEmitted = false; - var awaiterEmitted = false; + var decoratedClassAliases; + var convertedLoopState; + var extendsEmitted; + var decorateEmitted; + var paramEmitted; + var awaiterEmitted; var tempFlags = 0; var tempVariables; var tempParameters; var externalImports; var exportSpecifiers; var exportEquals; - var hasExportStars; - /** Write emitted output to disk */ - var writeEmittedFiles = writeJavaScriptFile; + var hasExportStarsToExportValues; 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; + /** Is the file being emitted into its own file */ + var isOwnFileEmit; /** If removeComments is true, no leading-comments needed to be emitted **/ var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { } : emitLeadingCommentsOfPositionWorker; + var setSourceMapWriterEmit = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? changeSourceMapEmit : function (writer) { }; var moduleEmitDelegates = (_a = {}, _a[5 /* ES6 */] = emitES6Module, _a[2 /* AMD */] = emitAMDModule, @@ -29576,31 +32484,79 @@ var ts; _a[1 /* CommonJS */] = emitCommonJSModule, _a ); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - initializeEmitterWithSourceMaps(); - } - if (root) { + var bundleEmitDelegates = (_b = {}, + _b[5 /* ES6 */] = function () { }, + _b[2 /* AMD */] = emitAMDModule, + _b[4 /* System */] = emitSystemModule, + _b[3 /* UMD */] = function () { }, + _b[1 /* CommonJS */] = function () { }, + _b + ); + return doEmit; + function doEmit(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + generatedNameSet = {}; + nodeToGeneratedName = []; + decoratedClassAliases = []; + isOwnFileEmit = !isBundledEmit; + // Emit helpers from all the files + if (isBundledEmit && modulekind) { + ts.forEach(sourceFiles, emitEmitHelpers); + } // 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); - } - }); + ts.forEach(sourceFiles, emitSourceFile); + writeLine(); + var sourceMappingURL = sourceMap.getSourceMappingURL(); + if (sourceMappingURL) { + write("//# sourceMappingURL=" + sourceMappingURL); + } + writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM); + // reset the state + sourceMap.reset(); + writer.reset(); + currentSourceFile = undefined; + currentText = undefined; + currentLineMap = undefined; + exportFunctionForFile = undefined; + contextObjectForFile = undefined; + generatedNameSet = undefined; + nodeToGeneratedName = undefined; + decoratedClassAliases = undefined; + computedPropertyNamesToGeneratedNames = undefined; + convertedLoopState = undefined; + extendsEmitted = false; + decorateEmitted = false; + paramEmitted = false; + awaiterEmitted = false; + tempFlags = 0; + tempVariables = undefined; + tempParameters = undefined; + externalImports = undefined; + exportSpecifiers = undefined; + exportEquals = undefined; + hasExportStarsToExportValues = undefined; + detachedCommentsInfo = undefined; + sourceMapData = undefined; + isEs6Module = false; + renamedDependencies = undefined; + isCurrentFileExternalModule = false; } - writeLine(); - writeEmittedFiles(writer.getText(), /*writeByteOrderMark*/ compilerOptions.emitBOM); - return; function emitSourceFile(sourceFile) { currentSourceFile = sourceFile; + currentText = sourceFile.text; + currentLineMap = ts.getLineStarts(sourceFile); exportFunctionForFile = undefined; - emit(sourceFile); + contextObjectForFile = undefined; + isEs6Module = sourceFile.symbol && sourceFile.symbol.exports && !!sourceFile.symbol.exports["___esModule"]; + renamedDependencies = sourceFile.renamedDependencies; + currentFileIdentifiers = sourceFile.identifiers; + isCurrentFileExternalModule = ts.isExternalModule(sourceFile); + setSourceFile(sourceFile); + emitNodeWithCommentsAndWithoutSourcemap(sourceFile); } function isUniqueName(name) { return !resolver.hasGlobalName(name) && - !ts.hasProperty(currentSourceFile.identifiers, name) && + !ts.hasProperty(currentFileIdentifiers, name) && !ts.hasProperty(generatedNameSet, name); } // Return the next available name in the pattern _a ... _z, _0, _1, ... @@ -29608,10 +32564,10 @@ var ts; // 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)) { + var name_22 = flags === 268435456 /* _i */ ? "_i" : "_n"; + if (isUniqueName(name_22)) { tempFlags |= flags; - return name_19; + return name_22; } } while (true) { @@ -29619,9 +32575,9 @@ var ts; 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; + var name_23 = count < 26 ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); + if (isUniqueName(name_23)) { + return name_23; } } } @@ -29665,17 +32621,17 @@ var ts; switch (node.kind) { case 69 /* Identifier */: return makeUniqueName(node.text); - case 218 /* ModuleDeclaration */: - case 217 /* EnumDeclaration */: + case 221 /* ModuleDeclaration */: + case 220 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 222 /* ImportDeclaration */: - case 228 /* ExportDeclaration */: + case 225 /* ImportDeclaration */: + case 231 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 213 /* FunctionDeclaration */: - case 214 /* ClassDeclaration */: - case 227 /* ExportAssignment */: + case 216 /* FunctionDeclaration */: + case 217 /* ClassDeclaration */: + case 230 /* ExportAssignment */: return generateNameForExportDefault(); - case 186 /* ClassExpression */: + case 189 /* ClassExpression */: return generateNameForClassExpression(); } } @@ -29683,338 +32639,15 @@ var ts; 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); - } - } + /** Write emitted output to disk */ + function writeEmittedFiles(emitOutput, jsFilePath, sourceMapFilePath, writeByteOrderMark) { + if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false); } - function emitNodeWithCommentsAndWithSourcemap(node) { - emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); + if (sourceMapDataList) { + sourceMapDataList.push(sourceMap.getSourceMapData()); } - 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); + ts.writeFile(host, emitterDiagnostics, jsFilePath, emitOutput, writeByteOrderMark); } // Create a temporary variable with a unique unused name. function createTempVariable(flags) { @@ -30046,7 +32679,15 @@ var ts; write(";"); } } - function emitTokenText(tokenKind, startPos, emitFn) { + /** 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 */ + function emitToken(tokenKind, startPos, emitFn) { + var tokenStartPos = ts.skipTrivia(currentText, startPos); + emitPos(tokenStartPos); var tokenString = ts.tokenToString(tokenKind); if (emitFn) { emitFn(); @@ -30054,7 +32695,9 @@ var ts; else { write(tokenString); } - return startPos + tokenString.length; + var tokenEndPos = tokenStartPos + tokenString.length; + emitPos(tokenEndPos); + return tokenEndPos; } function emitOptional(prefix, node) { if (node) { @@ -30071,11 +32714,6 @@ var ts; write(")"); } } - function emitTrailingCommaIfPresent(nodeList) { - if (nodeList.hasTrailingComma) { - write(","); - } - } function emitLinePreservingList(parent, nodes, allowTrailingComma, spacesBetweenBraces) { ts.Debug.assert(nodes.length > 0); increaseIndent(); @@ -30148,7 +32786,7 @@ var ts; } function emitCommaList(nodes) { if (nodes) { - emitList(nodes, 0, nodes.length, /*multiline*/ false, /*trailingComma*/ false); + emitList(nodes, 0, nodes.length, /*multiLine*/ false, /*trailingComma*/ false); } } function emitLines(nodes) { @@ -30193,7 +32831,7 @@ var ts; // 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); + return ts.getTextOfNodeFromSourceText(currentText, 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. @@ -30220,7 +32858,7 @@ var ts; // 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); + var text = ts.getTextOfNodeFromSourceText(currentText, 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 "}" @@ -30263,10 +32901,10 @@ var ts; write("("); emit(tempVariable); // Now we emit the expressions - if (node.template.kind === 183 /* TemplateExpression */) { + if (node.template.kind === 186 /* TemplateExpression */) { ts.forEach(node.template.templateSpans, function (templateSpan) { write(", "); - var needsParens = templateSpan.expression.kind === 181 /* BinaryExpression */ + var needsParens = templateSpan.expression.kind === 184 /* BinaryExpression */ && templateSpan.expression.operatorToken.kind === 24 /* CommaToken */; emitParenthesizedIf(templateSpan.expression, needsParens); }); @@ -30301,7 +32939,7 @@ var ts; // ("abc" + 1) << (2 + "") // rather than // "abc" + (1 << 2) + "" - var needsParens = templateSpan.expression.kind !== 172 /* ParenthesizedExpression */ + var needsParens = templateSpan.expression.kind !== 175 /* 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 @@ -30343,11 +32981,11 @@ var ts; } function templateNeedsParens(template, parent) { switch (parent.kind) { - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 171 /* CallExpression */: + case 172 /* NewExpression */: return parent.expression === template; - case 170 /* TaggedTemplateExpression */: - case 172 /* ParenthesizedExpression */: + case 173 /* TaggedTemplateExpression */: + case 175 /* ParenthesizedExpression */: return false; default: return comparePrecedenceToBinaryPlus(parent) !== -1 /* LessThan */; @@ -30368,7 +33006,7 @@ var ts; // 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 */: + case 184 /* BinaryExpression */: switch (expression.operatorToken.kind) { case 37 /* AsteriskToken */: case 39 /* SlashToken */: @@ -30380,8 +33018,8 @@ var ts; default: return -1 /* LessThan */; } - case 184 /* YieldExpression */: - case 182 /* ConditionalExpression */: + case 187 /* YieldExpression */: + case 185 /* ConditionalExpression */: return -1 /* LessThan */; default: return 1 /* GreaterThan */; @@ -30409,13 +33047,13 @@ var ts; /// 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("\""); + if (/^[A-Za-z_]\w*$/.test(name.text)) { emit(name); - write("\""); } else { + write("\""); emit(name); + write("\""); } } /// Emit an name/value pair for an attribute (e.g. "x: 3") @@ -30431,7 +33069,7 @@ var ts; } function emitJsxElement(openingNode, children) { var syntheticReactRef = ts.createSynthesizedNode(69 /* Identifier */); - syntheticReactRef.text = "React"; + syntheticReactRef.text = compilerOptions.reactNamespace ? compilerOptions.reactNamespace : "React"; syntheticReactRef.parent = openingNode; // Call React.createElement(tag, ... emitLeadingComments(openingNode); @@ -30448,38 +33086,38 @@ var ts; // 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 */; })) { + if (ts.forEach(attrs, function (attr) { return attr.kind === 242 /* 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 */) { + for (var i = 0; i < attrs.length; i++) { + if (attrs[i].kind === 242 /* JsxSpreadAttribute */) { // If this is the first argument, we need to emit a {} as the first argument - if (i_1 === 0) { + if (i === 0) { write("{}, "); } if (haveOpenedObjectLiteral) { write("}"); haveOpenedObjectLiteral = false; } - if (i_1 > 0) { + if (i > 0) { write(", "); } - emit(attrs[i_1].expression); + emit(attrs[i].expression); } else { - ts.Debug.assert(attrs[i_1].kind === 238 /* JsxAttribute */); + ts.Debug.assert(attrs[i].kind === 241 /* JsxAttribute */); if (haveOpenedObjectLiteral) { write(", "); } else { haveOpenedObjectLiteral = true; - if (i_1 > 0) { + if (i > 0) { write(", "); } write("{"); } - emitJsxAttribute(attrs[i_1]); + emitJsxAttribute(attrs[i]); } } if (haveOpenedObjectLiteral) @@ -30489,7 +33127,7 @@ var ts; else { // One object literal with all the attributes in them write("{"); - for (var i = 0; i < attrs.length; i++) { + for (var i = 0, n = attrs.length; i < n; i++) { if (i > 0) { write(", "); } @@ -30502,11 +33140,11 @@ var ts; if (children) { for (var i = 0; i < children.length; i++) { // Don't emit empty expressions - if (children[i].kind === 240 /* JsxExpression */ && !(children[i].expression)) { + if (children[i].kind === 243 /* JsxExpression */ && !(children[i].expression)) { continue; } // Don't emit empty strings - if (children[i].kind === 236 /* JsxText */) { + if (children[i].kind === 239 /* JsxText */) { var text = getTextToEmit(children[i]); if (text !== undefined) { write(", \""); @@ -30524,11 +33162,11 @@ var ts; write(")"); // closes "React.createElement(" emitTrailingComments(openingNode); } - if (node.kind === 233 /* JsxElement */) { + if (node.kind === 236 /* JsxElement */) { emitJsxElement(node.openingElement, node.children); } else { - ts.Debug.assert(node.kind === 234 /* JsxSelfClosingElement */); + ts.Debug.assert(node.kind === 237 /* JsxSelfClosingElement */); emitJsxElement(node); } } @@ -30550,11 +33188,11 @@ var ts; if (i > 0) { write(" "); } - if (attribs[i].kind === 239 /* JsxSpreadAttribute */) { + if (attribs[i].kind === 242 /* JsxSpreadAttribute */) { emitJsxSpreadAttribute(attribs[i]); } else { - ts.Debug.assert(attribs[i].kind === 238 /* JsxAttribute */); + ts.Debug.assert(attribs[i].kind === 241 /* JsxAttribute */); emitJsxAttribute(attribs[i]); } } @@ -30562,11 +33200,11 @@ var ts; function emitJsxOpeningOrSelfClosingElement(node) { write("<"); emit(node.tagName); - if (node.attributes.length > 0 || (node.kind === 234 /* JsxSelfClosingElement */)) { + if (node.attributes.length > 0 || (node.kind === 237 /* JsxSelfClosingElement */)) { write(" "); } emitAttributes(node.attributes); - if (node.kind === 234 /* JsxSelfClosingElement */) { + if (node.kind === 237 /* JsxSelfClosingElement */) { write("/>"); } else { @@ -30585,11 +33223,11 @@ var ts; } emitJsxClosingElement(node.closingElement); } - if (node.kind === 233 /* JsxElement */) { + if (node.kind === 236 /* JsxElement */) { emitJsxElement(node); } else { - ts.Debug.assert(node.kind === 234 /* JsxSelfClosingElement */); + ts.Debug.assert(node.kind === 237 /* JsxSelfClosingElement */); emitJsxOpeningOrSelfClosingElement(node); } } @@ -30597,11 +33235,11 @@ var ts; // 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 */); + ts.Debug.assert(node.kind !== 166 /* BindingElement */); if (node.kind === 9 /* StringLiteral */) { emitLiteral(node); } - else if (node.kind === 136 /* ComputedPropertyName */) { + else if (node.kind === 137 /* 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: @@ -30637,7 +33275,7 @@ var ts; write(node.text); } else { - writeTextOfNode(currentSourceFile, node); + writeTextOfNode(currentText, node); } write("\""); } @@ -30645,73 +33283,70 @@ var ts; 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 */: + case 167 /* ArrayLiteralExpression */: + case 192 /* AsExpression */: + case 184 /* BinaryExpression */: + case 171 /* CallExpression */: + case 244 /* CaseClause */: + case 137 /* ComputedPropertyName */: + case 185 /* ConditionalExpression */: + case 140 /* Decorator */: + case 178 /* DeleteExpression */: + case 200 /* DoStatement */: + case 170 /* ElementAccessExpression */: + case 230 /* ExportAssignment */: + case 198 /* ExpressionStatement */: + case 191 /* ExpressionWithTypeArguments */: + case 202 /* ForStatement */: + case 203 /* ForInStatement */: + case 204 /* ForOfStatement */: + case 199 /* IfStatement */: + case 240 /* JsxClosingElement */: + case 237 /* JsxSelfClosingElement */: + case 238 /* JsxOpeningElement */: + case 242 /* JsxSpreadAttribute */: + case 243 /* JsxExpression */: + case 172 /* NewExpression */: + case 175 /* ParenthesizedExpression */: + case 183 /* PostfixUnaryExpression */: + case 182 /* PrefixUnaryExpression */: + case 207 /* ReturnStatement */: + case 249 /* ShorthandPropertyAssignment */: + case 188 /* SpreadElementExpression */: + case 209 /* SwitchStatement */: + case 173 /* TaggedTemplateExpression */: + case 193 /* TemplateSpan */: + case 211 /* ThrowStatement */: + case 174 /* TypeAssertionExpression */: + case 179 /* TypeOfExpression */: + case 180 /* VoidExpression */: + case 201 /* WhileStatement */: + case 208 /* WithStatement */: + case 187 /* YieldExpression */: return true; - case 163 /* BindingElement */: - case 247 /* EnumMember */: - case 138 /* Parameter */: - case 245 /* PropertyAssignment */: - case 141 /* PropertyDeclaration */: - case 211 /* VariableDeclaration */: + case 166 /* BindingElement */: + case 250 /* EnumMember */: + case 139 /* Parameter */: + case 248 /* PropertyAssignment */: + case 142 /* PropertyDeclaration */: + case 214 /* VariableDeclaration */: return parent.initializer === node; - case 166 /* PropertyAccessExpression */: + case 169 /* PropertyAccessExpression */: return parent.expression === node; - case 174 /* ArrowFunction */: - case 173 /* FunctionExpression */: + case 177 /* ArrowFunction */: + case 176 /* FunctionExpression */: return parent.body === node; - case 221 /* ImportEqualsDeclaration */: + case 224 /* ImportEqualsDeclaration */: return parent.moduleReference === node; - case 135 /* QualifiedName */: + case 136 /* 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 */) { + if (container.kind === 251 /* SourceFile */) { // Identifier references module export if (modulekind !== 5 /* ES6 */ && modulekind !== 4 /* System */) { write("exports."); @@ -30727,17 +33362,17 @@ var ts; if (modulekind !== 5 /* ES6 */) { var declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { - if (declaration.kind === 223 /* ImportClause */) { + if (declaration.kind === 226 /* ImportClause */) { // Identifier references default import write(getGeneratedNameForNode(declaration.parent)); write(languageVersion === 0 /* ES3 */ ? "[\"default\"]" : ".default"); return; } - else if (declaration.kind === 226 /* ImportSpecifier */) { + else if (declaration.kind === 229 /* 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); + var name_24 = declaration.propertyName || declaration.name; + var identifier = ts.getTextOfNodeFromSourceText(currentText, name_24); if (languageVersion === 0 /* ES3 */ && identifier === "default") { write("[\"default\"]"); } @@ -30749,55 +33384,79 @@ var ts; } } } - if (languageVersion !== 2 /* ES6 */) { - var declaration = resolver.getReferencedNestedRedeclaration(node); + if (languageVersion < 2 /* ES6 */) { + var declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration) { write(getGeneratedNameForNode(declaration.name)); return; } } + else if (resolver.getNodeCheckFlags(node) & 1048576 /* BodyScopedClassBinding */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + var declaration = resolver.getReferencedValueDeclaration(node); + if (declaration) { + var classAlias = decoratedClassAliases[ts.getNodeId(declaration)]; + if (classAlias !== undefined) { + write(classAlias); + return; + } + } + } } if (ts.nodeIsSynthesized(node)) { write(node.text); } else { - writeTextOfNode(currentSourceFile, node); + writeTextOfNode(currentText, node); } } - function isNameOfNestedRedeclaration(node) { + function isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(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); + var parent_8 = node.parent; + switch (parent_8.kind) { + case 166 /* BindingElement */: + case 217 /* ClassDeclaration */: + case 220 /* EnumDeclaration */: + case 214 /* VariableDeclaration */: + return parent_8.name === node && resolver.isDeclarationWithCollidingName(parent_8); } } return false; } function emitIdentifier(node) { + if (convertedLoopState) { + if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { + // in converted loop body arguments cannot be used directly. + var name_25 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); + write(name_25); + return; + } + } if (!node.parent) { write(node.text); } else if (isExpressionIdentifier(node)) { emitExpressionIdentifier(node); } - else if (isNameOfNestedRedeclaration(node)) { + else if (isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node)) { write(getGeneratedNameForNode(node)); } else if (ts.nodeIsSynthesized(node)) { write(node.text); } else { - writeTextOfNode(currentSourceFile, node); + writeTextOfNode(currentText, node); } } function emitThis(node) { if (resolver.getNodeCheckFlags(node) & 2 /* LexicalThis */) { write("_this"); } + else if (convertedLoopState) { + write(convertedLoopState.thisName || (convertedLoopState.thisName = makeUniqueName("this"))); + } else { write("this"); } @@ -30871,10 +33530,10 @@ var ts; } } function needsParenthesisForAwaitExpressionAsYield(node) { - if (node.parent.kind === 181 /* BinaryExpression */ && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { + if (node.parent.kind === 184 /* BinaryExpression */ && !ts.isAssignmentOperator(node.parent.operatorToken.kind)) { return true; } - else if (node.parent.kind === 182 /* ConditionalExpression */ && node.parent.condition === node) { + else if (node.parent.kind === 185 /* ConditionalExpression */ && node.parent.condition === node) { return true; } return false; @@ -30882,11 +33541,11 @@ var ts; function needsParenthesisForPropertyAccessOrInvocation(node) { switch (node.kind) { case 69 /* Identifier */: - case 164 /* ArrayLiteralExpression */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: - case 168 /* CallExpression */: - case 172 /* ParenthesizedExpression */: + case 167 /* ArrayLiteralExpression */: + case 169 /* PropertyAccessExpression */: + case 170 /* ElementAccessExpression */: + case 171 /* CallExpression */: + case 175 /* 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; @@ -30906,17 +33565,17 @@ var ts; write(", "); } var e = elements[pos]; - if (e.kind === 185 /* SpreadElementExpression */) { + if (e.kind === 188 /* SpreadElementExpression */) { e = e.expression; emitParenthesizedIf(e, /*parenthesized*/ group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); pos++; - if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 164 /* ArrayLiteralExpression */) { + if (pos === length && group === 0 && needsUniqueCopy && e.kind !== 167 /* ArrayLiteralExpression */) { write(".slice()"); } } else { var i = pos; - while (i < length && elements[i].kind !== 185 /* SpreadElementExpression */) { + while (i < length && elements[i].kind !== 188 /* SpreadElementExpression */) { i++; } write("["); @@ -30939,7 +33598,7 @@ var ts; } } function isSpreadElementExpression(node) { - return node.kind === 185 /* SpreadElementExpression */; + return node.kind === 188 /* SpreadElementExpression */; } function emitArrayLiteral(node) { var elements = node.elements; @@ -30948,11 +33607,11 @@ var ts; } else if (languageVersion >= 2 /* ES6 */ || !ts.forEach(elements, isSpreadElementExpression)) { write("["); - emitLinePreservingList(node, node.elements, elements.hasTrailingComma, /*spacesBetweenBraces:*/ false); + emitLinePreservingList(node, node.elements, elements.hasTrailingComma, /*spacesBetweenBraces*/ false); write("]"); } else { - emitListWithSpread(elements, /*needsUniqueCopy*/ true, /*multiLine*/ (node.flags & 2048 /* MultiLine */) !== 0, + emitListWithSpread(elements, /*needsUniqueCopy*/ true, /*multiLine*/ (node.flags & 1024 /* MultiLine */) !== 0, /*trailingComma*/ elements.hasTrailingComma, /*useConcat*/ true); } } @@ -30968,10 +33627,10 @@ var ts; // 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); + emitLinePreservingList(node, properties, /*allowTrailingComma*/ languageVersion >= 1 /* ES5 */, /*spacesBetweenBraces*/ true); } else { - var multiLine = (node.flags & 2048 /* MultiLine */) !== 0; + var multiLine = (node.flags & 1024 /* MultiLine */) !== 0; if (!multiLine) { write(" "); } @@ -30990,7 +33649,7 @@ var ts; write("}"); } function emitDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex) { - var multiLine = (node.flags & 2048 /* MultiLine */) !== 0; + var multiLine = (node.flags & 1024 /* MultiLine */) !== 0; var properties = node.properties; write("("); if (multiLine) { @@ -31009,7 +33668,7 @@ var ts; writeComma(); var property = properties[i]; emitStart(property); - if (property.kind === 145 /* GetAccessor */ || property.kind === 146 /* SetAccessor */) { + if (property.kind === 146 /* GetAccessor */ || property.kind === 147 /* SetAccessor */) { // TODO (drosen): Reconcile with 'emitMemberFunctions'. var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property !== accessors.firstAccessor) { @@ -31061,13 +33720,13 @@ var ts; emitMemberAccessForPropertyName(property.name); emitEnd(property.name); write(" = "); - if (property.kind === 245 /* PropertyAssignment */) { + if (property.kind === 248 /* PropertyAssignment */) { emit(property.initializer); } - else if (property.kind === 246 /* ShorthandPropertyAssignment */) { + else if (property.kind === 249 /* ShorthandPropertyAssignment */) { emitExpressionIdentifier(property.name); } - else if (property.kind === 143 /* MethodDeclaration */) { + else if (property.kind === 144 /* MethodDeclaration */) { emitFunctionDeclaration(property); } else { @@ -31101,7 +33760,7 @@ var ts; // 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 */) { + if (properties[i].name.kind === 137 /* ComputedPropertyName */) { numInitialNonComputedProperties = i; break; } @@ -31117,21 +33776,21 @@ var ts; emitObjectLiteralBody(node, properties.length); } function createBinaryExpression(left, operator, right, startsOnNewLine) { - var result = ts.createSynthesizedNode(181 /* BinaryExpression */, startsOnNewLine); + var result = ts.createSynthesizedNode(184 /* 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 */); + var result = ts.createSynthesizedNode(169 /* 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 */); + var result = ts.createSynthesizedNode(170 /* ElementAccessExpression */); result.expression = parenthesizeForAccess(expression); result.argumentExpression = argumentExpression; return result; @@ -31139,7 +33798,7 @@ var ts; 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 */) { + while (expr.kind === 174 /* TypeAssertionExpression */ || expr.kind === 192 /* AsExpression */) { expr = expr.expression; } // isLeftHandSideExpression is almost the correct criterion for when it is not necessary @@ -31151,11 +33810,11 @@ var ts; // 1.x -> not the same as (1).x // if (ts.isLeftHandSideExpression(expr) && - expr.kind !== 169 /* NewExpression */ && + expr.kind !== 172 /* NewExpression */ && expr.kind !== 8 /* NumericLiteral */) { return expr; } - var node = ts.createSynthesizedNode(172 /* ParenthesizedExpression */); + var node = ts.createSynthesizedNode(175 /* ParenthesizedExpression */); node.expression = expr; return node; } @@ -31190,12 +33849,12 @@ var ts; // 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 */; + return container && container.kind !== 251 /* 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); + writeTextOfNode(currentText, 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 { @@ -31205,7 +33864,7 @@ var ts; // let obj = { y }; // } // Here we need to emit obj = { y : m.y } regardless of the output target. - if (languageVersion < 2 /* ES6 */ || isNamespaceExportReference(node.name)) { + if (modulekind !== 5 /* ES6 */ || isNamespaceExportReference(node.name)) { // Emit identifier as an identifier write(": "); emit(node.name); @@ -31220,7 +33879,7 @@ var ts; if (constantValue !== undefined) { write(constantValue.toString()); if (!compilerOptions.removeComments) { - var propertyName = node.kind === 166 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); + var propertyName = node.kind === 169 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); write(" /* " + propertyName + " */"); } return true; @@ -31231,7 +33890,7 @@ var ts; if (compilerOptions.isolatedModules) { return undefined; } - return node.kind === 166 /* PropertyAccessExpression */ || node.kind === 167 /* ElementAccessExpression */ + return node.kind === 169 /* PropertyAccessExpression */ || node.kind === 170 /* ElementAccessExpression */ ? resolver.getConstantValue(node) : undefined; } @@ -31258,15 +33917,23 @@ var ts; if (tryEmitConstantValue(node)) { return; } + if (languageVersion === 2 /* ES6 */ && + node.expression.kind === 95 /* SuperKeyword */ && + isInAsyncMethodWithSuperInES6(node)) { + var name_26 = ts.createSynthesizedNode(9 /* StringLiteral */); + name_26.text = node.name.text; + emitSuperAccessInAsyncMethod(node.expression, name_26); + 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; + var shouldEmitSpace = false; 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); + var text = ts.getTextOfNodeFromSourceText(currentText, node.expression); shouldEmitSpace = text.indexOf(ts.tokenToString(21 /* DotToken */)) < 0; } else { @@ -31320,25 +33987,34 @@ var ts; } emitExpressionIdentifier(node); break; - case 135 /* QualifiedName */: + case 136 /* QualifiedName */: emitQualifiedNameAsExpression(node, useFallback); break; + default: + emitNodeWithoutSourceMap(node); + break; } } function emitIndexedAccess(node) { if (tryEmitConstantValue(node)) { return; } + if (languageVersion === 2 /* ES6 */ && + node.expression.kind === 95 /* SuperKeyword */ && + isInAsyncMethodWithSuperInES6(node)) { + emitSuperAccessInAsyncMethod(node.expression, node.argumentExpression); + return; + } emit(node.expression); write("["); emit(node.argumentExpression); write("]"); } function hasSpreadElement(elements) { - return ts.forEach(elements, function (e) { return e.kind === 185 /* SpreadElementExpression */; }); + return ts.forEach(elements, function (e) { return e.kind === 188 /* SpreadElementExpression */; }); } function skipParentheses(node) { - while (node.kind === 172 /* ParenthesizedExpression */ || node.kind === 171 /* TypeAssertionExpression */ || node.kind === 189 /* AsExpression */) { + while (node.kind === 175 /* ParenthesizedExpression */ || node.kind === 174 /* TypeAssertionExpression */ || node.kind === 192 /* AsExpression */) { node = node.expression; } return node; @@ -31359,13 +34035,13 @@ var ts; function emitCallWithSpread(node) { var target; var expr = skipParentheses(node.expression); - if (expr.kind === 166 /* PropertyAccessExpression */) { + if (expr.kind === 169 /* PropertyAccessExpression */) { // Target will be emitted as "this" argument target = emitCallTarget(expr.expression); write("."); emit(expr.name); } - else if (expr.kind === 167 /* ElementAccessExpression */) { + else if (expr.kind === 170 /* ElementAccessExpression */) { // Target will be emitted as "this" argument target = emitCallTarget(expr.expression); write("["); @@ -31398,23 +34074,42 @@ var ts; emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*trailingComma*/ false, /*useConcat*/ true); write(")"); } + function isInAsyncMethodWithSuperInES6(node) { + if (languageVersion === 2 /* ES6 */) { + var container = ts.getSuperContainer(node, /*includeFunctions*/ false); + if (container && resolver.getNodeCheckFlags(container) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */)) { + return true; + } + } + return false; + } + function emitSuperAccessInAsyncMethod(superNode, argumentExpression) { + var container = ts.getSuperContainer(superNode, /*includeFunctions*/ false); + var isSuperBinding = resolver.getNodeCheckFlags(container) & 4096 /* AsyncMethodWithSuperBinding */; + write("_super("); + emit(argumentExpression); + write(isSuperBinding ? ").value" : ")"); + } function emitCallExpression(node) { if (languageVersion < 2 /* ES6 */ && hasSpreadElement(node.arguments)) { emitCallWithSpread(node); return; } + var expression = node.expression; var superCall = false; - if (node.expression.kind === 95 /* SuperKeyword */) { - emitSuper(node.expression); + var isAsyncMethodWithSuper = false; + if (expression.kind === 95 /* SuperKeyword */) { + emitSuper(expression); superCall = true; } else { - emit(node.expression); - superCall = node.expression.kind === 166 /* PropertyAccessExpression */ && node.expression.expression.kind === 95 /* SuperKeyword */; + superCall = ts.isSuperPropertyOrElementAccess(expression); + isAsyncMethodWithSuper = superCall && isInAsyncMethodWithSuperInES6(node); + emit(expression); } - if (superCall && languageVersion < 2 /* ES6 */) { + if (superCall && (languageVersion < 2 /* ES6 */ || isAsyncMethodWithSuper)) { write(".call("); - emitThis(node.expression); + emitThis(expression); if (node.arguments.length) { write(", "); emitCommaList(node.arguments); @@ -31452,7 +34147,7 @@ var ts; write(".bind.apply("); emit(target); write(", [void 0].concat("); - emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiline*/ false, /*trailingComma*/ false, /*useConcat*/ false); + emitListWithSpread(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*trailingComma*/ false, /*useConcat*/ false); write(")))"); write("()"); } @@ -31479,12 +34174,12 @@ var ts; // 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 */) { + if (!ts.nodeIsSynthesized(node) && node.parent.kind !== 177 /* ArrowFunction */) { + if (node.expression.kind === 174 /* TypeAssertionExpression */ || node.expression.kind === 192 /* 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 */) { + while (operand.kind === 174 /* TypeAssertionExpression */ || operand.kind === 192 /* AsExpression */) { operand = operand.expression; } // We have an expression of the form: (SubExpr) @@ -31495,15 +34190,15 @@ var ts; // (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 */)) { + if (operand.kind !== 182 /* PrefixUnaryExpression */ && + operand.kind !== 180 /* VoidExpression */ && + operand.kind !== 179 /* TypeOfExpression */ && + operand.kind !== 178 /* DeleteExpression */ && + operand.kind !== 183 /* PostfixUnaryExpression */ && + operand.kind !== 172 /* NewExpression */ && + !(operand.kind === 171 /* CallExpression */ && node.parent.kind === 172 /* NewExpression */) && + !(operand.kind === 176 /* FunctionExpression */ && node.parent.kind === 171 /* CallExpression */) && + !(operand.kind === 8 /* NumericLiteral */ && node.parent.kind === 169 /* PropertyAccessExpression */)) { emit(operand); return; } @@ -31532,14 +34227,15 @@ var ts; 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 isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 214 /* VariableDeclaration */ || node.parent.kind === 166 /* BindingElement */); var targetDeclaration = isVariableDeclarationOrBindingElement ? node.parent : resolver.getReferencedValueDeclaration(node); return isSourceFileLevelDeclarationInSystemJsModule(targetDeclaration, /*isExported*/ true); } function emitPrefixUnaryExpression(node) { - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); + var exportChanged = (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) && + isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); if (exportChanged) { // emit // ++x @@ -31562,7 +34258,7 @@ var ts; // 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 */) { + if (node.operand.kind === 182 /* PrefixUnaryExpression */) { var operand = node.operand; if (node.operator === 35 /* PlusToken */ && (operand.operator === 35 /* PlusToken */ || operand.operator === 41 /* PlusPlusToken */)) { write(" "); @@ -31613,15 +34309,15 @@ var ts; * we we emit variable statement 'var' should be dropped. */ function isSourceFileLevelDeclarationInSystemJsModule(node, isExported) { - if (!node || languageVersion >= 2 /* ES6 */ || !isCurrentFileSystemExternalModule()) { + if (!node || !isCurrentFileSystemExternalModule()) { return false; } - var current = node; + var current = ts.getRootDeclaration(node).parent; while (current) { - if (current.kind === 248 /* SourceFile */) { - return !isExported || ((ts.getCombinedNodeFlags(node) & 1 /* Export */) !== 0); + if (current.kind === 251 /* SourceFile */) { + return !isExported || ((ts.getCombinedNodeFlags(node) & 2 /* Export */) !== 0); } - else if (ts.isFunctionLike(current) || current.kind === 219 /* ModuleBlock */) { + else if (ts.isDeclaration(current)) { return false; } else { @@ -31636,19 +34332,19 @@ var ts; function emitExponentiationOperator(node) { var leftHandSideExpression = node.left; if (node.operatorToken.kind === 60 /* AsteriskAsteriskEqualsToken */) { - var synthesizedLHS; + var synthesizedLHS = void 0; 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 = ts.createSynthesizedNode(170 /* ElementAccessExpression */, /*startsOnNewLine*/ false); + var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ 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); + emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, /*shouldEmitCommaBeforeAssignment*/ true, leftHandSideExpression.expression); } else { synthesizedLHS.argumentExpression = leftHandSideExpression.argumentExpression; @@ -31658,8 +34354,8 @@ var ts; 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 = ts.createSynthesizedNode(169 /* PropertyAccessExpression */, /*startsOnNewLine*/ false); + var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ false, /*shouldEmitCommaBeforeAssignment*/ false); synthesizedLHS.expression = identifier; synthesizedLHS.dotToken = leftHandSideExpression.dotToken; synthesizedLHS.name = leftHandSideExpression.name; @@ -31686,8 +34382,8 @@ var ts; } 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 */); + (node.left.kind === 168 /* ObjectLiteralExpression */ || node.left.kind === 167 /* ArrayLiteralExpression */)) { + emitDestructuring(node, node.parent.kind === 198 /* ExpressionStatement */); } else { var exportChanged = node.operatorToken.kind >= 56 /* FirstAssignment */ && @@ -31752,7 +34448,7 @@ var ts; } } function isSingleLineEmptyBlock(node) { - if (node && node.kind === 192 /* Block */) { + if (node && node.kind === 195 /* Block */) { var block = node; return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); } @@ -31766,22 +34462,20 @@ var ts; } emitToken(15 /* OpenBraceToken */, node.pos); increaseIndent(); - scopeEmitStart(node.parent); - if (node.kind === 219 /* ModuleBlock */) { - ts.Debug.assert(node.parent.kind === 218 /* ModuleDeclaration */); + if (node.kind === 222 /* ModuleBlock */) { + ts.Debug.assert(node.parent.kind === 221 /* ModuleDeclaration */); emitCaptureThisForNodeIfNecessary(node.parent); } emitLines(node.statements); - if (node.kind === 219 /* ModuleBlock */) { + if (node.kind === 222 /* ModuleBlock */) { emitTempDeclarations(/*newLine*/ true); } decreaseIndent(); writeLine(); emitToken(16 /* CloseBraceToken */, node.statements.end); - scopeEmitEnd(); } function emitEmbeddedStatement(node) { - if (node.kind === 192 /* Block */) { + if (node.kind === 195 /* Block */) { write(" "); emit(node); } @@ -31793,7 +34487,7 @@ var ts; } } function emitExpressionStatement(node) { - emitParenthesizedIf(node.expression, /*parenthesized*/ node.expression.kind === 174 /* ArrowFunction */); + emitParenthesizedIf(node.expression, /*parenthesized*/ node.expression.kind === 177 /* ArrowFunction */); write(";"); } function emitIfStatement(node) { @@ -31806,7 +34500,7 @@ var ts; if (node.elseStatement) { writeLine(); emitToken(80 /* ElseKeyword */, node.thenStatement.end); - if (node.elseStatement.kind === 196 /* IfStatement */) { + if (node.elseStatement.kind === 199 /* IfStatement */) { write(" "); emit(node.elseStatement); } @@ -31816,9 +34510,17 @@ var ts; } } function emitDoStatement(node) { + emitLoop(node, emitDoStatementWorker); + } + function emitDoStatementWorker(node, loop) { write("do"); - emitEmbeddedStatement(node.statement); - if (node.statement.kind === 192 /* Block */) { + if (loop) { + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); + } + else { + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); + } + if (node.statement.kind === 195 /* Block */) { write(" "); } else { @@ -31829,47 +34531,55 @@ var ts; write(");"); } function emitWhileStatement(node) { + emitLoop(node, emitWhileStatementWorker); + } + function emitWhileStatementWorker(node, loop) { write("while ("); emit(node.expression); write(")"); - emitEmbeddedStatement(node.statement); + if (loop) { + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); + } + else { + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); + } } /** * 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) { + function tryEmitStartOfVariableDeclarationList(decl) { if (shouldHoistVariable(decl, /*checkIfSourceFileLevelDecl*/ true)) { // variables in variable declaration list were already hoisted return false; } - var tokenKind = 102 /* VarKeyword */; + if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 24576 /* BlockScoped */) === 0) { + // we are inside a converted loop - this can only happen in downlevel scenarios + // record names for all variable declarations + for (var _a = 0, _b = decl.declarations; _a < _b.length; _a++) { + var varDecl = _b[_a]; + hoistVariableDeclarationFromLoop(convertedLoopState, varDecl); + } + return false; + } + emitStart(decl); if (decl && languageVersion >= 2 /* ES6 */) { if (ts.isLet(decl)) { - tokenKind = 108 /* LetKeyword */; + write("let "); } else if (ts.isConst(decl)) { - tokenKind = 74 /* ConstKeyword */; + write("const "); + } + else { + write("var "); } - } - 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; - } + write("var "); } + // Note here we specifically dont emit end so that if we are going to emit binding pattern + // we can alter the source map correctly return true; } function emitVariableDeclarationListSkippingUninitializedEntries(list) { @@ -31889,13 +34599,326 @@ var ts; } return started; } + function shouldConvertLoopBody(node) { + return languageVersion < 2 /* ES6 */ && + (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; + } + function emitLoop(node, loopEmitter) { + var shouldConvert = shouldConvertLoopBody(node); + if (!shouldConvert) { + loopEmitter(node, /* convertedLoop*/ undefined); + } + else { + var loop = convertLoopBody(node); + if (node.parent.kind === 210 /* LabeledStatement */) { + // if parent of the loop was labeled statement - attach the label to loop skipping converted loop body + emitLabelAndColon(node.parent); + } + loopEmitter(node, loop); + } + } + function convertLoopBody(node) { + var functionName = makeUniqueName("_loop"); + var loopInitializer; + switch (node.kind) { + case 202 /* ForStatement */: + case 203 /* ForInStatement */: + case 204 /* ForOfStatement */: + var initializer = node.initializer; + if (initializer && initializer.kind === 215 /* VariableDeclarationList */) { + loopInitializer = node.initializer; + } + break; + } + var loopParameters; + var loopOutParameters; + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 24576 /* BlockScoped */)) { + // if loop initializer contains block scoped variables - they should be passed to converted loop body as parameters + loopParameters = []; + for (var _a = 0, _b = loopInitializer.declarations; _a < _b.length; _a++) { + var varDeclaration = _b[_a]; + processVariableDeclaration(varDeclaration.name); + } + } + var bodyIsBlock = node.statement.kind === 195 /* Block */; + var paramList = loopParameters ? loopParameters.join(", ") : ""; + writeLine(); + write("var " + functionName + " = function(" + paramList + ")"); + var convertedOuterLoopState = convertedLoopState; + convertedLoopState = { loopOutParameters: loopOutParameters }; + if (convertedOuterLoopState) { + // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. + // if outer converted loop has already accumulated some state - pass it through + if (convertedOuterLoopState.argumentsName) { + // outer loop has already used 'arguments' so we've already have some name to alias it + // use the same name in all nested loops + convertedLoopState.argumentsName = convertedOuterLoopState.argumentsName; + } + if (convertedOuterLoopState.thisName) { + // outer loop has already used 'this' so we've already have some name to alias it + // use the same name in all nested loops + convertedLoopState.thisName = convertedOuterLoopState.thisName; + } + if (convertedOuterLoopState.hoistedLocalVariables) { + // we've already collected some non-block scoped variable declarations in enclosing loop + // use the same storage in nested loop + convertedLoopState.hoistedLocalVariables = convertedOuterLoopState.hoistedLocalVariables; + } + } + write(" {"); + writeLine(); + increaseIndent(); + if (bodyIsBlock) { + emitLines(node.statement.statements); + } + else { + emit(node.statement); + } + writeLine(); + // end of loop body -> copy out parameter + copyLoopOutParameters(convertedLoopState, 1 /* ToOutParameter */, /*emitAsStatements*/ true); + decreaseIndent(); + writeLine(); + write("};"); + writeLine(); + if (loopOutParameters) { + // declare variables to hold out params for loop body + write("var "); + for (var i = 0; i < loopOutParameters.length; i++) { + if (i !== 0) { + write(", "); + } + write(loopOutParameters[i].outParamName); + } + write(";"); + writeLine(); + } + if (convertedLoopState.argumentsName) { + // if alias for arguments is set + if (convertedOuterLoopState) { + // pass it to outer converted loop + convertedOuterLoopState.argumentsName = convertedLoopState.argumentsName; + } + else { + // this is top level converted loop and we need to create an alias for 'arguments' object + write("var " + convertedLoopState.argumentsName + " = arguments;"); + writeLine(); + } + } + if (convertedLoopState.thisName) { + // if alias for this is set + if (convertedOuterLoopState) { + // pass it to outer converted loop + convertedOuterLoopState.thisName = convertedLoopState.thisName; + } + else { + // this is top level converted loop so we need to create an alias for 'this' here + // NOTE: + // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. + // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. + write("var " + convertedLoopState.thisName + " = this;"); + writeLine(); + } + } + if (convertedLoopState.hoistedLocalVariables) { + // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later + if (convertedOuterLoopState) { + // pass them to outer converted loop + convertedOuterLoopState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; + } + else { + // deduplicate and hoist collected variable declarations + write("var "); + var seen = void 0; + for (var _c = 0, _d = convertedLoopState.hoistedLocalVariables; _c < _d.length; _c++) { + var id = _d[_c]; + // Don't initialize seen unless we have at least one element. + // Emit a comma to separate for all but the first element. + if (!seen) { + seen = {}; + } + else { + write(", "); + } + if (!ts.hasProperty(seen, id.text)) { + emit(id); + seen[id.text] = id.text; + } + } + write(";"); + writeLine(); + } + } + var currentLoopState = convertedLoopState; + convertedLoopState = convertedOuterLoopState; + return { functionName: functionName, paramList: paramList, state: currentLoopState }; + function processVariableDeclaration(name) { + if (name.kind === 69 /* Identifier */) { + var nameText = isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(name) + ? getGeneratedNameForNode(name) + : name.text; + loopParameters.push(nameText); + if (resolver.getNodeCheckFlags(name.parent) & 2097152 /* NeedsLoopOutParameter */) { + var reassignedVariable = { originalName: name, outParamName: makeUniqueName("out_" + nameText) }; + (loopOutParameters || (loopOutParameters = [])).push(reassignedVariable); + } + } + else { + for (var _a = 0, _b = name.elements; _a < _b.length; _a++) { + var element = _b[_a]; + processVariableDeclaration(element.name); + } + } + } + } + function emitNormalLoopBody(node, emitAsEmbeddedStatement) { + var saveAllowedNonLabeledJumps; + if (convertedLoopState) { + // we get here if we are trying to emit normal loop loop inside converted loop + // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is + saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */; + } + if (emitAsEmbeddedStatement) { + emitEmbeddedStatement(node.statement); + } + else if (node.statement.kind === 195 /* Block */) { + emitLines(node.statement.statements); + } + else { + writeLine(); + emit(node.statement); + } + if (convertedLoopState) { + convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; + } + } + function copyLoopOutParameters(state, copyDirection, emitAsStatements) { + if (state.loopOutParameters) { + for (var _a = 0, _b = state.loopOutParameters; _a < _b.length; _a++) { + var outParam = _b[_a]; + if (copyDirection === 0 /* ToOriginal */) { + emitIdentifier(outParam.originalName); + write(" = " + outParam.outParamName); + } + else { + write(outParam.outParamName + " = "); + emitIdentifier(outParam.originalName); + } + if (emitAsStatements) { + write(";"); + writeLine(); + } + else { + write(", "); + } + } + } + } + function emitConvertedLoopCall(loop, emitAsBlock) { + if (emitAsBlock) { + write(" {"); + writeLine(); + increaseIndent(); + } + // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop + // simple loops are emitted as just 'loop()'; + var isSimpleLoop = !loop.state.nonLocalJumps && + !loop.state.labeledNonLocalBreaks && + !loop.state.labeledNonLocalContinues; + var loopResult = makeUniqueName("state"); + if (!isSimpleLoop) { + write("var " + loopResult + " = "); + } + write(loop.functionName + "(" + loop.paramList + ");"); + writeLine(); + copyLoopOutParameters(loop.state, 0 /* ToOriginal */, /*emitAsStatements*/ true); + if (!isSimpleLoop) { + // for non simple loops we need to store result returned from converted loop function and use it to do dispatching + // converted loop function can return: + // - object - used when body of the converted loop contains return statement. Property "value" of this object stores retuned value + // - string - used to dispatch jumps. "break" and "continue" are used to non-labeled jumps, other values are used to transfer control to + // different labels + writeLine(); + if (loop.state.nonLocalJumps & 8 /* Return */) { + write("if (typeof " + loopResult + " === \"object\") "); + if (convertedLoopState) { + // we are currently nested in another converted loop - return unwrapped result + write("return " + loopResult + ";"); + // propagate 'hasReturn' flag to outer loop + convertedLoopState.nonLocalJumps |= 8 /* Return */; + } + else { + // top level converted loop - return unwrapped value + write("return " + loopResult + ".value;"); + } + writeLine(); + } + if (loop.state.nonLocalJumps & 2 /* Break */) { + write("if (" + loopResult + " === \"break\") break;"); + writeLine(); + } + if (loop.state.nonLocalJumps & 4 /* Continue */) { + write("if (" + loopResult + " === \"continue\") continue;"); + writeLine(); + } + // in case of labeled breaks emit code that either breaks to some known label inside outer loop or delegates jump decision to outer loop + emitDispatchTableForLabeledJumps(loopResult, loop.state, convertedLoopState); + } + if (emitAsBlock) { + writeLine(); + decreaseIndent(); + write("}"); + } + function emitDispatchTableForLabeledJumps(loopResultVariable, currentLoop, outerLoop) { + if (!currentLoop.labeledNonLocalBreaks && !currentLoop.labeledNonLocalContinues) { + return; + } + write("switch(" + loopResultVariable + ") {"); + increaseIndent(); + emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalBreaks, /*isBreak*/ true, loopResultVariable, outerLoop); + emitDispatchEntriesForLabeledJumps(currentLoop.labeledNonLocalContinues, /*isBreak*/ false, loopResultVariable, outerLoop); + decreaseIndent(); + writeLine(); + write("}"); + } + function emitDispatchEntriesForLabeledJumps(table, isBreak, loopResultVariable, outerLoop) { + if (!table) { + return; + } + for (var labelText in table) { + var labelMarker = table[labelText]; + writeLine(); + write("case \"" + labelMarker + "\": "); + // if there are no outer converted loop or outer label in question is located inside outer converted loop + // then emit labeled break\continue + // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do + if (!outerLoop || (outerLoop.labels && outerLoop.labels[labelText])) { + if (isBreak) { + write("break "); + } + else { + write("continue "); + } + write(labelText + ";"); + } + else { + setLabeledJump(outerLoop, isBreak, labelText, labelMarker); + write("return " + loopResultVariable + ";"); + } + } + } + } function emitForStatement(node) { + emitLoop(node, emitForStatementWorker); + } + function emitForStatementWorker(node, loop) { var endPos = emitToken(86 /* ForKeyword */, node.pos); write(" "); endPos = emitToken(17 /* OpenParenToken */, endPos); - if (node.initializer && node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 215 /* VariableDeclarationList */) { var variableDeclarationList = node.initializer; - var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); + var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList); if (startIsEmitted) { emitCommaList(variableDeclarationList.declarations); } @@ -31911,26 +34934,36 @@ var ts; write(";"); emitOptional(" ", node.incrementor); write(")"); - emitEmbeddedStatement(node.statement); + if (loop) { + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); + } + else { + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); + } } function emitForInOrForOfStatement(node) { - if (languageVersion < 2 /* ES6 */ && node.kind === 201 /* ForOfStatement */) { - return emitDownLevelForOfStatement(node); + if (languageVersion < 2 /* ES6 */ && node.kind === 204 /* ForOfStatement */) { + emitLoop(node, emitDownLevelForOfStatementWorker); } + else { + emitLoop(node, emitForInOrForOfStatementWorker); + } + } + function emitForInOrForOfStatementWorker(node, loop) { var endPos = emitToken(86 /* ForKeyword */, node.pos); write(" "); endPos = emitToken(17 /* OpenParenToken */, endPos); - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 215 /* VariableDeclarationList */) { var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length >= 1) { - tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); + tryEmitStartOfVariableDeclarationList(variableDeclarationList); emit(variableDeclarationList.declarations[0]); } } else { emit(node.initializer); } - if (node.kind === 200 /* ForInStatement */) { + if (node.kind === 203 /* ForInStatement */) { write(" in "); } else { @@ -31938,9 +34971,14 @@ var ts; } emit(node.expression); emitToken(18 /* CloseParenToken */, node.expression.end); - emitEmbeddedStatement(node.statement); + if (loop) { + emitConvertedLoopCall(loop, /*emitAsBlock*/ true); + } + else { + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ true); + } } - function emitDownLevelForOfStatement(node) { + function emitDownLevelForOfStatementWorker(node, loop) { // The following ES6 code: // // for (let v of expr) { } @@ -31971,10 +35009,12 @@ var ts; // // 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 */; + // we can't reuse 'arr' because it might be modified within the body of the loop. var counter = createTempVariable(268435456 /* _i */); - var rhsReference = rhsIsIdentifier ? node.expression : createTempVariable(0 /* Auto */); + var rhsReference = ts.createSynthesizedNode(69 /* Identifier */); + rhsReference.text = node.expression.kind === 69 /* Identifier */ ? + makeUniqueName(node.expression.text) : + makeTempVariableName(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); @@ -31983,29 +35023,27 @@ var ts; emitNodeWithoutSourceMap(counter); write(" = 0"); emitEnd(node.expression); - if (!rhsIsIdentifier) { - // , _a = expr - write(", "); - emitStart(node.expression); - emitNodeWithoutSourceMap(rhsReference); - write(" = "); - emitNodeWithoutSourceMap(node.expression); - emitEnd(node.expression); - } + // , _a = expr + write(", "); + emitStart(node.expression); + emitNodeWithoutSourceMap(rhsReference); + write(" = "); + emitNodeWithoutSourceMap(node.expression); + emitEnd(node.expression); write("; "); // _i < _a.length; - emitStart(node.initializer); + emitStart(node.expression); emitNodeWithoutSourceMap(counter); write(" < "); emitNodeWithCommentsAndWithoutSourcemap(rhsReference); write(".length"); - emitEnd(node.initializer); + emitEnd(node.expression); write("; "); // _i++) - emitStart(node.initializer); + emitStart(node.expression); emitNodeWithoutSourceMap(counter); write("++"); - emitEnd(node.initializer); + emitEnd(node.expression); emitToken(18 /* CloseParenToken */, node.expression.end); // Body write(" {"); @@ -32015,7 +35053,7 @@ var ts; // let v = _a[_i]; var rhsIterationValue = createElementAccessExpression(rhsReference, counter); emitStart(node.initializer); - if (node.initializer.kind === 212 /* VariableDeclarationList */) { + if (node.initializer.kind === 215 /* VariableDeclarationList */) { write("var "); var variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -32045,7 +35083,7 @@ var ts; // 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 */) { + if (node.initializer.kind === 167 /* ArrayLiteralExpression */ || node.initializer.kind === 168 /* 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); @@ -32056,23 +35094,72 @@ var ts; } emitEnd(node.initializer); write(";"); - if (node.statement.kind === 192 /* Block */) { - emitLines(node.statement.statements); + if (loop) { + writeLine(); + emitConvertedLoopCall(loop, /*emitAsBlock*/ false); } else { - writeLine(); - emit(node.statement); + emitNormalLoopBody(node, /*emitAsEmbeddedStatement*/ false); } writeLine(); decreaseIndent(); write("}"); } function emitBreakOrContinueStatement(node) { - emitToken(node.kind === 203 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */, node.pos); + if (convertedLoopState) { + // check if we can emit break\continue as is + // it is possible if either + // - break\continue is statement labeled and label is located inside the converted loop + // - break\continue is non-labeled and located in non-converted loop\switch statement + var jump = node.kind === 206 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels[node.label.text]) || + (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); + if (!canUseBreakOrContinue) { + write("return "); + // explicit exit from loop -> copy out parameters + copyLoopOutParameters(convertedLoopState, 1 /* ToOutParameter */, /*emitAsStatements*/ false); + if (!node.label) { + if (node.kind === 206 /* BreakStatement */) { + convertedLoopState.nonLocalJumps |= 2 /* Break */; + write("\"break\";"); + } + else { + convertedLoopState.nonLocalJumps |= 4 /* Continue */; + write("\"continue\";"); + } + } + else { + var labelMarker = void 0; + if (node.kind === 206 /* BreakStatement */) { + labelMarker = "break-" + node.label.text; + setLabeledJump(convertedLoopState, /*isBreak*/ true, node.label.text, labelMarker); + } + else { + labelMarker = "continue-" + node.label.text; + setLabeledJump(convertedLoopState, /*isBreak*/ false, node.label.text, labelMarker); + } + write("\"" + labelMarker + "\";"); + } + return; + } + } + emitToken(node.kind === 206 /* BreakStatement */ ? 70 /* BreakKeyword */ : 75 /* ContinueKeyword */, node.pos); emitOptional(" ", node.label); write(";"); } function emitReturnStatement(node) { + if (convertedLoopState) { + convertedLoopState.nonLocalJumps |= 8 /* Return */; + write("return { value: "); + if (node.expression) { + emit(node.expression); + } + else { + write("void 0"); + } + write(" };"); + return; + } emitToken(94 /* ReturnKeyword */, node.pos); emitOptional(" ", node.expression); write(";"); @@ -32090,7 +35177,16 @@ var ts; emit(node.expression); endPos = emitToken(18 /* CloseParenToken */, node.expression.end); write(" "); + var saveAllowedNonLabeledJumps; + if (convertedLoopState) { + saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; + // for switch statement allow only non-labeled break + convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */; + } emitCaseBlock(node.caseBlock, endPos); + if (convertedLoopState) { + convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps; + } } function emitCaseBlock(node, startPos) { emitToken(15 /* OpenBraceToken */, startPos); @@ -32101,19 +35197,19 @@ var ts; 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)); + return ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node1.pos)) === + ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); } function nodeEndPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPosition(currentSourceFile, node1.end) === - ts.getLineOfLocalPosition(currentSourceFile, node2.end); + return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === + ts.getLineOfLocalPositionFromLineMap(currentLineMap, node2.end); } function nodeEndIsOnSameLineAsNodeStart(node1, node2) { - return ts.getLineOfLocalPosition(currentSourceFile, node1.end) === - ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); + return ts.getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) === + ts.getLineOfLocalPositionFromLineMap(currentLineMap, ts.skipTrivia(currentText, node2.pos)); } function emitCaseOrDefaultClause(node) { - if (node.kind === 241 /* CaseClause */) { + if (node.kind === 244 /* CaseClause */) { write("case "); emit(node.expression); write(":"); @@ -32160,15 +35256,29 @@ var ts; emitToken(76 /* DebuggerKeyword */, node.pos); write(";"); } - function emitLabelledStatement(node) { + function emitLabelAndColon(node) { emit(node.label); write(": "); + } + function emitLabeledStatement(node) { + if (!ts.isIterationStatement(node.statement, /* lookInLabeledStatements */ false) || !shouldConvertLoopBody(node.statement)) { + emitLabelAndColon(node); + } + if (convertedLoopState) { + if (!convertedLoopState.labels) { + convertedLoopState.labels = {}; + } + convertedLoopState.labels[node.label.text] = node.label.text; + } emit(node.statement); + if (convertedLoopState) { + convertedLoopState.labels[node.label.text] = undefined; + } } function getContainingModule(node) { do { node = node.parent; - } while (node && node.kind !== 218 /* ModuleDeclaration */); + } while (node && node.kind !== 221 /* ModuleDeclaration */); return node; } function emitContainingModuleName(node) { @@ -32177,7 +35287,7 @@ var ts; } function emitModuleMemberName(node) { emitStart(node.name); - if (ts.getCombinedNodeFlags(node) & 1 /* Export */) { + if (ts.getCombinedNodeFlags(node) & 2 /* Export */) { var container = getContainingModule(node); if (container) { write(getGeneratedNameForNode(container)); @@ -32193,22 +35303,22 @@ var ts; function createVoidZero() { var zero = ts.createSynthesizedNode(8 /* NumericLiteral */); zero.text = "0"; - var result = ts.createSynthesizedNode(177 /* VoidExpression */); + var result = ts.createSynthesizedNode(180 /* 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 */); + if (node.parent.kind === 251 /* SourceFile */) { + ts.Debug.assert(!!(node.flags & 512 /* Default */) || node.kind === 230 /* 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 */) { + if (!isEs6Module) { + if (languageVersion !== 0 /* ES3 */) { // default value of configurable, enumerable, writable are `false`. write("Object.defineProperty(exports, \"__esModule\", { value: true });"); writeLine(); } - else if (languageVersion === 0 /* ES3 */) { + else { write("exports.__esModule = true;"); writeLine(); } @@ -32217,7 +35327,7 @@ var ts; } } function emitExportMemberAssignment(node) { - if (node.flags & 1 /* Export */) { + if (node.flags & 2 /* Export */) { writeLine(); emitStart(node); // emit call to exporter only for top level nodes @@ -32225,7 +35335,7 @@ var ts; // emit export default as // export("default", ) write(exportFunctionForFile + "(\""); - if (node.flags & 1024 /* Default */) { + if (node.flags & 512 /* Default */) { write("default"); } else { @@ -32236,7 +35346,7 @@ var ts; write(")"); } else { - if (node.flags & 1024 /* Default */) { + if (node.flags & 512 /* Default */) { emitEs6ExportDefaultCompat(node); if (languageVersion === 0 /* ES3 */) { write("exports[\"default\"]"); @@ -32295,7 +35405,7 @@ var ts; * @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) { + function emitAssignment(name, value, shouldEmitCommaBeforeAssignment, nodeForSourceMap) { if (shouldEmitCommaBeforeAssignment) { write(", "); } @@ -32305,15 +35415,21 @@ var ts; 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); + var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 214 /* VariableDeclaration */ || name.parent.kind === 166 /* BindingElement */); + // If this is first var declaration, we need to start at var/let/const keyword instead + // otherwise use nodeForSourceMap as the start position + emitStart(isFirstVariableDeclaration(nodeForSourceMap) ? nodeForSourceMap.parent : nodeForSourceMap); + withTemporaryNoSourceMap(function () { + if (isVariableDeclarationOrBindingElement) { + emitModuleMemberName(name.parent); + } + else { + emit(name); + } + write(" = "); + emit(value); + }); + emitEnd(nodeForSourceMap, /*stopOverridingSpan*/ true); if (exportChanged) { write(")"); } @@ -32324,14 +35440,19 @@ var ts; * @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) { + function emitTempVariableAssignment(expression, canDefineTempVariablesInPlace, shouldEmitCommaBeforeAssignment, sourceMapNode) { var identifier = createTempVariable(0 /* Auto */); if (!canDefineTempVariablesInPlace) { recordTempDeclaration(identifier); } - emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment); + emitAssignment(identifier, expression, shouldEmitCommaBeforeAssignment, sourceMapNode || expression.parent); return identifier; } + function isFirstVariableDeclaration(root) { + return root.kind === 214 /* VariableDeclaration */ && + root.parent.kind === 215 /* VariableDeclarationList */ && + root.parent.declarations[0] === root; + } 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 @@ -32339,19 +35460,24 @@ var ts; // 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 */; + if (root.kind === 214 /* VariableDeclaration */) { + var isExported = ts.getCombinedNodeFlags(root) & 2 /* Export */; var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; } - else if (root.kind === 138 /* Parameter */) { + else if (root.kind === 139 /* Parameter */) { canDefineTempVariablesInPlace = true; } - if (root.kind === 181 /* BinaryExpression */) { + if (root.kind === 184 /* BinaryExpression */) { emitAssignmentExpression(root); } else { ts.Debug.assert(!isAssignmentExpressionStatement); + // If first variable declaration of variable statement correct the start location + if (isFirstVariableDeclaration(root)) { + // Use emit location of "var " as next emit start entry + sourceMap.changeEmitSourcePos(); + } emitBindingElement(root, value); } /** @@ -32363,27 +35489,28 @@ var ts; * @param reuseIdentifierExpressions true if identifier expressions can simply be returned; * false if it is necessary to always emit an identifier. */ - function ensureIdentifier(expr, reuseIdentifierExpressions) { + function ensureIdentifier(expr, reuseIdentifierExpressions, sourceMapNode) { if (expr.kind === 69 /* Identifier */ && reuseIdentifierExpressions) { return expr; } - var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0); + var identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0, sourceMapNode); emitCount++; return identifier; } - function createDefaultValueCheck(value, defaultValue) { + function createDefaultValueCheck(value, defaultValue, sourceMapNode) { // 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); + // If the temporary variable needs to be emitted use the source Map node for assignment of that statement + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, sourceMapNode); // Return the expression 'value === void 0 ? defaultValue : value' - var equals = ts.createSynthesizedNode(181 /* BinaryExpression */); + var equals = ts.createSynthesizedNode(184 /* 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 */); + var cond = ts.createSynthesizedNode(185 /* ConditionalExpression */); cond.condition = condition; cond.questionToken = ts.createSynthesizedNode(53 /* QuestionToken */); cond.whenTrue = whenTrue; @@ -32397,17 +35524,28 @@ var ts; 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); + var index; + var nameIsComputed = propName.kind === 137 /* ComputedPropertyName */; + if (nameIsComputed) { + // TODO to handle when we look into sourcemaps for computed properties, for now use propName + index = ensureIdentifier(propName.expression, /*reuseIdentifierExpressions*/ false, propName); } - return createPropertyAccessExpression(object, syntheticName); + else { + // We create a synthetic copy of the identifier in order to avoid the rewriting that might + // otherwise occur when the identifier is emitted. + index = ts.createSynthesizedNode(propName.kind); + // We need to unescape identifier here because when parsing an identifier prefixing with "__" + // the parser need to append "_" in order to escape colliding with magic identifiers such as "__proto__" + // Therefore, in order to correctly emit identifiers that are written in original TypeScript file, + // we will unescapeIdentifier to remove additional underscore (if no underscore is added, the function will return original input string) + index.text = ts.unescapeIdentifier(propName.text); + } + return !nameIsComputed && index.kind === 69 /* Identifier */ + ? createPropertyAccessExpression(object, index) + : createElementAccessExpression(object, index); } function createSliceCall(value, sliceIndex) { - var call = ts.createSynthesizedNode(168 /* CallExpression */); + var call = ts.createSynthesizedNode(171 /* CallExpression */); var sliceIdentifier = ts.createSynthesizedNode(69 /* Identifier */); sliceIdentifier.text = "slice"; call.expression = createPropertyAccessExpression(value, sliceIdentifier); @@ -32415,60 +35553,65 @@ var ts; call.arguments[0] = createNumericLiteral(sliceIndex); return call; } - function emitObjectLiteralAssignment(target, value) { + function emitObjectLiteralAssignment(target, value, sourceMapNode) { 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); + // When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, sourceMapNode); } - for (var _a = 0; _a < properties.length; _a++) { - var p = properties[_a]; - if (p.kind === 245 /* PropertyAssignment */ || p.kind === 246 /* ShorthandPropertyAssignment */) { + for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { + var p = properties_5[_a]; + if (p.kind === 248 /* PropertyAssignment */ || p.kind === 249 /* ShorthandPropertyAssignment */) { var propName = p.name; - var target_1 = p.kind === 246 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName; - emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName)); + var target_1 = p.kind === 249 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName; + // Assignment for target = value.propName should highligh whole property, hence use p as source map node + emitDestructuringAssignment(target_1, createPropertyAccessForDestructuringProperty(value, propName), p); } } } - function emitArrayLiteralAssignment(target, value) { + function emitArrayLiteralAssignment(target, value, sourceMapNode) { 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); + // When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, sourceMapNode); } 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))); + if (e.kind !== 190 /* OmittedExpression */) { + // Assignment for target = value.propName should highligh whole property, hence use e as source map node + if (e.kind !== 188 /* SpreadElementExpression */) { + emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i)), e); } else if (i === elements.length - 1) { - emitDestructuringAssignment(e.expression, createSliceCall(value, i)); + emitDestructuringAssignment(e.expression, createSliceCall(value, i), e); } } } } - function emitDestructuringAssignment(target, value) { - if (target.kind === 246 /* ShorthandPropertyAssignment */) { + function emitDestructuringAssignment(target, value, sourceMapNode) { + // When emitting target = value use source map node to highlight, including any temporary assignments needed for this + if (target.kind === 249 /* ShorthandPropertyAssignment */) { if (target.objectAssignmentInitializer) { - value = createDefaultValueCheck(value, target.objectAssignmentInitializer); + value = createDefaultValueCheck(value, target.objectAssignmentInitializer, sourceMapNode); } target = target.name; } - else if (target.kind === 181 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { - value = createDefaultValueCheck(value, target.right); + else if (target.kind === 184 /* BinaryExpression */ && target.operatorToken.kind === 56 /* EqualsToken */) { + value = createDefaultValueCheck(value, target.right, sourceMapNode); target = target.left; } - if (target.kind === 165 /* ObjectLiteralExpression */) { - emitObjectLiteralAssignment(target, value); + if (target.kind === 168 /* ObjectLiteralExpression */) { + emitObjectLiteralAssignment(target, value, sourceMapNode); } - else if (target.kind === 164 /* ArrayLiteralExpression */) { - emitArrayLiteralAssignment(target, value); + else if (target.kind === 167 /* ArrayLiteralExpression */) { + emitArrayLiteralAssignment(target, value, sourceMapNode); } else { - emitAssignment(target, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0); + emitAssignment(target, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0, sourceMapNode); emitCount++; } } @@ -32479,25 +35622,32 @@ var ts; emit(value); } else if (isAssignmentExpressionStatement) { - emitDestructuringAssignment(target, value); + // Source map node for root.left = root.right is root + // but if root is synthetic, which could be in below case, use the target which is { a } + // for ({a} of {a: string}) { + // } + emitDestructuringAssignment(target, value, ts.nodeIsSynthesized(root) ? target : root); } else { - if (root.parent.kind !== 172 /* ParenthesizedExpression */) { + if (root.parent.kind !== 175 /* ParenthesizedExpression */) { write("("); } - value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); - emitDestructuringAssignment(target, value); + // Temporary assignment needed to emit root should highlight whole binary expression + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, root); + // Source map node for root.left = root.right is root + emitDestructuringAssignment(target, value, root); write(", "); emit(value); - if (root.parent.kind !== 172 /* ParenthesizedExpression */) { + if (root.parent.kind !== 175 /* ParenthesizedExpression */) { write(")"); } } } function emitBindingElement(target, value) { + // Any temporary assignments needed to emit target = value should point to target if (target.initializer) { // Combine value and initializer - value = value ? createDefaultValueCheck(value, target.initializer) : target.initializer; + value = value ? createDefaultValueCheck(value, target.initializer, target) : target.initializer; } else if (!value) { // Use 'void 0' in absence of value and initializer @@ -32512,16 +35662,16 @@ var ts; // 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); + value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ numElements !== 0, target); } for (var i = 0; i < numElements; i++) { var element = elements[i]; - if (pattern.kind === 161 /* ObjectBindingPattern */) { + if (pattern.kind === 164 /* 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 */) { + else if (element.kind !== 190 /* OmittedExpression */) { if (!element.dotDotDotToken) { // Rewrite element to a declaration that accesses array element at index i emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); @@ -32533,7 +35683,7 @@ var ts; } } else { - emitAssignment(target.name, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0); + emitAssignment(target.name, value, /*shouldEmitCommaBeforeAssignment*/ emitCount > 0, target); emitCount++; } } @@ -32550,19 +35700,46 @@ var ts; } 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 */) { + if (!initializer && + languageVersion < 2 /* ES6 */ && + // for names - binding patterns that lack initializer there is no point to emit explicit initializer + // since downlevel codegen for destructuring will fail in the absence of initializer so all binding elements will say uninitialized + node.name.kind === 69 /* Identifier */) { + var container = ts.getEnclosingBlockScopeContainer(node); + var flags = resolver.getNodeCheckFlags(node); + // nested let bindings might need to be initialized explicitly to preserve ES6 semantic + // { let x = 1; } + // { let x; } // x here should be undefined. not 1 + // NOTES: + // Top level bindings never collide with anything and thus don't require explicit initialization. + // As for nested let bindings there are two cases: + // - nested let bindings that were not renamed definitely should be initialized explicitly + // { let x = 1; } + // { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } } + // Without explicit initialization code in /*1*/ can be executed even if some-condition is evaluated to false + // - renaming introduces fresh name that should not collide with any existing names, however renamed bindings sometimes also should be + // explicitly initialized. One particular case: non-captured binding declared inside loop body (but not in loop initializer) + // let x; + // for (;;) { + // let x; + // } + // in downlevel codegen inner 'x' will be renamed so it won't collide with outer 'x' however it will should be reset on every iteration + // as if it was declared anew. + // * Why non-captured binding - because if loop contains block scoped binding captured in some function then loop body will be rewritten + // to have a fresh scope on every iteration so everything will just work. + // * Why loop initializer is excluded - since we've introduced a fresh name it already will be undefined. + var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var emittedAsTopLevel = ts.isBlockScopedContainerTopLevel(container) || + (isCapturedInFunction && isDeclaredInLoop && container.kind === 195 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false)); + var emittedAsNestedLetDeclaration = ts.getCombinedNodeFlags(node) & 8192 /* Let */ && + !emittedAsTopLevel; + var emitExplicitInitializer = emittedAsNestedLetDeclaration && + container.kind !== 203 /* ForInStatement */ && + container.kind !== 204 /* ForOfStatement */ && + (!resolver.isDeclarationWithCollidingName(node) || + (isDeclaredInLoop && !isCapturedInFunction && !ts.isIterationStatement(container, /*lookInLabeledStatements*/ false))); + if (emitExplicitInitializer) { initializer = createVoidZero(); } } @@ -32580,7 +35757,7 @@ var ts; } } function emitExportVariableAssignments(node) { - if (node.kind === 187 /* OmittedExpression */) { + if (node.kind === 190 /* OmittedExpression */) { return; } var name = node.name; @@ -32591,20 +35768,14 @@ var ts; 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 */) && + return !!(node.flags & 2 /* Export */) && modulekind === 5 /* ES6 */ && - node.parent.kind === 248 /* SourceFile */; + node.parent.kind === 251 /* SourceFile */; } function emitVariableStatement(node) { var startIsEmitted = false; - if (node.flags & 1 /* Export */) { + if (node.flags & 2 /* Export */) { if (isES6ExportedDeclaration(node)) { // Exported ES6 module member write("export "); @@ -32631,7 +35802,7 @@ var ts; 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 */)) { + if (!(node.flags & 2 /* Export */)) { return true; } // If we are exporting, but it's a top-level ES6 module exports, @@ -32651,12 +35822,12 @@ var ts; function emitParameter(node) { if (languageVersion < 2 /* ES6 */) { if (ts.isBindingPattern(node.name)) { - var name_24 = createTempVariable(0 /* Auto */); + var name_27 = createTempVariable(0 /* Auto */); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_24); - emit(name_24); + tempParameters.push(name_27); + emit(name_27); } else { emit(node.name); @@ -32672,7 +35843,7 @@ var ts; } function emitDefaultValueAssignments(node) { if (languageVersion < 2 /* ES6 */) { - var tempIndex = 0; + var tempIndex_1 = 0; ts.forEach(node.parameters, function (parameter) { // A rest parameter cannot have a binding pattern or an initializer, // so let's just ignore it. @@ -32689,15 +35860,15 @@ var ts; writeLine(); write("var "); if (hasBindingElements) { - emitDestructuring(parameter, /*isAssignmentExpressionStatement*/ false, tempParameters[tempIndex]); + emitDestructuring(parameter, /*isAssignmentExpressionStatement*/ false, tempParameters[tempIndex_1]); } else { - emit(tempParameters[tempIndex]); + emit(tempParameters[tempIndex_1]); write(" = "); emit(initializer); } write(";"); - tempIndex++; + tempIndex_1++; } } else if (initializer) { @@ -32761,12 +35932,12 @@ var ts; } } function emitAccessor(node) { - write(node.kind === 145 /* GetAccessor */ ? "get " : "set "); + write(node.kind === 146 /* GetAccessor */ ? "get " : "set "); emit(node.name); emitSignatureAndBody(node); } function shouldEmitAsArrowFunction(node) { - return node.kind === 174 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */; + return node.kind === 177 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */; } function emitDeclarationName(node) { if (node.name) { @@ -32777,13 +35948,13 @@ var ts; } } function shouldEmitFunctionName(node) { - if (node.kind === 173 /* FunctionExpression */) { + if (node.kind === 176 /* FunctionExpression */) { // Emit name if one is present return !!node.name; } - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 216 /* 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 */; + return !!node.name || modulekind !== 5 /* ES6 */; } } function emitFunctionDeclaration(node) { @@ -32792,20 +35963,29 @@ var ts; } // 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 + var kind = node.kind, parent = node.parent; + if (kind !== 144 /* MethodDeclaration */ && + kind !== 143 /* MethodSignature */ && + parent && + parent.kind !== 248 /* PropertyAssignment */ && + parent.kind !== 171 /* CallExpression */ && + parent.kind !== 167 /* ArrayLiteralExpression */) { + // 1. Methods will emit comments at their assignment declaration sites. + // // 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: + // is done by emitNodeWithoutSourceMap which then call this function. + // In particular, we would like to avoid emit comments twice in following case: + // // 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 + // taken care of in emit list of arguments inside of 'emitCallExpression'. + // + // 4. If the function is in an array literal, 'emitLinePreservingList' will take care + // of leading comments. emitLeadingComments(node); } emitStart(node); @@ -32814,7 +35994,7 @@ var ts; if (!shouldEmitAsArrowFunction(node)) { if (isES6ExportedDeclaration(node)) { write("export "); - if (node.flags & 1024 /* Default */) { + if (node.flags & 512 /* Default */) { write("default "); } } @@ -32828,11 +36008,11 @@ var ts; emitDeclarationName(node); } emitSignatureAndBody(node); - if (modulekind !== 5 /* ES6 */ && node.kind === 213 /* FunctionDeclaration */ && node.parent === currentSourceFile && node.name) { + if (modulekind !== 5 /* ES6 */ && kind === 216 /* FunctionDeclaration */ && parent === currentSourceFile && node.name) { emitExportMemberAssignments(node.name); } emitEnd(node); - if (node.kind !== 143 /* MethodDeclaration */ && node.kind !== 142 /* MethodSignature */) { + if (kind !== 144 /* MethodDeclaration */ && kind !== 143 /* MethodSignature */) { emitTrailingComments(node); } } @@ -32865,9 +36045,8 @@ var ts; } 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; + var isArrowFunction = node.kind === 177 /* ArrowFunction */; + var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; // 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 @@ -32945,29 +36124,31 @@ var ts; write(" {"); increaseIndent(); writeLine(); + if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { + writeLines("\nconst _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n})(name => super[name], (name, value) => super[name] = value);"); + writeLine(); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { + write("const _super = name => super[name];"); + writeLine(); + } write("return"); } write(" __awaiter(this"); if (hasLexicalArguments) { - write(", arguments"); + write(", arguments, "); } else { - write(", void 0"); + write(", void 0, "); } - if (promiseConstructor) { - write(", "); - emitNodeWithoutSourceMap(promiseConstructor); + if (!promiseConstructor || (compilerOptions.noCustomAsyncPromise && languageVersion >= 2 /* ES6 */)) { + write("void 0"); } else { - write(", Promise"); + emitEntityNameAsExpression(promiseConstructor, /*useFallback*/ false); } // Emit the call to __awaiter. - if (hasLexicalArguments) { - write(", function* (_arguments)"); - } - else { - write(", function* ()"); - } + write(", function* ()"); // Emit the signature and body for the inner generator function. emitFunctionBody(node); write(")"); @@ -32986,7 +36167,7 @@ var ts; write(" { }"); } else { - if (node.body.kind === 192 /* Block */) { + if (node.body.kind === 195 /* Block */) { emitBlockFunctionBody(node, node.body); } else { @@ -32995,9 +36176,11 @@ var ts; } } function emitSignatureAndBody(node) { + var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; var saveTempVariables = tempVariables; var saveTempParameters = tempParameters; + convertedLoopState = undefined; tempFlags = 0; tempVariables = undefined; tempParameters = undefined; @@ -33010,7 +36193,7 @@ var ts; emitSignatureParameters(node); } var isAsync = ts.isAsyncFunctionLike(node); - if (isAsync && languageVersion === 2 /* ES6 */) { + if (isAsync) { emitAsyncFunctionBodyForES6(node); } else { @@ -33019,6 +36202,8 @@ var ts; if (!isES6ExportedDeclaration(node)) { emitExportMemberAssignment(node); } + ts.Debug.assert(convertedLoopState === undefined); + convertedLoopState = saveConvertedLoopState; tempFlags = saveTempFlags; tempVariables = saveTempVariables; tempParameters = saveTempParameters; @@ -33030,7 +36215,7 @@ var ts; emitRestParameter(node); } function emitExpressionFunctionBody(node, body) { - if (languageVersion < 2 /* ES6 */ || node.flags & 512 /* Async */) { + if (languageVersion < 2 /* ES6 */ || node.flags & 256 /* Async */) { emitDownLevelExpressionFunctionBody(node, body); return; } @@ -33041,17 +36226,16 @@ var ts; write(" "); // Unwrap all type assertions. var current = body; - while (current.kind === 171 /* TypeAssertionExpression */) { + while (current.kind === 174 /* TypeAssertionExpression */) { current = current.expression; } - emitParenthesizedIf(body, current.kind === 165 /* ObjectLiteralExpression */); + emitParenthesizedIf(body, current.kind === 168 /* ObjectLiteralExpression */); } function emitDownLevelExpressionFunctionBody(node, body) { write(" {"); - scopeEmitStart(node); increaseIndent(); var outPos = writer.getTextPos(); - emitDetachedComments(node.body); + emitDetachedCommentsAndUpdateCommentsInfo(node.body); emitFunctionBodyPreamble(node); var preambleEmitted = writer.getTextPos() !== outPos; decreaseIndent(); @@ -33071,8 +36255,10 @@ var ts; increaseIndent(); writeLine(); emitLeadingComments(node.body); + emitStart(body); write("return "); emit(body); + emitEnd(body); write(";"); emitTrailingComments(node.body); emitTempDeclarations(/*newLine*/ true); @@ -33082,14 +36268,12 @@ var ts; emitStart(node.body); write("}"); emitEnd(node.body); - scopeEmitEnd(); } function emitBlockFunctionBody(node, body) { write(" {"); - scopeEmitStart(node); var initialTextPos = writer.getTextPos(); increaseIndent(); - emitDetachedComments(body.statements); + emitDetachedCommentsAndUpdateCommentsInfo(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); @@ -33115,25 +36299,28 @@ var ts; 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; - } - } - } + /** + * Return the statement at a given index if it is a super-call statement + * @param ctor a constructor declaration + * @param index an index to constructor's body to check + */ + function getSuperCallAtGivenIndex(ctor, index) { + if (!ctor.body) { + return undefined; + } + var statements = ctor.body.statements; + if (!statements || index >= statements.length) { + return undefined; + } + var statement = statements[index]; + if (statement.kind === 198 /* ExpressionStatement */) { + return ts.isSuperCallExpression(statement.expression) ? statement : undefined; } } function emitParameterPropertyAssignments(node) { ts.forEach(node.parameters, function (param) { - if (param.flags & 112 /* AccessibilityModifier */) { + if (param.flags & 56 /* AccessibilityModifier */) { writeLine(); emitStart(param); emitStart(param.name); @@ -33156,7 +36343,7 @@ var ts; emitNodeWithCommentsAndWithoutSourcemap(memberName); write("]"); } - else if (memberName.kind === 136 /* ComputedPropertyName */) { + else if (memberName.kind === 137 /* ComputedPropertyName */) { emitComputedPropertyName(memberName); } else { @@ -33168,15 +36355,15 @@ var ts; 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) { + if (member.kind === 142 /* PropertyDeclaration */ && isStatic === ((member.flags & 64 /* 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]; + for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) { + var property = properties_6[_a]; emitPropertyDeclaration(node, property); } } @@ -33189,7 +36376,7 @@ var ts; emit(receiver); } else { - if (property.flags & 128 /* Static */) { + if (property.flags & 64 /* Static */) { emitDeclarationName(node); } else { @@ -33208,11 +36395,11 @@ var ts; } function emitMemberFunctionsForES5AndLower(node) { ts.forEach(node.members, function (member) { - if (member.kind === 191 /* SemicolonClassElement */) { + if (member.kind === 194 /* SemicolonClassElement */) { writeLine(); write(";"); } - else if (member.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */) { + else if (member.kind === 144 /* MethodDeclaration */ || node.kind === 143 /* MethodSignature */) { if (!member.body) { return emitCommentsOnNotEmittedNode(member); } @@ -33229,7 +36416,7 @@ var ts; write(";"); emitTrailingComments(member); } - else if (member.kind === 145 /* GetAccessor */ || member.kind === 146 /* SetAccessor */) { + else if (member.kind === 146 /* GetAccessor */ || member.kind === 147 /* SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { writeLine(); @@ -33279,22 +36466,22 @@ var ts; 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) { + if ((member.kind === 144 /* MethodDeclaration */ || node.kind === 143 /* MethodSignature */) && !member.body) { emitCommentsOnNotEmittedNode(member); } - else if (member.kind === 143 /* MethodDeclaration */ || - member.kind === 145 /* GetAccessor */ || - member.kind === 146 /* SetAccessor */) { + else if (member.kind === 144 /* MethodDeclaration */ || + member.kind === 146 /* GetAccessor */ || + member.kind === 147 /* SetAccessor */) { writeLine(); emitLeadingComments(member); emitStart(member); - if (member.flags & 128 /* Static */) { + if (member.flags & 64 /* Static */) { write("static "); } - if (member.kind === 145 /* GetAccessor */) { + if (member.kind === 146 /* GetAccessor */) { write("get "); } - else if (member.kind === 146 /* SetAccessor */) { + else if (member.kind === 147 /* SetAccessor */) { write("set "); } if (member.asteriskToken) { @@ -33305,20 +36492,24 @@ var ts; emitEnd(member); emitTrailingComments(member); } - else if (member.kind === 191 /* SemicolonClassElement */) { + else if (member.kind === 194 /* SemicolonClassElement */) { writeLine(); write(";"); } } } function emitConstructor(node, baseTypeElement) { + var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; var saveTempVariables = tempVariables; var saveTempParameters = tempParameters; + convertedLoopState = undefined; tempFlags = 0; tempVariables = undefined; tempParameters = undefined; emitConstructorWorker(node, baseTypeElement); + ts.Debug.assert(convertedLoopState === undefined); + convertedLoopState = saveConvertedLoopState; tempFlags = saveTempFlags; tempVariables = saveTempVariables; tempParameters = saveTempParameters; @@ -33330,11 +36521,11 @@ var ts; var hasInstancePropertyWithInitializer = false; // Emit the constructor overload pinned comments ts.forEach(node.members, function (member) { - if (member.kind === 144 /* Constructor */ && !member.body) { + if (member.kind === 145 /* 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) { + if (member.kind === 142 /* PropertyDeclaration */ && member.initializer && (member.flags & 64 /* Static */) === 0) { hasInstancePropertyWithInitializer = true; } }); @@ -33375,13 +36566,12 @@ var ts; } 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); + emitDetachedCommentsAndUpdateCommentsInfo(ctor.body.statements); } emitCaptureThisForNodeIfNecessary(node); var superCall; @@ -33389,7 +36579,7 @@ var ts; emitDefaultValueAssignments(ctor); emitRestParameter(ctor); if (baseTypeElement) { - superCall = findInitialSuperCall(ctor); + superCall = getSuperCallAtGivenIndex(ctor, startIndex); if (superCall) { writeLine(); emit(superCall); @@ -33410,7 +36600,7 @@ var ts; emitEnd(baseTypeElement); } } - emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ false)); + emitPropertyDeclarations(node, getInitializedProperties(node, /*isStatic*/ false)); if (ctor) { var statements = ctor.body.statements; if (superCall) { @@ -33425,7 +36615,6 @@ var ts; } decreaseIndent(); emitToken(16 /* CloseBraceToken */, ctor ? ctor.body.statements.end : node.members.end); - scopeEmitEnd(); emitEnd(ctor || node); if (ctor) { emitTrailingComments(ctor); @@ -33449,68 +36638,108 @@ var ts; } } function emitClassLikeDeclarationForES6AndHigher(node) { + var decoratedClassAlias; var thisNodeIsDecorated = ts.nodeIsDecorated(node); - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 217 /* 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: + // When we emit an ES6 class that has a class decorator, we must tailor the + // emit to certain specific cases. // - // * For a local class declaration: + // In the simplest case, we emit the class declaration as a let declaration, and + // evaluate decorators after the close of the class body: // - // @dec class C { - // } + // TypeScript | Javascript + // --------------------------------|------------------------------------ + // @dec | let C = class C { + // class C { | } + // } | C = __decorate([dec], C); + // --------------------------------|------------------------------------ + // @dec | export let C = class C { + // export class C { | } + // } | C = __decorate([dec], C); + // --------------------------------------------------------------------- + // [Example 1] // - // The emit should be: + // If a class declaration contains a reference to itself *inside* of the class body, + // this introduces two bindings to the class: One outside of the class body, and one + // inside of the class body. If we apply decorators as in [Example 1] above, there + // is the possibility that the decorator `dec` will return a new value for the + // constructor, which would result in the binding inside of the class no longer + // pointing to the same reference as the binding outside of the class. // - // let C = class { - // }; - // C = __decorate([dec], C); + // As a result, we must instead rewrite all references to the class *inside* of the + // class body to instead point to a local temporary alias for the class: // - // * For an exported class declaration: + // TypeScript | Javascript + // --------------------------------|------------------------------------ + // @dec | let C_1; + // class C { | let C = C_1 = class C { + // static x() { return C.y; } | static x() { return C_1.y; } + // static y = 1; | } + // } | C.y = 1; + // | C = C_1 = __decorate([dec], C); + // --------------------------------|------------------------------------ + // @dec | let C_1; + // export class C { | export let C = C_1 = class C { + // static x() { return C.y; } | static x() { return C_1.y; } + // static y = 1; | } + // } | C.y = 1; + // | C = C_1 = __decorate([dec], C); + // --------------------------------------------------------------------- + // [Example 2] // - // @dec export class C { - // } + // If a class declaration is the default export of a module, we instead emit + // the export after the decorated declaration: // - // The emit should be: + // TypeScript | Javascript + // --------------------------------|------------------------------------ + // @dec | let default_1 = class { + // export default class { | } + // } | default_1 = __decorate([dec], default_1); + // | export default default_1; + // --------------------------------|------------------------------------ + // @dec | let C = class C { + // export default class { | } + // } | C = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // [Example 3] // - // export let C = class { - // }; - // C = __decorate([dec], C); + // If the class declaration is the default export and a reference to itself + // inside of the class body, we must emit both an alias for the class *and* + // move the export after the declaration: // - // * For a default export of a class declaration with a name: + // TypeScript | Javascript + // --------------------------------|------------------------------------ + // @dec | let C_1; + // export default class C { | let C = C_1 = class C { + // static x() { return C.y; } | static x() { return C_1.y; } + // static y = 1; | } + // } | C.y = 1; + // | C = C_1 = __decorate([dec], C); + // | export default C; + // --------------------------------------------------------------------- + // [Example 4] // - // @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 */)) { + if (resolver.getNodeCheckFlags(node) & 524288 /* ClassWithBodyScopedClassBinding */) { + decoratedClassAlias = ts.unescapeIdentifier(makeUniqueName(node.name ? node.name.text : "default")); + decoratedClassAliases[ts.getNodeId(node)] = decoratedClassAlias; + write("let " + decoratedClassAlias + ";"); + writeLine(); + } + if (isES6ExportedDeclaration(node) && !(node.flags & 512 /* Default */)) { write("export "); } write("let "); emitDeclarationName(node); + if (decoratedClassAlias !== undefined) { + write(" = " + decoratedClassAlias); + } write(" = "); } else if (isES6ExportedDeclaration(node)) { write("export "); - if (node.flags & 1024 /* Default */) { + if (node.flags & 512 /* Default */) { write("default "); } } @@ -33526,8 +36755,8 @@ var ts; // // 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 staticProperties = getInitializedProperties(node, /*isStatic*/ true); + var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 189 /* ClassExpression */; var tempVariable; if (isClassExpressionWithStaticProperties) { tempVariable = createAndRecordTempVariable(0 /* Auto */); @@ -33540,7 +36769,7 @@ var ts; // 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) { + if (node.name || (node.flags & 512 /* Default */ && (staticProperties.length > 0 || modulekind !== 5 /* ES6 */) && !thisNodeIsDecorated)) { write(" "); emitDeclarationName(node); } @@ -33551,23 +36780,14 @@ var ts; } 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) { + decoratedClassAliases[ts.getNodeId(node)] = undefined; write(";"); } // Emit static property assignment. Because classDeclaration is lexically evaluated, @@ -33576,11 +36796,11 @@ var ts; // 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]; + for (var _a = 0, staticProperties_1 = staticProperties; _a < staticProperties_1.length; _a++) { + var property = staticProperties_1[_a]; write(","); writeLine(); - emitPropertyDeclaration(node, property, /*receiver:*/ tempVariable, /*isExpression:*/ true); + emitPropertyDeclaration(node, property, /*receiver*/ tempVariable, /*isExpression*/ true); } write(","); writeLine(); @@ -33591,29 +36811,39 @@ var ts; else { writeLine(); emitPropertyDeclarations(node, staticProperties); - emitDecoratorsOfClass(node); + emitDecoratorsOfClass(node, decoratedClassAlias); } - // 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(";"); + if (!(node.flags & 2 /* Export */)) { + return; } - 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(";"); + if (modulekind !== 5 /* ES6 */) { + emitExportMemberAssignment(node); + } + else { + // If this is an exported class, but not on the top level (i.e. on an internal + // module), export it + if (node.flags & 512 /* Default */) { + // if this is a top level default export of decorated class, write the export after the declaration. + if (thisNodeIsDecorated) { + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } + } + else if (node.parent.kind !== 251 /* SourceFile */) { + writeLine(); + emitStart(node); + emitModuleMemberName(node); + write(" = "); + emitDeclarationName(node); + emitEnd(node); + write(";"); + } } } function emitClassLikeDeclarationBelowES6(node) { - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 217 /* ClassDeclaration */) { // source file level classes in system modules are hoisted so 'var's for them are already defined if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); @@ -33631,12 +36861,13 @@ var ts; var saveTempVariables = tempVariables; var saveTempParameters = tempParameters; var saveComputedPropertyNamesToGeneratedNames = computedPropertyNamesToGeneratedNames; + var saveConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; tempFlags = 0; tempVariables = undefined; tempParameters = undefined; computedPropertyNamesToGeneratedNames = undefined; increaseIndent(); - scopeEmitStart(node); if (baseTypeNode) { writeLine(); emitStart(baseTypeNode); @@ -33648,9 +36879,9 @@ var ts; writeLine(); emitConstructor(node, baseTypeNode); emitMemberFunctionsForES5AndLower(node); - emitPropertyDeclarations(node, getInitializedProperties(node, /*static:*/ true)); + emitPropertyDeclarations(node, getInitializedProperties(node, /*isStatic*/ true)); writeLine(); - emitDecoratorsOfClass(node); + emitDecoratorsOfClass(node, /*decoratedClassAlias*/ undefined); writeLine(); emitToken(16 /* CloseBraceToken */, node.members.end, function () { write("return "); @@ -33658,6 +36889,8 @@ var ts; }); write(";"); emitTempDeclarations(/*newLine*/ true); + ts.Debug.assert(convertedLoopState === undefined); + convertedLoopState = saveConvertedLoopState; tempFlags = saveTempFlags; tempVariables = saveTempVariables; tempParameters = saveTempParameters; @@ -33665,38 +36898,37 @@ var ts; decreaseIndent(); writeLine(); emitToken(16 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); emitStart(node); - write(")("); + write("("); if (baseTypeNode) { emit(baseTypeNode.expression); } - write(")"); - if (node.kind === 214 /* ClassDeclaration */) { + write("))"); + if (node.kind === 217 /* ClassDeclaration */) { write(";"); } emitEnd(node); - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 217 /* ClassDeclaration */) { emitExportMemberAssignment(node); } } function emitClassMemberPrefix(node, member) { emitDeclarationName(node); - if (!(member.flags & 128 /* Static */)) { + if (!(member.flags & 64 /* Static */)) { write(".prototype"); } } - function emitDecoratorsOfClass(node) { + function emitDecoratorsOfClass(node, decoratedClassAlias) { emitDecoratorsOfMembers(node, /*staticFlag*/ 0); - emitDecoratorsOfMembers(node, 128 /* Static */); - emitDecoratorsOfConstructor(node); + emitDecoratorsOfMembers(node, 64 /* Static */); + emitDecoratorsOfConstructor(node, decoratedClassAlias); } - function emitDecoratorsOfConstructor(node) { + function emitDecoratorsOfConstructor(node, decoratedClassAlias) { var decorators = node.decorators; var constructor = ts.getFirstConstructorWithBody(node); - var hasDecoratedParameters = constructor && ts.forEach(constructor.parameters, ts.nodeIsDecorated); + var firstParameterDecorator = constructor && ts.forEach(constructor.parameters, function (parameter) { return parameter.decorators; }); // skip decoration of the constructor if neither it nor its parameters are decorated - if (!decorators && !hasDecoratedParameters) { + if (!decorators && !firstParameterDecorator) { return; } // Emit the call to __decorate. Given the class: @@ -33710,42 +36942,40 @@ var ts; // C = __decorate([dec], C); // writeLine(); - emitStart(node); + emitStart(node.decorators || firstParameterDecorator); emitDeclarationName(node); + if (decoratedClassAlias !== undefined) { + write(" = " + decoratedClassAlias); + } 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); + var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { return emit(decorator.expression); }); + if (firstParameterDecorator) { + argumentsWritten += emitDecoratorsOfParameters(constructor, /*leadingComma*/ argumentsWritten > 0); + } emitSerializedTypeMetadata(node, /*leadingComma*/ argumentsWritten >= 0); decreaseIndent(); writeLine(); write("], "); emitDeclarationName(node); - write(");"); - emitEnd(node); + write(")"); + emitEnd(node.decorators || firstParameterDecorator); + write(";"); 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) { + if ((member.flags & 64 /* 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; @@ -33765,10 +36995,15 @@ var ts; else { decorators = member.decorators; // we only decorate the parameters here if this is a method - if (member.kind === 143 /* MethodDeclaration */) { + if (member.kind === 144 /* MethodDeclaration */) { functionLikeMember = member; } } + var firstParameterDecorator = functionLikeMember && ts.forEach(functionLikeMember.parameters, function (parameter) { return parameter.decorators; }); + // skip a member if it or any of its parameters are not decorated + if (!decorators && !firstParameterDecorator) { + continue; + } // Emit the call to __decorate. Given the following: // // class C { @@ -33800,28 +37035,24 @@ var ts; // ], C.prototype, "prop"); // writeLine(); - emitStart(member); + emitStart(decorators || firstParameterDecorator); 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); + var argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, function (decorator) { return emit(decorator.expression); }); + if (firstParameterDecorator) { + 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 */) { + if (member.kind !== 142 /* 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"); @@ -33832,29 +37063,28 @@ var ts; write(", void 0"); } } - write(");"); - emitEnd(member); + write(")"); + emitEnd(decorators || firstParameterDecorator); + write(";"); writeLine(); } } function emitDecoratorsOfParameters(node, leadingComma) { var argumentsWritten = 0; if (node) { - var parameterIndex = 0; + var parameterIndex_1 = 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 + ", "); + write("__param(" + parameterIndex_1 + ", "); emit(decorator.expression); write(")"); - emitEnd(decorator); }); leadingComma = true; } - ++parameterIndex; + parameterIndex_1++; } } return argumentsWritten; @@ -33864,10 +37094,10 @@ var ts; // 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 */: + case 144 /* MethodDeclaration */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 142 /* PropertyDeclaration */: return true; } return false; @@ -33877,7 +37107,7 @@ var ts; // 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 144 /* MethodDeclaration */: return true; } return false; @@ -33887,9 +37117,9 @@ var ts; // 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 */: + case 217 /* ClassDeclaration */: + case 144 /* MethodDeclaration */: + case 147 /* SetAccessor */: return true; } return false; @@ -33907,19 +37137,19 @@ var ts; // // For rules on serializing type annotations, see `serializeTypeNode`. switch (node.kind) { - case 214 /* ClassDeclaration */: + case 217 /* ClassDeclaration */: write("Function"); return; - case 141 /* PropertyDeclaration */: + case 142 /* PropertyDeclaration */: emitSerializedTypeNode(node.type); return; - case 138 /* Parameter */: + case 139 /* Parameter */: emitSerializedTypeNode(node.type); return; - case 145 /* GetAccessor */: + case 146 /* GetAccessor */: emitSerializedTypeNode(node.type); return; - case 146 /* SetAccessor */: + case 147 /* SetAccessor */: emitSerializedTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); return; } @@ -33935,23 +37165,23 @@ var ts; case 103 /* VoidKeyword */: write("void 0"); return; - case 160 /* ParenthesizedType */: + case 161 /* ParenthesizedType */: emitSerializedTypeNode(node.type); return; - case 152 /* FunctionType */: - case 153 /* ConstructorType */: + case 153 /* FunctionType */: + case 154 /* ConstructorType */: write("Function"); return; - case 156 /* ArrayType */: - case 157 /* TupleType */: + case 157 /* ArrayType */: + case 158 /* TupleType */: write("Array"); return; - case 150 /* TypePredicate */: + case 151 /* TypePredicate */: case 120 /* BooleanKeyword */: write("Boolean"); return; case 130 /* StringKeyword */: - case 9 /* StringLiteral */: + case 163 /* StringLiteralType */: write("String"); return; case 128 /* NumberKeyword */: @@ -33960,14 +37190,15 @@ var ts; case 131 /* SymbolKeyword */: write("Symbol"); return; - case 151 /* TypeReference */: + case 152 /* TypeReference */: emitSerializedTypeReferenceNode(node); return; - case 154 /* TypeQuery */: - case 155 /* TypeLiteral */: - case 158 /* UnionType */: - case 159 /* IntersectionType */: + case 155 /* TypeQuery */: + case 156 /* TypeLiteral */: + case 159 /* UnionType */: + case 160 /* IntersectionType */: case 117 /* AnyKeyword */: + case 162 /* ThisType */: break; default: ts.Debug.fail("Cannot serialize unexpected type node."); @@ -33983,8 +37214,7 @@ var ts; 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 typeName = ts.cloneEntityName(node.typeName, location); var result = resolver.getTypeReferenceSerializationKind(typeName); switch (result) { case ts.TypeReferenceSerializationKind.Unknown: @@ -34040,8 +37270,8 @@ var ts; // // For the rules on serializing the type of each parameter declaration, see `serializeTypeOfDeclaration`. if (node) { - var valueDeclaration; - if (node.kind === 214 /* ClassDeclaration */) { + var valueDeclaration = void 0; + if (node.kind === 217 /* ClassDeclaration */) { valueDeclaration = ts.getFirstConstructorWithBody(node); } else if (ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)) { @@ -34057,10 +37287,10 @@ var ts; } if (parameters[i].dotDotDotToken) { var parameterType = parameters[i].type; - if (parameterType.kind === 156 /* ArrayType */) { + if (parameterType.kind === 157 /* ArrayType */) { parameterType = parameterType.elementType; } - else if (parameterType.kind === 151 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + else if (parameterType.kind === 152 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { parameterType = parameterType.typeArguments[0]; } else { @@ -34136,9 +37366,10 @@ var ts; } if (!shouldHoistDeclarationInSystemJsModule(node)) { // do not emit var if variable was already hoisted - if (!(node.flags & 1 /* Export */) || isES6ExportedDeclaration(node)) { + var isES6ExportedEnum = isES6ExportedDeclaration(node); + if (!(node.flags & 2 /* Export */) || (isES6ExportedEnum && isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 220 /* EnumDeclaration */))) { emitStart(node); - if (isES6ExportedDeclaration(node)) { + if (isES6ExportedEnum) { write("export "); } write("var "); @@ -34155,19 +37386,17 @@ var ts; 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)) { + if (!isES6ExportedDeclaration(node) && node.flags & 2 /* Export */ && !shouldHoistDeclarationInSystemJsModule(node)) { // do not emit var if variable was already hoisted writeLine(); emitStart(node); @@ -34179,7 +37408,7 @@ var ts; write(";"); } if (modulekind !== 5 /* ES6 */ && node.parent === currentSourceFile) { - if (modulekind === 4 /* System */ && (node.flags & 1 /* Export */)) { + if (modulekind === 4 /* System */ && (node.flags & 2 /* Export */)) { // write the call to exporter for enum writeLine(); write(exportFunctionForFile + "(\""); @@ -34220,7 +37449,7 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 218 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 221 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -34231,6 +37460,9 @@ var ts; function isModuleMergedWithES6Class(node) { return languageVersion === 2 /* ES6 */ && !!(resolver.getNodeCheckFlags(node) & 32768 /* LexicalModuleMergesWithClass */); } + function isFirstDeclarationOfKind(node, declarations, kind) { + return !ts.forEach(declarations, function (declaration) { return declaration.kind === kind && declaration.pos < node.pos; }); + } function emitModuleDeclaration(node) { // Emit only if this module is non-ambient. var shouldEmit = shouldEmitModuleDeclaration(node); @@ -34240,15 +37472,18 @@ var ts; var hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node); var emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); if (emitVarForModule) { - emitStart(node); - if (isES6ExportedDeclaration(node)) { - write("export "); + var isES6ExportedNamespace = isES6ExportedDeclaration(node); + if (!isES6ExportedNamespace || isFirstDeclarationOfKind(node, node.symbol && node.symbol.declarations, 221 /* ModuleDeclaration */)) { + emitStart(node); + if (isES6ExportedNamespace) { + write("export "); + } + write("var "); + emit(node.name); + write(";"); + emitEnd(node); + writeLine(); } - write("var "); - emit(node.name); - write(";"); - emitEnd(node); - writeLine(); } emitStart(node); write("(function ("); @@ -34256,19 +37491,22 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); - if (node.body.kind === 219 /* ModuleBlock */) { + if (node.body.kind === 222 /* ModuleBlock */) { + var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; var saveTempVariables = tempVariables; + convertedLoopState = undefined; tempFlags = 0; tempVariables = undefined; emit(node.body); + ts.Debug.assert(convertedLoopState === undefined); + convertedLoopState = saveConvertedLoopState; tempFlags = saveTempFlags; tempVariables = saveTempVariables; } else { write("{"); increaseIndent(); - scopeEmitStart(node); emitCaptureThisForNodeIfNecessary(node); writeLine(); emit(node.body); @@ -34276,11 +37514,10 @@ var ts; 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)) { + if ((node.flags & 2 /* Export */) && !isES6ExportedDeclaration(node)) { emit(node.name); write(" = "); } @@ -34290,7 +37527,7 @@ var ts; write(" = {}));"); emitEnd(node); if (!isES6ExportedDeclaration(node) && node.name.kind === 69 /* Identifier */ && node.parent === currentSourceFile) { - if (modulekind === 4 /* System */ && (node.flags & 1 /* Export */)) { + if (modulekind === 4 /* System */ && (node.flags & 2 /* Export */)) { writeLine(); write(exportFunctionForFile + "(\""); emitDeclarationName(node); @@ -34306,8 +37543,8 @@ var ts; * 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] + "\""; + if (renamedDependencies && ts.hasProperty(renamedDependencies, moduleName.text)) { + return "\"" + renamedDependencies[moduleName.text] + "\""; } return undefined; } @@ -34330,16 +37567,16 @@ var ts; } } function getNamespaceDeclarationNode(node) { - if (node.kind === 221 /* ImportEqualsDeclaration */) { + if (node.kind === 224 /* ImportEqualsDeclaration */) { return node; } var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 227 /* NamespaceImport */) { return importClause.namedBindings; } } function isDefaultImport(node) { - return node.kind === 222 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; + return node.kind === 225 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; } function emitExportImportAssignments(node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { @@ -34367,7 +37604,7 @@ var ts; if (shouldEmitNamedBindings) { emitLeadingComments(node.importClause.namedBindings); emitStart(node.importClause.namedBindings); - if (node.importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (node.importClause.namedBindings.kind === 227 /* NamespaceImport */) { write("* as "); emit(node.importClause.namedBindings.name); } @@ -34393,16 +37630,19 @@ var ts; } function emitExternalImportDeclaration(node) { if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 221 /* ImportEqualsDeclaration */ && (node.flags & 1 /* Export */) !== 0; + var isExportedImport = node.kind === 224 /* ImportEqualsDeclaration */ && (node.flags & 2 /* Export */) !== 0; var namespaceDeclaration = getNamespaceDeclarationNode(node); + var varOrConst = (languageVersion <= 1 /* ES5 */) ? "var " : "const "; 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 "); + if (!isExportedImport) { + write(varOrConst); + } + ; emitModuleMemberName(namespaceDeclaration); write(" = "); } @@ -34412,9 +37652,9 @@ var ts; // import { x, y } from "foo" // import d, * as x from "foo" // import d, { x, y } from "foo" - var isNakedImport = 222 /* ImportDeclaration */ && !node.importClause; + var isNakedImport = 225 /* ImportDeclaration */ && !node.importClause; if (!isNakedImport) { - write("var "); + write(varOrConst); write(getGeneratedNameForNode(node)); write(" = "); } @@ -34441,7 +37681,7 @@ var ts; } else if (namespaceDeclaration && isDefaultImport(node)) { // import d, * as x from "foo" - write("var "); + write(varOrConst); emitModuleMemberName(namespaceDeclaration); write(" = "); write(getGeneratedNameForNode(node)); @@ -34460,7 +37700,7 @@ var ts; // - 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))) { + (!isCurrentFileExternalModule && resolver.isTopLevelValueImportEqualsWithEntityName(node))) { emitLeadingComments(node); emitStart(node); // variable declaration for import-equals declaration can be hoisted in system modules @@ -34475,7 +37715,7 @@ var ts; write("export "); write("var "); } - else if (!(node.flags & 1 /* Export */)) { + else if (!(node.flags & 2 /* Export */)) { write("var "); } } @@ -34530,15 +37770,17 @@ var ts; } else { // export * from "foo" - writeLine(); - write("__export("); - if (modulekind !== 2 /* AMD */) { - emitRequire(ts.getExternalModuleName(node)); - } - else { - write(generatedName); + if (hasExportStarsToExportValues && resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + writeLine(); + write("__export("); + if (modulekind !== 2 /* AMD */) { + emitRequire(ts.getExternalModuleName(node)); + } + else { + write(generatedName); + } + write(");"); } - write(");"); } emitEnd(node); } @@ -34566,8 +37808,8 @@ var ts; 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]; + for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) { + var specifier = specifiers_1[_a]; if (shouldEmit(specifier)) { if (needsComma) { write(", "); @@ -34589,8 +37831,8 @@ var ts; write("export default "); var expression = node.expression; emit(expression); - if (expression.kind !== 213 /* FunctionDeclaration */ && - expression.kind !== 214 /* ClassDeclaration */) { + if (expression.kind !== 216 /* FunctionDeclaration */ && + expression.kind !== 217 /* ClassDeclaration */) { write(";"); } emitEnd(node); @@ -34623,11 +37865,11 @@ var ts; externalImports = []; exportSpecifiers = {}; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { var node = _b[_a]; switch (node.kind) { - case 222 /* ImportDeclaration */: + case 225 /* ImportDeclaration */: if (!node.importClause || resolver.isReferencedAliasDeclaration(node.importClause, /*checkChildren*/ true)) { // import "mod" @@ -34637,18 +37879,20 @@ var ts; externalImports.push(node); } break; - case 221 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 232 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { + case 224 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 235 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { // import x = require("mod") where x is referenced externalImports.push(node); } break; - case 228 /* ExportDeclaration */: + case 231 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" - externalImports.push(node); - hasExportStars = true; + if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } } else if (resolver.isValueAliasDeclaration(node)) { // export { x, y } from "mod" where at least one export is a value symbol @@ -34659,12 +37903,12 @@ var ts; // 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); + var name_28 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_28] || (exportSpecifiers[name_28] = [])).push(specifier); } } break; - case 227 /* ExportAssignment */: + case 230 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; @@ -34674,7 +37918,7 @@ var ts; } } function emitExportStarHelper() { - if (hasExportStars) { + if (hasExportStarsToExportValues) { writeLine(); write("function __export(m) {"); increaseIndent(); @@ -34688,16 +37932,22 @@ var ts; function getLocalNameForExternalImport(node) { var namespaceDeclaration = getNamespaceDeclarationNode(node); if (namespaceDeclaration && !isDefaultImport(node)) { - return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name); + return ts.getTextOfNodeFromSourceText(currentText, namespaceDeclaration.name); } - if (node.kind === 222 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 225 /* ImportDeclaration */ && node.importClause) { return getGeneratedNameForNode(node); } - if (node.kind === 228 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 231 /* ExportDeclaration */ && node.moduleSpecifier) { return getGeneratedNameForNode(node); } } - function getExternalModuleNameText(importNode) { + function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { + if (emitRelativePathAsModuleName) { + var name_29 = getExternalModuleNameFromDeclaration(host, resolver, importNode); + if (name_29) { + return "\"" + name_29 + "\""; + } + } var moduleName = ts.getExternalModuleName(importNode); if (moduleName.kind === 9 /* StringLiteral */) { return tryRenameExternalModule(moduleName) || getLiteralText(moduleName); @@ -34710,11 +37960,11 @@ var ts; } writeLine(); var started = false; - for (var _a = 0; _a < externalImports.length; _a++) { - var importNode = externalImports[_a]; + for (var _a = 0, externalImports_1 = externalImports; _a < externalImports_1.length; _a++) { + var importNode = externalImports_1[_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); + var skipNode = importNode.kind === 231 /* ExportDeclaration */ || + (importNode.kind === 225 /* ImportDeclaration */ && !importNode.importClause); if (skipNode) { continue; } @@ -34736,7 +37986,7 @@ var ts; // 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) { + if (!hasExportStarsToExportValues) { // local names set is needed only in presence of star exports return undefined; } @@ -34745,9 +37995,9 @@ var ts; // 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) { + for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { + var externalImport = externalImports_2[_a]; + if (externalImport.kind === 231 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -34763,7 +38013,7 @@ var ts; increaseIndent(); var started = false; if (exportedDeclarations) { - for (var i = 0; i < exportedDeclarations.length; ++i) { + for (var i = 0; i < exportedDeclarations.length; i++) { // write name of exported declaration, i.e 'export var x...' writeExportedName(exportedDeclarations[i]); } @@ -34777,9 +38027,9 @@ var ts; } } } - for (var _d = 0; _d < externalImports.length; _d++) { - var externalImport = externalImports[_d]; - if (externalImport.kind !== 228 /* ExportDeclaration */) { + for (var _d = 0, externalImports_3 = externalImports; _d < externalImports_3.length; _d++) { + var externalImport = externalImports_3[_d]; + if (externalImport.kind !== 231 /* ExportDeclaration */) { continue; } var exportDecl = externalImport; @@ -34827,7 +38077,7 @@ var ts; 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 */) { + if (node.kind !== 69 /* Identifier */ && node.flags & 512 /* Default */) { return; } if (started) { @@ -34865,14 +38115,14 @@ var ts; writeLine(); write("var "); var seen = {}; - for (var i = 0; i < hoistedVars.length; ++i) { + for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; - var name_26 = local.kind === 69 /* Identifier */ + var name_30 = local.kind === 69 /* Identifier */ ? local : local.name; - if (name_26) { + if (name_30) { // do not emit duplicate entries (in case of declaration merging) in the list of hoisted variables - var text = ts.unescapeIdentifier(name_26.text); + var text = ts.unescapeIdentifier(name_30.text); if (ts.hasProperty(seen, text)) { continue; } @@ -34883,14 +38133,14 @@ var ts; if (i !== 0) { write(", "); } - if (local.kind === 214 /* ClassDeclaration */ || local.kind === 218 /* ModuleDeclaration */ || local.kind === 217 /* EnumDeclaration */) { + if (local.kind === 217 /* ClassDeclaration */ || local.kind === 221 /* ModuleDeclaration */ || local.kind === 220 /* EnumDeclaration */) { emitDeclarationName(local); } else { emit(local); } var flags = ts.getCombinedNodeFlags(local.kind === 69 /* Identifier */ ? local.parent : local); - if (flags & 1 /* Export */) { + if (flags & 2 /* Export */) { if (!exportedDeclarations) { exportedDeclarations = []; } @@ -34900,11 +38150,11 @@ var ts; write(";"); } if (hoistedFunctionDeclarations) { - for (var _a = 0; _a < hoistedFunctionDeclarations.length; _a++) { - var f = hoistedFunctionDeclarations[_a]; + for (var _a = 0, hoistedFunctionDeclarations_1 = hoistedFunctionDeclarations; _a < hoistedFunctionDeclarations_1.length; _a++) { + var f = hoistedFunctionDeclarations_1[_a]; writeLine(); emit(f); - if (f.flags & 1 /* Export */) { + if (f.flags & 2 /* Export */) { if (!exportedDeclarations) { exportedDeclarations = []; } @@ -34914,24 +38164,24 @@ var ts; } return exportedDeclarations; function visit(node) { - if (node.flags & 2 /* Ambient */) { + if (node.flags & 4 /* Ambient */) { return; } - if (node.kind === 213 /* FunctionDeclaration */) { + if (node.kind === 216 /* FunctionDeclaration */) { if (!hoistedFunctionDeclarations) { hoistedFunctionDeclarations = []; } hoistedFunctionDeclarations.push(node); return; } - if (node.kind === 214 /* ClassDeclaration */) { + if (node.kind === 217 /* ClassDeclaration */) { if (!hoistedVars) { hoistedVars = []; } hoistedVars.push(node); return; } - if (node.kind === 217 /* EnumDeclaration */) { + if (node.kind === 220 /* EnumDeclaration */) { if (shouldEmitEnumDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -34940,7 +38190,7 @@ var ts; } return; } - if (node.kind === 218 /* ModuleDeclaration */) { + if (node.kind === 221 /* ModuleDeclaration */) { if (shouldEmitModuleDeclaration(node)) { if (!hoistedVars) { hoistedVars = []; @@ -34949,17 +38199,17 @@ var ts; } return; } - if (node.kind === 211 /* VariableDeclaration */ || node.kind === 163 /* BindingElement */) { + if (node.kind === 214 /* VariableDeclaration */ || node.kind === 166 /* BindingElement */) { if (shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ false)) { - var name_27 = node.name; - if (name_27.kind === 69 /* Identifier */) { + var name_31 = node.name; + if (name_31.kind === 69 /* Identifier */) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_27); + hoistedVars.push(name_31); } else { - ts.forEachChild(name_27, visit); + ts.forEachChild(name_31, visit); } } return; @@ -34989,11 +38239,11 @@ var ts; // - 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 */; + return (ts.getCombinedNodeFlags(node) & 24576 /* BlockScoped */) === 0 || + ts.getEnclosingBlockScopeContainer(node).kind === 251 /* SourceFile */; } function isCurrentFileSystemExternalModule() { - return modulekind === 4 /* System */ && ts.isExternalModule(currentSourceFile); + return modulekind === 4 /* System */ && isCurrentFileExternalModule; } function emitSystemModuleBody(node, dependencyGroups, startIndex) { // shape of the body in system modules: @@ -35050,7 +38300,7 @@ var ts; } function emitSetters(exportStarFunction, dependencyGroups) { write("setters:["); - for (var i = 0; i < dependencyGroups.length; ++i) { + for (var i = 0; i < dependencyGroups.length; i++) { if (i !== 0) { write(","); } @@ -35061,25 +38311,25 @@ var ts; var parameterName = makeUniqueName(ts.forEach(group, getLocalNameForExternalImport) || ""); write("function (" + parameterName + ") {"); increaseIndent(); - for (var _a = 0; _a < group.length; _a++) { - var entry = group[_a]; + for (var _a = 0, group_1 = group; _a < group_1.length; _a++) { + var entry = group_1[_a]; var importVariableName = getLocalNameForExternalImport(entry) || ""; switch (entry.kind) { - case 222 /* ImportDeclaration */: + case 225 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // fall-through - case 221 /* ImportEqualsDeclaration */: + case 224 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== ""); writeLine(); // save import into the local write(importVariableName + " = " + parameterName + ";"); writeLine(); break; - case 228 /* ExportDeclaration */: + case 231 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== ""); if (entry.exportClause) { // export {a, b as c} from 'foo' @@ -35092,12 +38342,12 @@ var ts; write(exportFunctionForFile + "({"); writeLine(); increaseIndent(); - for (var i_2 = 0, len = entry.exportClause.elements.length; i_2 < len; ++i_2) { - if (i_2 !== 0) { + for (var i_1 = 0, len = entry.exportClause.elements.length; i_1 < len; i_1++) { + if (i_1 !== 0) { write(","); writeLine(); } - var e = entry.exportClause.elements[i_2]; + var e = entry.exportClause.elements[i_1]; write("\""); emitNodeWithCommentsAndWithoutSourcemap(e.name); write("\": " + parameterName + "[\""); @@ -35109,6 +38359,8 @@ var ts; write("});"); } else { + // collectExternalModuleInfo prefilters star exports to keep only ones that export values + // this means that check 'resolver.moduleExportsSomeValue' is redundant and can be omitted here writeLine(); // export * from 'foo' // emit as: @@ -35129,17 +38381,17 @@ var ts; write("execute: function() {"); increaseIndent(); writeLine(); - for (var i = startIndex; i < node.statements.length; ++i) { + 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 */: + case 216 /* FunctionDeclaration */: + case 225 /* ImportDeclaration */: continue; - case 228 /* ExportDeclaration */: + case 231 /* ExportDeclaration */: if (!statement.moduleSpecifier) { for (var _a = 0, _b = statement.exportClause.elements; _a < _b.length; _a++) { var element = _b[_a]; @@ -35148,7 +38400,7 @@ var ts; } } continue; - case 221 /* ImportEqualsDeclaration */: + case 224 /* ImportEqualsDeclaration */: if (!ts.isInternalModuleImportEqualsDeclaration(statement)) { // - import equals declarations that import external modules are not emitted continue; @@ -35163,7 +38415,13 @@ var ts; writeLine(); write("}"); // execute } - function emitSystemModule(node) { + function writeModuleName(node, emitRelativePathAsModuleName) { + var moduleName = node.moduleName; + if (moduleName || (emitRelativePathAsModuleName && (moduleName = getResolvedExternalModuleName(host, node)))) { + write("\"" + moduleName + "\", "); + } + } + function emitSystemModule(node, emitRelativePathAsModuleName) { collectExternalModuleInfo(node); // System modules has the following shape // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) @@ -35176,24 +38434,29 @@ var ts; ts.Debug.assert(!exportFunctionForFile); // make sure that name of 'exports' function does not conflict with existing identifiers exportFunctionForFile = makeUniqueName("exports"); + contextObjectForFile = makeUniqueName("context"); writeLine(); write("System.register("); - if (node.moduleName) { - write("\"" + node.moduleName + "\", "); - } + writeModuleName(node, emitRelativePathAsModuleName); write("["); var groupIndices = {}; var dependencyGroups = []; - for (var i = 0; i < externalImports.length; ++i) { - var text = getExternalModuleNameText(externalImports[i]); - if (ts.hasProperty(groupIndices, text)) { + for (var i = 0; i < externalImports.length; i++) { + var text = getExternalModuleNameText(externalImports[i], emitRelativePathAsModuleName); + if (text === undefined) { + continue; + } + // text should be quoted string + // for deduplication purposes in key remove leading and trailing quotes so 'a' and "a" will be considered the same + var key = text.substr(1, text.length - 2); + if (ts.hasProperty(groupIndices, key)) { // deduplicate/group entries in dependency list by the dependency name - var groupIndex = groupIndices[text]; + var groupIndex = groupIndices[key]; dependencyGroups[groupIndex].push(externalImports[i]); continue; } else { - groupIndices[text] = dependencyGroups.length; + groupIndices[key] = dependencyGroups.length; dependencyGroups.push([externalImports[i]]); } if (i !== 0) { @@ -35201,10 +38464,13 @@ var ts; } write(text); } - write("], function(" + exportFunctionForFile + ") {"); + write("], function(" + exportFunctionForFile + ", " + contextObjectForFile + ") {"); writeLine(); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); + writeLine(); + write("var __moduleName = " + contextObjectForFile + " && " + contextObjectForFile + ".id;"); + writeLine(); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitSystemModuleBody(node, dependencyGroups, startIndex); @@ -35212,7 +38478,7 @@ var ts; writeLine(); write("});"); } - function getAMDDependencyNames(node, includeNonAmdDependencies) { + function getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { // names of modules with corresponding parameter in the factory function var aliasedModuleNames = []; // names of modules with no corresponding parameters in factory function @@ -35231,10 +38497,10 @@ var ts; unaliasedModuleNames.push("\"" + amdDependency.path + "\""); } } - for (var _c = 0; _c < externalImports.length; _c++) { - var importNode = externalImports[_c]; + for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) { + var importNode = externalImports_4[_c]; // Find the name of the external module - var externalModuleName = getExternalModuleNameText(importNode); + var externalModuleName = getExternalModuleNameText(importNode, emitRelativePathAsModuleName); // Find the name of the module alias, if there is one var importAliasName = getLocalNameForExternalImport(importNode); if (includeNonAmdDependencies && importAliasName) { @@ -35247,7 +38513,7 @@ var ts; } return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; } - function emitAMDDependencies(node, includeNonAmdDependencies) { + function emitAMDDependencies(node, includeNonAmdDependencies, emitRelativePathAsModuleName) { // An AMD define function has the following shape: // define(id?, dependencies?, factory); // @@ -35259,7 +38525,7 @@ var ts; // 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); + var dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName); emitAMDDependencyList(dependencyNames); write(", "); emitAMDFactoryHeader(dependencyNames); @@ -35286,17 +38552,15 @@ var ts; } write(") {"); } - function emitAMDModule(node) { + function emitAMDModule(node, emitRelativePathAsModuleName) { emitEmitHelpers(node); collectExternalModuleInfo(node); writeLine(); write("define("); - if (node.moduleName) { - write("\"" + node.moduleName + "\", "); - } - emitAMDDependencies(node, /*includeNonAmdDependencies*/ true); + writeModuleName(node, emitRelativePathAsModuleName); + emitAMDDependencies(node, /*includeNonAmdDependencies*/ true, emitRelativePathAsModuleName); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -35307,7 +38571,7 @@ var ts; write("});"); } function emitCommonJSModule(node) { - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); emitEmitHelpers(node); collectExternalModuleInfo(node); emitExportStarHelper(); @@ -35327,7 +38591,7 @@ var ts; writeLines(" }\n})("); emitAMDFactoryHeader(dependencyNames); increaseIndent(); - var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -35341,7 +38605,7 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; var startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); @@ -35404,7 +38668,9 @@ var ts; // Replace entities like   result = result.replace(/&(\w+);/g, function (s, m) { if (entities[m] !== undefined) { - return String.fromCharCode(entities[m]); + var ch = String.fromCharCode(entities[m]); + // " needs to be escaped + return ch === "\"" ? "\\\"" : ch; } else { return s; @@ -35456,24 +38722,41 @@ var ts; } } } - function emitDirectivePrologues(statements, startWithNewLine) { - for (var i = 0; i < statements.length; ++i) { + function isUseStrictPrologue(node) { + return !!node.expression.text.match(/use strict/); + } + function ensureUseStrictPrologue(startWithNewLine, writeUseStrict) { + if (writeUseStrict) { + if (startWithNewLine) { + writeLine(); + } + write("\"use strict\";"); + } + } + function emitDirectivePrologues(statements, startWithNewLine, ensureUseStrict) { + var foundUseStrict = false; + for (var i = 0; i < statements.length; i++) { if (ts.isPrologueDirective(statements[i])) { + if (isUseStrictPrologue(statements[i])) { + foundUseStrict = true; + } if (startWithNewLine || i > 0) { writeLine(); } emit(statements[i]); } else { + ensureUseStrictPrologue(startWithNewLine || i > 0, !foundUseStrict && ensureUseStrict); // return index of the first non prologue directive return i; } } + ensureUseStrictPrologue(startWithNewLine, !foundUseStrict && ensureUseStrict); return statements.length; } function writeLines(text) { var lines = text.split(/\r\n|\r|\n/g); - for (var i = 0; i < lines.length; ++i) { + for (var i = 0; i < lines.length; i++) { var line = lines[i]; if (line.length) { writeLine(); @@ -35486,22 +38769,22 @@ var ts; 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 */)) { + if ((languageVersion < 2 /* ES6 */) && (!extendsEmitted && node.flags & 4194304 /* HasClassExtends */)) { writeLines(extendsHelper); extendsEmitted = true; } - if (!decorateEmitted && resolver.getNodeCheckFlags(node) & 16 /* EmitDecorate */) { + if (!decorateEmitted && node.flags & 8388608 /* HasDecorators */) { writeLines(decorateHelper); if (compilerOptions.emitDecoratorMetadata) { writeLines(metadataHelper); } decorateEmitted = true; } - if (!paramEmitted && resolver.getNodeCheckFlags(node) & 32 /* EmitParam */) { + if (!paramEmitted && node.flags & 16777216 /* HasParamDecorators */) { writeLines(paramHelper); paramEmitted = true; } - if (!awaiterEmitted && resolver.getNodeCheckFlags(node) & 64 /* EmitAwaiter */) { + if (!awaiterEmitted && node.flags & 33554432 /* HasAsyncFunctions */) { writeLines(awaiterHelper); awaiterEmitted = true; } @@ -35511,10 +38794,15 @@ var ts; // Start new file on new line writeLine(); emitShebang(); - emitDetachedComments(node); + emitDetachedCommentsAndUpdateCommentsInfo(node); if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { - var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1 /* CommonJS */]; - emitModule(node); + if (isOwnFileEmit || (!ts.isExternalModule(node) && compilerOptions.isolatedModules)) { + var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1 /* CommonJS */]; + emitModule(node); + } + else { + bundleEmitDelegates[modulekind](node, /*emitRelativePathAsModuleName*/ true); + } } else { // emit prologue directives prior to __extends @@ -35522,7 +38810,7 @@ var ts; externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; - hasExportStars = false; + hasExportStarsToExportValues = false; emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -35530,12 +38818,15 @@ var ts; } emitLeadingComments(node.endOfFileToken); } + function emit(node) { + emitNodeConsideringCommentsOption(node, emitNodeWithSourceMap); + } function emitNodeWithCommentsAndWithoutSourcemap(node) { emitNodeConsideringCommentsOption(node, emitNodeWithoutSourceMap); } function emitNodeConsideringCommentsOption(node, emitNodeConsideringSourcemap) { if (node) { - if (node.flags & 2 /* Ambient */) { + if (node.flags & 4 /* Ambient */) { return emitCommentsOnNotEmittedNode(node); } if (isSpecializedCommentHandling(node)) { @@ -35552,33 +38843,53 @@ var ts; } } } + function emitNodeWithSourceMap(node) { + if (node) { + emitStart(node); + emitNodeWithoutSourceMap(node); + emitEnd(node); + } + } function emitNodeWithoutSourceMap(node) { if (node) { emitJavaScriptWorker(node); } } + function changeSourceMapEmit(writer) { + sourceMap = writer; + emitStart = writer.emitStart; + emitEnd = writer.emitEnd; + emitPos = writer.emitPos; + setSourceFile = writer.setSourceFile; + } + function withTemporaryNoSourceMap(callback) { + var prevSourceMap = sourceMap; + setSourceMapWriterEmit(ts.getNullSourceMapWriter()); + callback(); + setSourceMapWriterEmit(prevSourceMap); + } 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 */: + case 218 /* InterfaceDeclaration */: + case 216 /* FunctionDeclaration */: + case 225 /* ImportDeclaration */: + case 224 /* ImportEqualsDeclaration */: + case 219 /* TypeAliasDeclaration */: + case 230 /* ExportAssignment */: return true; } } function shouldEmitLeadingAndTrailingComments(node) { switch (node.kind) { - case 193 /* VariableStatement */: + case 196 /* VariableStatement */: return shouldEmitLeadingAndTrailingCommentsForVariableStatement(node); - case 218 /* ModuleDeclaration */: + case 221 /* 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 */: + case 220 /* EnumDeclaration */: // Only emit the leading/trailing comments for an enum if we're actually // emitting the module as well. return shouldEmitEnumDeclaration(node); @@ -35590,9 +38901,9 @@ var ts; // 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 */ && + if (node.kind !== 195 /* Block */ && node.parent && - node.parent.kind === 174 /* ArrowFunction */ && + node.parent.kind === 177 /* ArrowFunction */ && node.parent.body === node && compilerOptions.target <= 1 /* ES5 */) { return false; @@ -35605,13 +38916,13 @@ var ts; switch (node.kind) { case 69 /* Identifier */: return emitIdentifier(node); - case 138 /* Parameter */: + case 139 /* Parameter */: return emitParameter(node); - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: return emitMethod(node); - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: return emitAccessor(node); case 97 /* ThisKeyword */: return emitThis(node); @@ -35631,142 +38942,142 @@ var ts; case 13 /* TemplateMiddle */: case 14 /* TemplateTail */: return emitLiteral(node); - case 183 /* TemplateExpression */: + case 186 /* TemplateExpression */: return emitTemplateExpression(node); - case 190 /* TemplateSpan */: + case 193 /* TemplateSpan */: return emitTemplateSpan(node); - case 233 /* JsxElement */: - case 234 /* JsxSelfClosingElement */: + case 236 /* JsxElement */: + case 237 /* JsxSelfClosingElement */: return emitJsxElement(node); - case 236 /* JsxText */: + case 239 /* JsxText */: return emitJsxText(node); - case 240 /* JsxExpression */: + case 243 /* JsxExpression */: return emitJsxExpression(node); - case 135 /* QualifiedName */: + case 136 /* QualifiedName */: return emitQualifiedName(node); - case 161 /* ObjectBindingPattern */: + case 164 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); - case 162 /* ArrayBindingPattern */: + case 165 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); - case 163 /* BindingElement */: + case 166 /* BindingElement */: return emitBindingElement(node); - case 164 /* ArrayLiteralExpression */: + case 167 /* ArrayLiteralExpression */: return emitArrayLiteral(node); - case 165 /* ObjectLiteralExpression */: + case 168 /* ObjectLiteralExpression */: return emitObjectLiteral(node); - case 245 /* PropertyAssignment */: + case 248 /* PropertyAssignment */: return emitPropertyAssignment(node); - case 246 /* ShorthandPropertyAssignment */: + case 249 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); - case 136 /* ComputedPropertyName */: + case 137 /* ComputedPropertyName */: return emitComputedPropertyName(node); - case 166 /* PropertyAccessExpression */: + case 169 /* PropertyAccessExpression */: return emitPropertyAccess(node); - case 167 /* ElementAccessExpression */: + case 170 /* ElementAccessExpression */: return emitIndexedAccess(node); - case 168 /* CallExpression */: + case 171 /* CallExpression */: return emitCallExpression(node); - case 169 /* NewExpression */: + case 172 /* NewExpression */: return emitNewExpression(node); - case 170 /* TaggedTemplateExpression */: + case 173 /* TaggedTemplateExpression */: return emitTaggedTemplateExpression(node); - case 171 /* TypeAssertionExpression */: + case 174 /* TypeAssertionExpression */: return emit(node.expression); - case 189 /* AsExpression */: + case 192 /* AsExpression */: return emit(node.expression); - case 172 /* ParenthesizedExpression */: + case 175 /* ParenthesizedExpression */: return emitParenExpression(node); - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 216 /* FunctionDeclaration */: + case 176 /* FunctionExpression */: + case 177 /* ArrowFunction */: return emitFunctionDeclaration(node); - case 175 /* DeleteExpression */: + case 178 /* DeleteExpression */: return emitDeleteExpression(node); - case 176 /* TypeOfExpression */: + case 179 /* TypeOfExpression */: return emitTypeOfExpression(node); - case 177 /* VoidExpression */: + case 180 /* VoidExpression */: return emitVoidExpression(node); - case 178 /* AwaitExpression */: + case 181 /* AwaitExpression */: return emitAwaitExpression(node); - case 179 /* PrefixUnaryExpression */: + case 182 /* PrefixUnaryExpression */: return emitPrefixUnaryExpression(node); - case 180 /* PostfixUnaryExpression */: + case 183 /* PostfixUnaryExpression */: return emitPostfixUnaryExpression(node); - case 181 /* BinaryExpression */: + case 184 /* BinaryExpression */: return emitBinaryExpression(node); - case 182 /* ConditionalExpression */: + case 185 /* ConditionalExpression */: return emitConditionalExpression(node); - case 185 /* SpreadElementExpression */: + case 188 /* SpreadElementExpression */: return emitSpreadElementExpression(node); - case 184 /* YieldExpression */: + case 187 /* YieldExpression */: return emitYieldExpression(node); - case 187 /* OmittedExpression */: + case 190 /* OmittedExpression */: return; - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 195 /* Block */: + case 222 /* ModuleBlock */: return emitBlock(node); - case 193 /* VariableStatement */: + case 196 /* VariableStatement */: return emitVariableStatement(node); - case 194 /* EmptyStatement */: + case 197 /* EmptyStatement */: return write(";"); - case 195 /* ExpressionStatement */: + case 198 /* ExpressionStatement */: return emitExpressionStatement(node); - case 196 /* IfStatement */: + case 199 /* IfStatement */: return emitIfStatement(node); - case 197 /* DoStatement */: + case 200 /* DoStatement */: return emitDoStatement(node); - case 198 /* WhileStatement */: + case 201 /* WhileStatement */: return emitWhileStatement(node); - case 199 /* ForStatement */: + case 202 /* ForStatement */: return emitForStatement(node); - case 201 /* ForOfStatement */: - case 200 /* ForInStatement */: + case 204 /* ForOfStatement */: + case 203 /* ForInStatement */: return emitForInOrForOfStatement(node); - case 202 /* ContinueStatement */: - case 203 /* BreakStatement */: + case 205 /* ContinueStatement */: + case 206 /* BreakStatement */: return emitBreakOrContinueStatement(node); - case 204 /* ReturnStatement */: + case 207 /* ReturnStatement */: return emitReturnStatement(node); - case 205 /* WithStatement */: + case 208 /* WithStatement */: return emitWithStatement(node); - case 206 /* SwitchStatement */: + case 209 /* SwitchStatement */: return emitSwitchStatement(node); - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + case 244 /* CaseClause */: + case 245 /* DefaultClause */: return emitCaseOrDefaultClause(node); - case 207 /* LabeledStatement */: - return emitLabelledStatement(node); - case 208 /* ThrowStatement */: + case 210 /* LabeledStatement */: + return emitLabeledStatement(node); + case 211 /* ThrowStatement */: return emitThrowStatement(node); - case 209 /* TryStatement */: + case 212 /* TryStatement */: return emitTryStatement(node); - case 244 /* CatchClause */: + case 247 /* CatchClause */: return emitCatchClause(node); - case 210 /* DebuggerStatement */: + case 213 /* DebuggerStatement */: return emitDebuggerStatement(node); - case 211 /* VariableDeclaration */: + case 214 /* VariableDeclaration */: return emitVariableDeclaration(node); - case 186 /* ClassExpression */: + case 189 /* ClassExpression */: return emitClassExpression(node); - case 214 /* ClassDeclaration */: + case 217 /* ClassDeclaration */: return emitClassDeclaration(node); - case 215 /* InterfaceDeclaration */: + case 218 /* InterfaceDeclaration */: return emitInterfaceDeclaration(node); - case 217 /* EnumDeclaration */: + case 220 /* EnumDeclaration */: return emitEnumDeclaration(node); - case 247 /* EnumMember */: + case 250 /* EnumMember */: return emitEnumMember(node); - case 218 /* ModuleDeclaration */: + case 221 /* ModuleDeclaration */: return emitModuleDeclaration(node); - case 222 /* ImportDeclaration */: + case 225 /* ImportDeclaration */: return emitImportDeclaration(node); - case 221 /* ImportEqualsDeclaration */: + case 224 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); - case 228 /* ExportDeclaration */: + case 231 /* ExportDeclaration */: return emitExportDeclaration(node); - case 227 /* ExportAssignment */: + case 230 /* ExportAssignment */: return emitExportAssignment(node); - case 248 /* SourceFile */: + case 251 /* SourceFile */: return emitSourceFileNode(node); } } @@ -35775,7 +39086,7 @@ var ts; } function getLeadingCommentsWithoutDetachedComments() { // get the leading comments from detachedPos - var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); + var leadingComments = ts.getLeadingCommentRanges(currentText, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); } @@ -35784,10 +39095,6 @@ var ts; } 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 * @@ -35796,10 +39103,10 @@ var ts; 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 */ && + if (currentText.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); + currentText.charCodeAt(comment.pos + 2) === 47 /* slash */) { + var textSubStr = currentText.substring(comment.pos, comment.end); return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) || textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ? true : false; @@ -35809,14 +39116,14 @@ var ts; 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 (node.parent.kind === 251 /* 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); + return ts.getLeadingCommentRangesOfNodeFromText(node, currentText); } } } @@ -35824,8 +39131,8 @@ var ts; 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); + if (node.parent.kind === 251 /* SourceFile */ || node.end !== node.parent.end) { + return ts.getTrailingCommentRanges(currentText, node.end); } } } @@ -35833,10 +39140,10 @@ var ts; * Emit comments associated with node that will not be emitted into JS file */ function emitCommentsOnNotEmittedNode(node) { - emitLeadingCommentsWorker(node, /*isEmittedNode:*/ false); + emitLeadingCommentsWorker(node, /*isEmittedNode*/ false); } function emitLeadingComments(node) { - return emitLeadingCommentsWorker(node, /*isEmittedNode:*/ true); + return emitLeadingCommentsWorker(node, /*isEmittedNode*/ true); } function emitLeadingCommentsWorker(node, isEmittedNode) { if (compilerOptions.removeComments) { @@ -35859,9 +39166,9 @@ var ts; leadingComments = ts.filter(getLeadingCommentsToEmit(node), isTripleSlashComment); } } - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); + ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, node, leadingComments); // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator:*/ true, newLine, writeComment); + ts.emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment); } function emitTrailingComments(node) { if (compilerOptions.removeComments) { @@ -35870,7 +39177,7 @@ var ts; // 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); + ts.emitComments(currentText, currentLineMap, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment); } /** * Emit trailing comments at the position. The term trailing comment is used here to describe following comment: @@ -35881,9 +39188,9 @@ var ts; if (compilerOptions.removeComments) { return; } - var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, pos); + var trailingComments = ts.getTrailingCommentRanges(currentText, pos); // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ - ts.emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment); + ts.emitComments(currentText, currentLineMap, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment); } function emitLeadingCommentsOfPositionWorker(pos) { if (compilerOptions.removeComments) { @@ -35896,78 +39203,48 @@ var ts; } else { // get the leading comments from the node - leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, pos); + leadingComments = ts.getLeadingCommentRanges(currentText, pos); } - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments); + ts.emitNewLineBeforeLeadingComments(currentLineMap, 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); + ts.emitComments(currentText, currentLineMap, 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); + function emitDetachedCommentsAndUpdateCommentsInfo(node) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentText, currentLineMap, writer, writeComment, node, newLine, compilerOptions.removeComments); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); } - } - 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]; - } - } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; } } } + function writeComment(text, lineMap, writer, comment, newLine) { + emitPos(comment.pos); + ts.writeCommentRange(text, lineMap, writer, comment, newLine); + emitPos(comment.end); + } function emitShebang() { - var shebang = ts.getShebang(currentSourceFile.text); + var shebang = ts.getShebang(currentText); if (shebang) { write(shebang); + writeLine(); } } - var _a; + var _a, _b; } - function emitFile(jsFilePath, sourceFile) { - emitJavaScript(jsFilePath, sourceFile); - if (compilerOptions.declaration) { - ts.writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics); + function emitFile(_a, sourceFiles, isBundledEmit) { + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; + // Make sure not to write js File and source map file if any of them cannot be written + if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { + emitJavaScript(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } + else { + emitSkipped = true; + } + if (declarationFilePath) { + emitSkipped = ts.writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; } } } @@ -35984,11 +39261,11 @@ var ts; /* @internal */ ts.ioWriteTime = 0; /** The version of the TypeScript compiler release */ var emptyArray = []; - ts.version = "1.7.5"; - function findConfigFile(searchPath) { + ts.version = "1.8.7"; + function findConfigFile(searchPath, fileExists) { var fileName = "tsconfig.json"; while (true) { - if (ts.sys.fileExists(fileName)) { + if (fileExists(fileName)) { return fileName; } var parentPath = ts.getDirectoryPath(searchPath); @@ -36010,23 +39287,24 @@ var ts; function resolveModuleName(moduleName, containingFile, compilerOptions, host) { var moduleResolution = compilerOptions.moduleResolution !== undefined ? compilerOptions.moduleResolution - : compilerOptions.module === 1 /* CommonJS */ ? 2 /* NodeJs */ : 1 /* Classic */; + : ts.getEmitModuleKind(compilerOptions) === 1 /* CommonJS */ ? 2 /* NodeJs */ : 1 /* Classic */; switch (moduleResolution) { - case 2 /* NodeJs */: return nodeModuleNameResolver(moduleName, containingFile, host); + case 2 /* NodeJs */: return nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); case 1 /* Classic */: return classicNameResolver(moduleName, containingFile, compilerOptions, host); } } ts.resolveModuleName = resolveModuleName; - function nodeModuleNameResolver(moduleName, containingFile, host) { + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); if (ts.getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) { var failedLookupLocations = []; var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var resolvedFileName = loadNodeModuleFromFile(candidate, failedLookupLocations, host); + var resolvedFileName = loadNodeModuleFromFile(supportedExtensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, host); if (resolvedFileName) { return { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations }; } - resolvedFileName = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host); + resolvedFileName = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, host); return resolvedFileName ? { resolvedModule: { resolvedFileName: resolvedFileName }, failedLookupLocations: failedLookupLocations } : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; @@ -36036,11 +39314,21 @@ var ts; } } ts.nodeModuleNameResolver = nodeModuleNameResolver; - function loadNodeModuleFromFile(candidate, failedLookupLocation, host) { - return ts.forEach(ts.moduleFileExtensions, tryLoad); + /* @internal */ + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + /** + * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary + * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. + */ + function loadNodeModuleFromFile(extensions, candidate, failedLookupLocation, onlyRecordFailures, host) { + return ts.forEach(extensions, tryLoad); function tryLoad(ext) { var fileName = ts.fileExtensionIs(candidate, ext) ? candidate : candidate + ext; - if (host.fileExists(fileName)) { + if (!onlyRecordFailures && host.fileExists(fileName)) { return fileName; } else { @@ -36049,20 +39337,22 @@ var ts; } } } - function loadNodeModuleFromDirectory(candidate, failedLookupLocation, host) { + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, host) { var packageJsonPath = ts.combinePaths(candidate, "package.json"); - if (host.fileExists(packageJsonPath)) { - var jsonContent; + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, host); + if (directoryExists && host.fileExists(packageJsonPath)) { + var jsonContent = void 0; try { var jsonText = host.readFile(packageJsonPath); jsonContent = jsonText ? JSON.parse(jsonText) : { typings: undefined }; } catch (e) { - // gracefully handle if readFile fails or returns not JSON + // 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 (typeof jsonContent.typings === "string") { + var path = ts.normalizePath(ts.combinePaths(candidate, jsonContent.typings)); + var result = loadNodeModuleFromFile(extensions, path, failedLookupLocation, !directoryProbablyExists(ts.getDirectoryPath(path), host), host); if (result) { return result; } @@ -36072,7 +39362,7 @@ var ts; // 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); + return loadNodeModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocation, !directoryExists, host); } function loadModuleFromNodeModules(moduleName, directory, host) { var failedLookupLocations = []; @@ -36081,12 +39371,14 @@ var ts; var baseName = ts.getBaseFileName(directory); if (baseName !== "node_modules") { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, host); var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var result = loadNodeModuleFromFile(candidate, failedLookupLocations, host); + // Load only typescript files irrespective of allowJs option if loading from node modules + var result = loadNodeModuleFromFile(ts.supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, host); if (result) { return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; } - result = loadNodeModuleFromDirectory(candidate, failedLookupLocations, host); + result = loadNodeModuleFromDirectory(ts.supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, host); if (result) { return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations: failedLookupLocations }; } @@ -36112,11 +39404,12 @@ var ts; var searchName; var failedLookupLocations = []; var referencedSourceFile; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); while (true) { searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName)); - referencedSourceFile = ts.forEach(ts.supportedExtensions, function (extension) { + referencedSourceFile = ts.forEach(supportedExtensions, function (extension) { if (extension === ".tsx" && !compilerOptions.jsx) { - // resolve .tsx files only if jsx support is enabled + // resolve .tsx files only if jsx support is enabled // 'logical not' handles both undefined and None cases return undefined; } @@ -36145,14 +39438,11 @@ var ts; /* @internal */ ts.defaultInitCompilerOptions = { module: 1 /* CommonJS */, - target: 0 /* ES3 */, + target: 1 /* ES5 */, 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. @@ -36213,19 +39503,20 @@ var ts; 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()); }, + getCurrentDirectory: ts.memoize(function () { return 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); } + readFile: function (fileName) { return ts.sys.readFile(fileName); }, + directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); } }; } 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)); + diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); } @@ -36263,12 +39554,37 @@ var ts; var noDiagnosticsTypeChecker; var classifiableNames; var skipDefaultLib = options.noLib; + var supportedExtensions = ts.getSupportedExtensions(options); var start = new Date().getTime(); host = host || createCompilerHost(options); + // Map storing if there is emit blocking diagnostics for given input + var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName); + var currentDirectory = host.getCurrentDirectory(); 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); }); + : (function (moduleNames, containingFile) { + var resolvedModuleNames = []; + // resolveModuleName does not store any results between calls. + // lookup is a local cache to avoid resolving the same module name several times + var lookup = {}; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedName = void 0; + if (ts.hasProperty(lookup, moduleName)) { + resolvedName = lookup[moduleName]; + } + else { + resolvedName = resolveModuleName(moduleName, containingFile, options, host).resolvedModule; + lookup[moduleName] = resolvedName; + } + resolvedModuleNames.push(resolvedName); + } + return resolvedModuleNames; + }); + var filesByName = ts.createFileMap(); + // stores 'filename -> file association' ignoring case + // used to track cases when two file names differ only in casing + var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; 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 @@ -36277,24 +39593,23 @@ var ts; (oldOptions.noResolve !== options.noResolve) || (oldOptions.target !== options.target) || (oldOptions.noLib !== options.noLib) || - (oldOptions.jsx !== options.jsx)) { + (oldOptions.jsx !== options.jsx) || + (oldOptions.allowJs !== options.allowJs)) { oldProgram = undefined; } } if (!tryReuseStructureFromOldProgram()) { - ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); + ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ 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); + processRootFile(host.getDefaultLibFileName(options), /*isDefaultLib*/ 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, @@ -36308,23 +39623,43 @@ var ts; getTypeChecker: getTypeChecker, getClassifiableNames: getClassifiableNames, getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, - getCommonSourceDirectory: function () { return commonSourceDirectory; }, + getCommonSourceDirectory: getCommonSourceDirectory, emit: emit, - getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + getCurrentDirectory: function () { return currentDirectory; }, getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); }, getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; } }; + verifyCompilerOptions(); + ts.programTime += new Date().getTime() - start; return program; + function getCommonSourceDirectory() { + if (typeof commonSourceDirectory === "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, currentDirectory); + } + else { + 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; + } + } + return commonSourceDirectory; + } 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]; + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var sourceFile = files_3[_i]; ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } @@ -36342,6 +39677,7 @@ var ts; } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; + var filePaths = []; var modifiedSourceFiles = []; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; @@ -36349,6 +39685,8 @@ var ts; if (!newSourceFile) { return false; } + newSourceFile.path = oldSourceFile.path; + filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed @@ -36360,17 +39698,21 @@ var ts; // tripleslash references has changed return false; } - // check imports + // check imports and module augmentations collectExternalModuleReferences(newSourceFile); if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { // imports has changed return false; } + if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + // moduleAugmentations has changed + return false; + } if (resolveModuleNamesWorker) { - var moduleNames = ts.map(newSourceFile.imports, function (name) { return name.text; }); - var resolutions = resolveModuleNamesWorker(moduleNames, newSourceFile.fileName); + var moduleNames = ts.map(ts.concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral); + var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); // ensure that module resolution results are still correct - for (var i = 0; i < moduleNames.length; ++i) { + for (var i = 0; i < moduleNames.length; i++) { var newResolution = resolutions[i]; var oldResolution = ts.getResolvedModule(oldSourceFile, moduleNames[i]); var resolutionChanged = oldResolution @@ -36395,14 +39737,13 @@ var ts; newSourceFiles.push(newSourceFile); } // update fileName -> file mapping - for (var _b = 0; _b < newSourceFiles.length; _b++) { - var file = newSourceFiles[_b]; - filesByName.set(file.fileName, file); + for (var i = 0, len = newSourceFiles.length; i < len; i++) { + filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _c = 0; _c < modifiedSourceFiles.length; _c++) { - var modifiedFile = modifiedSourceFiles[_c]; + for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { + var modifiedFile = modifiedSourceFiles_1[_b]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile); } oldProgram.structureIsReused = true; @@ -36410,14 +39751,15 @@ var ts; } function getEmitHost(writeFileCallback) { return { - getCanonicalFileName: function (fileName) { return host.getCanonicalFileName(fileName); }, + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, - getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + getCurrentDirectory: function () { return currentDirectory; }, 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); }) + writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError) { return host.writeFile(fileName, data, writeByteOrderMark, onError); }), + isEmitBlocked: isEmitBlocked }; } function getDiagnosticsProducingTypeChecker() { @@ -36430,12 +39772,22 @@ var ts; var _this = this; return runWithCancellationToken(function () { return emitWorker(_this, sourceFile, writeFileCallback, cancellationToken); }); } + function isEmitBlocked(emitFileName) { + return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); + } 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 }; + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + var declarationDiagnostics = []; + if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { diagnostics: declarationDiagnostics, 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 @@ -36452,9 +39804,7 @@ var ts; 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())); + return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); } function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { if (sourceFile) { @@ -36476,7 +39826,14 @@ var ts; return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken); } function getDeclarationDiagnostics(sourceFile, cancellationToken) { - return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); + var options = program.getCompilerOptions(); + // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit) + if (!sourceFile || options.out || options.outFile) { + return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + } + else { + return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); + } } function getSyntacticDiagnosticsForFile(sourceFile, cancellationToken) { return sourceFile.parseDiagnostics; @@ -36507,22 +39864,180 @@ var ts; var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); var bindDiagnostics = sourceFile.bindDiagnostics; - var checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken); + // 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. + var checkDiagnostics = ts.isSourceFileJavaScript(sourceFile) ? + getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) : + 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) { + function getJavaScriptSemanticDiagnosticsForFile(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); + var diagnostics = []; + walk(sourceFile); + return diagnostics; + function walk(node) { + if (!node) { + return false; + } + switch (node.kind) { + case 224 /* ImportEqualsDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return true; + case 230 /* ExportAssignment */: + if (node.isExportEquals) { + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 217 /* ClassDeclaration */: + var classDeclaration = node; + if (checkModifiers(classDeclaration.modifiers) || + checkTypeParameters(classDeclaration.typeParameters)) { + return true; + } + break; + case 246 /* 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 218 /* InterfaceDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 221 /* ModuleDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 219 /* TypeAliasDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return true; + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 145 /* Constructor */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 176 /* FunctionExpression */: + case 216 /* FunctionDeclaration */: + case 177 /* ArrowFunction */: + case 216 /* FunctionDeclaration */: + var functionDeclaration = node; + if (checkModifiers(functionDeclaration.modifiers) || + checkTypeParameters(functionDeclaration.typeParameters) || + checkTypeAnnotation(functionDeclaration.type)) { + return true; + } + break; + case 196 /* VariableStatement */: + var variableStatement = node; + if (checkModifiers(variableStatement.modifiers)) { + return true; + } + break; + case 214 /* VariableDeclaration */: + var variableDeclaration = node; + if (checkTypeAnnotation(variableDeclaration.type)) { + return true; + } + break; + case 171 /* CallExpression */: + case 172 /* NewExpression */: + var expression = node; + if (expression.typeArguments && expression.typeArguments.length > 0) { + var start_2 = expression.typeArguments.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_2, expression.typeArguments.end - start_2, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return true; + } + break; + case 139 /* Parameter */: + var parameter = node; + if (parameter.modifiers) { + var start_3 = parameter.modifiers.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_3, parameter.modifiers.end - start_3, 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 142 /* PropertyDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 220 /* EnumDeclaration */: + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return true; + case 174 /* 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 140 /* Decorator */: + if (!options.experimentalDecorators) { + diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + } + return true; + } + return ts.forEachChild(node, walk); + } + function checkTypeParameters(typeParameters) { + if (typeParameters) { + var start_4 = typeParameters.pos; + diagnostics.push(ts.createFileDiagnostic(sourceFile, start_4, typeParameters.end - start_4, 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, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_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 getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); + // Don't actually write any files since we're just getting diagnostics. + var writeFile = function () { }; + return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile); + }); + } + function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { + return ts.isDeclarationFile(sourceFile) ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + } function getOptionsDiagnostics() { var allDiagnostics = []; ts.addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics()); @@ -36546,21 +40061,32 @@ var ts; function moduleNameIsEqualTo(a, b) { return a.text === b.text; } + function getTextOfLiteral(literal) { + return literal.text; + } function collectExternalModuleReferences(file) { if (file.imports) { return; } + var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isExternalModuleFile = ts.isExternalModule(file); var imports; + var moduleAugmentations; for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; - collect(node, /* allowRelativeModuleNames */ true); + collectModuleReferences(node, /*inAmbientModule*/ false); + if (isJavaScriptFile) { + collectRequireCalls(node); + } } file.imports = imports || emptyArray; - function collect(node, allowRelativeModuleNames) { + file.moduleAugmentations = moduleAugmentations || emptyArray; + return; + function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { - case 222 /* ImportDeclaration */: - case 221 /* ImportEqualsDeclaration */: - case 228 /* ExportDeclaration */: + case 225 /* ImportDeclaration */: + case 224 /* ImportEqualsDeclaration */: + case 231 /* ExportDeclaration */: var moduleNameExpr = ts.getExternalModuleName(node); if (!moduleNameExpr || moduleNameExpr.kind !== 9 /* StringLiteral */) { break; @@ -36568,25 +40094,44 @@ var ts; if (!moduleNameExpr.text) { break; } - if (allowRelativeModuleNames || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) { + // TypeScript 1.0 spec (April 2014): 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. + if (!inAmbientModule || !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); - }); + case 221 /* ModuleDeclaration */: + if (ts.isAmbientModule(node) && (inAmbientModule || node.flags & 4 /* Ambient */ || ts.isDeclarationFile(file))) { + var moduleName = node.name; + // Ambient module declarations can be interpreted as augmentations for some existing external modules. + // This will happen in two cases: + // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope + // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name + // immediately nested in top level ambient module declaration . + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { + (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); + } + else if (!inAmbientModule) { + // 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 + // NOTE: body of ambient module is always a module block + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, /*inAmbientModule*/ true); + } + } } - break; + } + } + function collectRequireCalls(node) { + if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + (imports || (imports = [])).push(node.arguments[0]); + } + else { + ts.forEachChild(node, collectRequireCalls); } } } @@ -36594,11 +40139,11 @@ var ts; var diagnosticArgument; var diagnostic; if (hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(ts.supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(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("', '") + "'"]; + diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"]; } - else if (!findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd)) { + else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } @@ -36608,13 +40153,13 @@ var ts; } } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, isDefaultLib, refFile, refPos, refEnd); + var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), 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); })) { + else if (!ts.forEach(supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { diagnostic = ts.Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; @@ -36630,18 +40175,23 @@ var ts; } } } + function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { + 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, existingFileName)); + } + else { + fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); + } + } // 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); + function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { + if (filesByName.contains(path)) { + var file_1 = filesByName.get(path); + // try to check if we've already seen this file but with a different casing in path + // NOTE: this only makes sense for case-insensitive file systems + if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { + reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); + } return file_1; } // We haven't looked for this file, do so now and cache result @@ -36653,11 +40203,20 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); } }); - filesByName.set(fileName, file); + filesByName.set(path, file); if (file) { + file.path = path; + if (host.useCaseSensitiveFileNames()) { + // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case + var existingFile = filesByNameIgnoreCase.get(path); + if (existingFile) { + reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); + } + else { + filesByNameIgnoreCase.set(path, 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); @@ -36665,7 +40224,6 @@ var ts; // always process imported modules to record module name resolutions processImportedModules(file, basePath); if (isDefaultLib) { - file.isDefaultLib = true; files.unshift(file); } else { @@ -36673,43 +40231,40 @@ var ts; } } 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); + processSourceFile(referencedFileName, /*isDefaultLib*/ false, file, ref.pos, ref.end); }); } + function getCanonicalFileName(fileName) { + return host.getCanonicalFileName(fileName); + } function processImportedModules(file, basePath) { collectExternalModuleReferences(file); - if (file.imports.length) { + if (file.imports.length || file.moduleAugmentations.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 moduleNames = ts.map(ts.concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral); + var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory)); + for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - if (resolution && !options.noResolve) { - var importedFile = findModuleSourceFile(resolution.resolvedFileName, file.imports[i]); + // add file to program only if: + // - resolution was successfull + // - noResolve is falsy + // - module name come from the list fo imports + var shouldAddFile = resolution && + !options.noResolve && + i < file.imports.length; + if (shouldAddFile) { + var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); 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)); + // Since currently irrespective of allowJs, we only look for supportedTypeScript extension external module files, + // this check is ok. Otherwise this would be never true for javascript file + if (!ts.isExternalModule(importedFile) && importedFile.statements.length) { + var start_5 = ts.getTokenPosOfNode(file.imports[i], file); + fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, start_5, file.imports[i].end - start_5, 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]; @@ -36724,14 +40279,10 @@ var ts; 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) { + var failed = ts.forEach(files, function (sourceFile) { // Each file contributes into common source file path if (ts.isDeclarationFile(sourceFile)) { return; @@ -36744,10 +40295,10 @@ var ts; return; } for (var i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) { - if (commonPathComponents[i] !== sourcePathComponents[i]) { + if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { if (i === 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); - return; + // Failed to find any common path component + return true; } // New common path found that is 0 -> i-1 commonPathComponents.length = i; @@ -36759,15 +40310,21 @@ var ts; commonPathComponents.length = sourcePathComponents.length; } }); + // A common path can not be found when paths span multiple drives on windows, for example + if (failed) { + return ""; + } + if (!commonPathComponents) { + return currentDirectory; + } 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]; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -36801,14 +40358,14 @@ var ts; 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.sourceRoot) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSources")); + } } if (options.out && options.outFile) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile")); @@ -36818,17 +40375,16 @@ var ts; if (options.mapRoot) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap")); } - if (options.sourceRoot) { + if (options.sourceRoot && !options.inlineSourceMap) { 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)); + if (options.module === 0 /* None */ && 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_ES2015_or_higher)); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); if (firstNonExternalModuleSourceFile) { @@ -36836,34 +40392,29 @@ var ts; 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) { + else if (firstExternalModuleSourceFile && languageVersion < 2 /* ES6 */ && options.module === 0 /* None */) { // 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)); + programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file)); } // 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)); + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); + } + // Cannot specify module gen that isn't amd or system with --out + if (outFile && options.module && !(options.module === 2 /* AMD */ || options.module === 4 /* System */)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); } // 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; + options.mapRoot) { + // Precalculate and cache the common source directory + var dir = getCommonSourceDirectory(); + // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure + if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); } } if (options.noEmit) { @@ -36880,10 +40431,47 @@ var ts; programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration")); } } + else if (options.allowJs && options.declaration) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration")); + } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); } + if (options.reactNamespace && !ts.isIdentifier(options.reactNamespace, languageVersion)) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalide_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); + } + // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files + if (!options.noEmit && !options.suppressOutputPathCheck) { + var emitHost = getEmitHost(); + var emitFilesSeen_1 = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined); + ts.forEachExpectedEmitFile(emitHost, function (emitFileNames, sourceFiles, isBundledEmit) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); + }); + } + // Verify that all the emit files are unique and don't overwrite input files + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + var emitFilePath = ts.toPath(emitFileName, currentDirectory, getCanonicalFileName); + // Report error if the output overwrites input file + if (filesByName.contains(emitFilePath)) { + createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file); + } + // Report error if multiple files write into same file + if (emitFilesSeen.contains(emitFilePath)) { + // Already seen the same emit file - report error + createEmitBlockingDiagnostics(emitFileName, emitFilePath, ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files); + } + else { + emitFilesSeen.set(emitFilePath, true); + } + } + } + } + function createEmitBlockingDiagnostics(emitFileName, emitFilePath, message) { + hasEmitBlockingDiagnostics.set(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName), true); + programDiagnostics.add(ts.createCompilerDiagnostic(message, emitFileName)); } } ts.createProgram = createProgram; @@ -36891,6 +40479,7 @@ var ts; /// /// /// +/// /// var ts; (function (ts) { @@ -36943,6 +40532,11 @@ var ts; description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react, error: ts.Diagnostics.Argument_for_jsx_must_be_preserve_or_react }, + { + name: "reactNamespace", + type: "string", + description: ts.Diagnostics.Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit + }, { name: "listFiles", type: "boolean" @@ -36962,6 +40556,7 @@ var ts; name: "module", shortName: "m", type: { + "none": 0 /* None */, "commonjs": 1 /* CommonJS */, "amd": 2 /* AMD */, "system": 4 /* System */, @@ -36969,9 +40564,9 @@ var ts; "es6": 5 /* ES6 */, "es2015": 5 /* ES2015 */ }, - description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es6, + description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, paramType: ts.Diagnostics.KIND, - error: ts.Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_umd_or_es6 + error: ts.Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_umd_es2015_or_none }, { name: "newLine", @@ -37040,6 +40635,12 @@ var ts; type: "boolean", description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code }, + { + name: "pretty", + paramType: ts.Diagnostics.KIND, + description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental, + type: "boolean" + }, { name: "project", shortName: "p", @@ -37102,9 +40703,9 @@ var ts; "es6": 2 /* ES6 */, "es2015": 2 /* ES2015 */ }, - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES6_experimental, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental, paramType: ts.Diagnostics.VERSION, - error: ts.Diagnostics.Argument_for_target_option_must_be_ES3_ES5_or_ES6 + error: ts.Diagnostics.Argument_for_target_option_must_be_ES3_ES5_or_ES2015 }, { name: "version", @@ -37137,6 +40738,51 @@ var ts; }, 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 + }, + { + name: "allowUnusedLabels", + type: "boolean", + description: ts.Diagnostics.Do_not_report_errors_on_unused_labels + }, + { + name: "noImplicitReturns", + type: "boolean", + description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value + }, + { + name: "noFallthroughCasesInSwitch", + type: "boolean", + description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement + }, + { + name: "allowUnreachableCode", + type: "boolean", + description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code + }, + { + name: "forceConsistentCasingInFileNames", + type: "boolean", + description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file + }, + { + name: "allowSyntheticDefaultImports", + type: "boolean", + description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking + }, + { + name: "allowJs", + type: "boolean", + description: ts.Diagnostics.Allow_javascript_files_to_be_compiled + }, + { + name: "noImplicitUseStrict", + type: "boolean", + description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output + }, + { + name: "noCustomAsyncPromise", + type: "boolean", + experimental: true } ]; var optionNameMapCache; @@ -37171,7 +40817,8 @@ var ts; function parseStrings(args) { var i = 0; while (i < args.length) { - var s = args[i++]; + var s = args[i]; + i++; if (s.charCodeAt(0) === 64 /* at */) { parseResponseFile(s.slice(1)); } @@ -37189,20 +40836,23 @@ var ts; } switch (opt.type) { case "number": - options[opt.name] = parseInt(args[i++]); + options[opt.name] = parseInt(args[i]); + i++; break; case "boolean": options[opt.name] = true; break; case "string": - options[opt.name] = args[i++] || ""; + options[opt.name] = args[i] || ""; + 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]; + var map_1 = opt.type; + var key = (args[i] || "").toLowerCase(); + i++; + if (ts.hasProperty(map_1, key)) { + options[opt.name] = map_1[key]; } else { errors.push(ts.createCompilerDiagnostic(opt.error)); @@ -37276,70 +40926,54 @@ var ts; */ function parseConfigFileTextToJson(fileName, jsonText) { try { - return { config: /\S/.test(jsonText) ? JSON.parse(jsonText) : {} }; + var jsonTextWithoutComments = removeComments(jsonText); + return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; } } ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + /** + * Remove the comments from a json like text. + * Comments can be single line comments (starting with # or //) or multiline comments using / * * / + * + * This method replace comment content by whitespace rather than completely remove them to keep positions in json parsing error reporting accurate. + */ + function removeComments(jsonText) { + var output = ""; + var scanner = ts.createScanner(1 /* ES5 */, /* skipTrivia */ false, 0 /* Standard */, jsonText); + var token; + while ((token = scanner.scan()) !== 1 /* EndOfFileToken */) { + switch (token) { + case 2 /* SingleLineCommentTrivia */: + case 3 /* MultiLineCommentTrivia */: + // replace comments with whitespace to preserve original character positions + output += scanner.getTokenText().replace(/\S/g, " "); + break; + default: + output += scanner.getTokenText(); + break; + } + } + return output; + } /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. * @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 = []; + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { + if (existingOptions === void 0) { existingOptions = {}; } + var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath, configFileName), optionsFromJsonConfigFile = _a.options, errors = _a.errors; + var options = ts.extend(existingOptions, optionsFromJsonConfigFile); return { - options: getCompilerOptions(), + options: options, 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")) { @@ -37351,23 +40985,47 @@ var ts; } } 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); + var filesSeen = {}; + var exclude = []; + if (json["exclude"] instanceof Array) { + exclude = json["exclude"]; + } + else { + // by default exclude node_modules, and any specificied output directory + exclude = ["node_modules"]; + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + exclude.push(outDir); + } + } + exclude = ts.map(exclude, ts.normalizeSlashes); + var supportedExtensions = ts.getSupportedExtensions(options); + ts.Debug.assert(ts.indexOf(supportedExtensions, ".ts") < ts.indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); + // Get files of supported extensions in their order of resolution + for (var _i = 0, supportedExtensions_1 = supportedExtensions; _i < supportedExtensions_1.length; _i++) { + var extension = supportedExtensions_1[_i]; + var filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); + for (var _a = 0, filesInDirWithExtension_1 = filesInDirWithExtension; _a < filesInDirWithExtension_1.length; _a++) { + var fileName = filesInDirWithExtension_1[_a]; + // .ts extension would read the .d.ts extension files too but since .d.ts is lower priority extension, + // lets pick them when its turn comes up + if (extension === ".ts" && ts.fileExtensionIs(fileName, ".d.ts")) { + continue; } - } - else if (ts.fileExtensionIs(name_28, ".ts")) { - if (!ts.contains(sysFiles, name_28 + "x")) { - fileNames.push(name_28); + // Skip over any minified JavaScript files (ending in ".min.js") + if (/\.min\.js$/.test(fileName)) { + continue; } - } - else { - fileNames.push(name_28); + // If this is one of the output extension (which would be .d.ts and .js if we are allowing compilation of js files) + // do not include this file if we included .ts or .tsx file with same base name as it could be output of the earlier compilation + if (extension === ".d.ts" || (options.allowJs && ts.contains(ts.supportedJavascriptExtensions, extension))) { + var baseName = fileName.substr(0, fileName.length - extension.length); + if (ts.hasProperty(filesSeen, baseName + ".ts") || ts.hasProperty(filesSeen, baseName + ".tsx")) { + continue; + } + } + filesSeen[fileName] = true; + fileNames.push(fileName); } } } @@ -37375,6 +41033,52 @@ var ts; } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { + var options = {}; + var errors = []; + if (configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json") { + options.allowJs = true; + } + if (!jsonOptions) { + return { options: options, errors: errors }; + } + var optionNameMap = ts.arrayToMap(ts.optionDeclarations, function (opt) { return opt.name; }); + 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: options, errors: errors }; + } + ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson; })(ts || (ts = {})); /* @internal */ var ts; @@ -37413,8 +41117,8 @@ var ts; var lastSingleLineCommentEnd = -1; var isFirstSingleLineComment = true; var singleLineCommentCount = 0; - for (var _i = 0; _i < comments.length; _i++) { - var currentComment = comments[_i]; + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var currentComment = comments_2[_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 */) { @@ -37448,7 +41152,7 @@ var ts; } } function autoCollapse(node) { - return ts.isFunctionBlock(node) && node.parent.kind !== 174 /* ArrowFunction */; + return ts.isFunctionBlock(node) && node.parent.kind !== 177 /* ArrowFunction */; } var depth = 0; var maxDepth = 20; @@ -37460,30 +41164,30 @@ var ts; addOutliningForLeadingCommentsForNode(n); } switch (n.kind) { - case 192 /* Block */: + case 195 /* Block */: if (!ts.isFunctionBlock(n)) { - var parent_7 = n.parent; + var parent_9 = 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)); + if (parent_9.kind === 200 /* DoStatement */ || + parent_9.kind === 203 /* ForInStatement */ || + parent_9.kind === 204 /* ForOfStatement */ || + parent_9.kind === 202 /* ForStatement */ || + parent_9.kind === 199 /* IfStatement */ || + parent_9.kind === 201 /* WhileStatement */ || + parent_9.kind === 208 /* WithStatement */ || + parent_9.kind === 247 /* CatchClause */) { + addOutliningSpan(parent_9, openBrace, closeBrace, autoCollapse(n)); break; } - if (parent_7.kind === 209 /* TryStatement */) { + if (parent_9.kind === 212 /* TryStatement */) { // Could be the try-block, or the finally-block. - var tryStatement = parent_7; + var tryStatement = parent_9; if (tryStatement.tryBlock === n) { - addOutliningSpan(parent_7, openBrace, closeBrace, autoCollapse(n)); + addOutliningSpan(parent_9, openBrace, closeBrace, autoCollapse(n)); break; } else if (tryStatement.finallyBlock === n) { @@ -37506,23 +41210,23 @@ var ts; break; } // Fallthrough. - case 219 /* ModuleBlock */: { + case 222 /* 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 */: { + case 217 /* ClassDeclaration */: + case 218 /* InterfaceDeclaration */: + case 220 /* EnumDeclaration */: + case 168 /* ObjectLiteralExpression */: + case 223 /* 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 */: + case 167 /* ArrayLiteralExpression */: var openBracket = ts.findChildOfKind(n, 19 /* OpenBracketToken */, sourceFile); var closeBracket = ts.findChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); @@ -37546,21 +41250,23 @@ var ts; function getNavigateToItems(program, cancellationToken, searchValue, maxResultCount) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; + // This means "compare in a case insensitive manner." + var baseSensitivity = { sensitivity: "base" }; // 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); + for (var name_32 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_32); 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); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_32); if (!matches) { continue; } - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_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) { @@ -37568,14 +41274,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_29); + matches = patternMatcher.getMatches(containers, name_32); 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.push({ name: name_32, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -37589,8 +41295,8 @@ var ts; 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]; + for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { + var match = matches_1[_i]; if (!match.isCaseSensitive) { return false; } @@ -37613,8 +41319,8 @@ var ts; if (text !== undefined) { containers.unshift(text); } - else if (declaration.name.kind === 136 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion:*/ true); + else if (declaration.name.kind === 137 /* ComputedPropertyName */) { + return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ true); } else { // Don't know how to add this. @@ -37634,12 +41340,12 @@ var ts; } return true; } - if (expression.kind === 166 /* PropertyAccessExpression */) { + if (expression.kind === 169 /* PropertyAccessExpression */) { var propertyAccess = expression; if (includeLastPortion) { containers.unshift(propertyAccess.name.text); } - return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion:*/ true); + return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion*/ true); } return false; } @@ -37647,8 +41353,8 @@ var ts; 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)) { + if (declaration.name.kind === 137 /* ComputedPropertyName */) { + if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ false)) { return undefined; } } @@ -37665,8 +41371,8 @@ var ts; 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]; + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; var kind = match.kind; if (kind < bestMatchKind) { bestMatchKind = kind; @@ -37674,8 +41380,6 @@ var ts; } 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. @@ -37711,7 +41415,7 @@ var ts; (function (ts) { var NavigationBar; (function (NavigationBar) { - function getNavigationBarItems(sourceFile) { + function getNavigationBarItems(sourceFile, compilerOptions) { // 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; @@ -37723,17 +41427,17 @@ var ts; var current = node.parent; while (current) { switch (current.kind) { - case 218 /* ModuleDeclaration */: + case 221 /* 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 */); + } while (current.kind === 221 /* ModuleDeclaration */); // fall through - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 215 /* InterfaceDeclaration */: - case 213 /* FunctionDeclaration */: + case 217 /* ClassDeclaration */: + case 220 /* EnumDeclaration */: + case 218 /* InterfaceDeclaration */: + case 216 /* FunctionDeclaration */: indent++; } current = current.parent; @@ -37744,21 +41448,21 @@ var ts; var childNodes = []; function visit(node) { switch (node.kind) { - case 193 /* VariableStatement */: + case 196 /* VariableStatement */: ts.forEach(node.declarationList.declarations, visit); break; - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: + case 164 /* ObjectBindingPattern */: + case 165 /* ArrayBindingPattern */: ts.forEach(node.elements, visit); break; - case 228 /* ExportDeclaration */: + case 231 /* 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 */: + case 225 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -37770,7 +41474,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 227 /* NamespaceImport */) { childNodes.push(importClause.namedBindings); } else { @@ -37779,21 +41483,21 @@ var ts; } } break; - case 163 /* BindingElement */: - case 211 /* VariableDeclaration */: + case 166 /* BindingElement */: + case 214 /* 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 */: + case 217 /* ClassDeclaration */: + case 220 /* EnumDeclaration */: + case 218 /* InterfaceDeclaration */: + case 221 /* ModuleDeclaration */: + case 216 /* FunctionDeclaration */: + case 224 /* ImportEqualsDeclaration */: + case 229 /* ImportSpecifier */: + case 233 /* ExportSpecifier */: childNodes.push(node); break; } @@ -37838,20 +41542,20 @@ var ts; } function addTopLevelNodes(nodes, topLevelNodes) { nodes = sortNodes(nodes); - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; switch (node.kind) { - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: - case 215 /* InterfaceDeclaration */: + case 217 /* ClassDeclaration */: + case 220 /* EnumDeclaration */: + case 218 /* InterfaceDeclaration */: topLevelNodes.push(node); break; - case 218 /* ModuleDeclaration */: + case 221 /* ModuleDeclaration */: var moduleDeclaration = node; topLevelNodes.push(node); addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes); break; - case 213 /* FunctionDeclaration */: + case 216 /* FunctionDeclaration */: var functionDeclaration = node; if (isTopLevelFunctionDeclaration(functionDeclaration)) { topLevelNodes.push(node); @@ -37862,12 +41566,12 @@ var ts; } } function isTopLevelFunctionDeclaration(functionDeclaration) { - if (functionDeclaration.kind === 213 /* FunctionDeclaration */) { + if (functionDeclaration.kind === 216 /* FunctionDeclaration */) { // A function declaration is 'top level' if it contains any function declarations // within it. - if (functionDeclaration.body && functionDeclaration.body.kind === 192 /* Block */) { + if (functionDeclaration.body && functionDeclaration.body.kind === 195 /* 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); })) { + if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 216 /* FunctionDeclaration */ && !isEmpty(s.name.text); })) { return true; } // Or if it is not parented by another function. i.e all functions @@ -37882,8 +41586,8 @@ var ts; function getItemsWorker(nodes, createItem) { var items = []; var keyToItem = {}; - for (var _i = 0; _i < nodes.length; _i++) { - var child = nodes[_i]; + for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { + var child = nodes_5[_i]; var item = createItem(child); if (item !== undefined) { if (item.text.length > 0) { @@ -37927,44 +41631,44 @@ var ts; } function createChildItem(node) { switch (node.kind) { - case 138 /* Parameter */: + case 139 /* Parameter */: if (ts.isBindingPattern(node.name)) { break; } - if ((node.flags & 2035 /* Modifier */) === 0) { + if ((node.flags & 1022 /* Modifier */) === 0) { return undefined; } return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberFunctionElement); - case 145 /* GetAccessor */: + case 146 /* GetAccessor */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement); - case 146 /* SetAccessor */: + case 147 /* SetAccessor */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); - case 149 /* IndexSignature */: + case 150 /* IndexSignature */: return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); - case 247 /* EnumMember */: + case 250 /* EnumMember */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 147 /* CallSignature */: + case 148 /* CallSignature */: return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); - case 148 /* ConstructSignature */: + case 149 /* ConstructSignature */: return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement); - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 213 /* FunctionDeclaration */: + case 216 /* 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; + case 214 /* VariableDeclaration */: + case 166 /* BindingElement */: + var variableDeclarationNode = void 0; + var name_33; + if (node.kind === 166 /* BindingElement */) { + name_33 = 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 */) { + while (variableDeclarationNode && variableDeclarationNode.kind !== 214 /* VariableDeclaration */) { variableDeclarationNode = variableDeclarationNode.parent; } ts.Debug.assert(variableDeclarationNode !== undefined); @@ -37972,24 +41676,24 @@ var ts; else { ts.Debug.assert(!ts.isBindingPattern(node.name)); variableDeclarationNode = node; - name_30 = node.name; + name_33 = node.name; } if (ts.isConst(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_30), ts.ScriptElementKind.constElement); + return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.constElement); } else if (ts.isLet(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_30), ts.ScriptElementKind.letElement); + return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.letElement); } else { - return createItem(node, getTextOfNode(name_30), ts.ScriptElementKind.variableElement); + return createItem(node, getTextOfNode(name_33), ts.ScriptElementKind.variableElement); } - case 144 /* Constructor */: + case 145 /* Constructor */: return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); - case 230 /* ExportSpecifier */: - case 226 /* ImportSpecifier */: - case 221 /* ImportEqualsDeclaration */: - case 223 /* ImportClause */: - case 224 /* NamespaceImport */: + case 233 /* ExportSpecifier */: + case 229 /* ImportSpecifier */: + case 224 /* ImportEqualsDeclaration */: + case 226 /* ImportClause */: + case 227 /* NamespaceImport */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias); } return undefined; @@ -38019,29 +41723,29 @@ var ts; } function createTopLevelItem(node) { switch (node.kind) { - case 248 /* SourceFile */: + case 251 /* SourceFile */: return createSourceFileItem(node); - case 214 /* ClassDeclaration */: + case 217 /* ClassDeclaration */: return createClassItem(node); - case 217 /* EnumDeclaration */: + case 220 /* EnumDeclaration */: return createEnumItem(node); - case 215 /* InterfaceDeclaration */: + case 218 /* InterfaceDeclaration */: return createIterfaceItem(node); - case 218 /* ModuleDeclaration */: + case 221 /* ModuleDeclaration */: return createModuleItem(node); - case 213 /* FunctionDeclaration */: + case 216 /* FunctionDeclaration */: return createFunctionItem(node); } return undefined; function getModuleName(moduleDeclaration) { // We want to maintain quotation marks. - if (moduleDeclaration.name.kind === 9 /* StringLiteral */) { + if (ts.isAmbientModule(moduleDeclaration)) { 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 */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 221 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(moduleDeclaration.name.text); } @@ -38053,7 +41757,7 @@ var ts; 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 */) { + if (node.body && node.body.kind === 195 /* 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)); } @@ -38074,7 +41778,7 @@ var ts; var childItems; if (node.members) { var constructor = ts.forEach(node.members, function (member) { - return member.kind === 144 /* Constructor */ && member; + return member.kind === 145 /* 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 @@ -38098,7 +41802,7 @@ var ts; } } function removeComputedProperties(node) { - return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 136 /* ComputedPropertyName */; }); + return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 137 /* ComputedPropertyName */; }); } /** * Like removeComputedProperties, but retains the properties with well known symbol names @@ -38107,13 +41811,13 @@ var ts; return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); }); } function getInnermostModule(node) { - while (node.body.kind === 218 /* ModuleDeclaration */) { + while (node.body.kind === 221 /* ModuleDeclaration */) { node = node.body; } return node; } function getNodeSpan(node) { - return node.kind === 248 /* SourceFile */ + return node.kind === 251 /* SourceFile */ ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); } @@ -38145,12 +41849,11 @@ var ts; } 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 + // 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 { @@ -38190,7 +41893,7 @@ var ts; // 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--) { + for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) { var segment = dotSeparatedSegments[i]; var containerName = candidateContainers[j]; var containerMatch = matchSegment(containerName, segment); @@ -38229,14 +41932,14 @@ var ts; 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. + // 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]; + for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { + var span = wordSpans_1[_i]; if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) { return createPatternMatch(PatternMatchKind.substring, punctuationStripped, /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false)); @@ -38269,8 +41972,8 @@ var ts; 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 + // 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) { @@ -38322,7 +42025,7 @@ var ts; // // 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. + // 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 @@ -38336,14 +42039,14 @@ var ts; // 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 + // 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]; + for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) { + var subWordTextChunk = subWordTextChunks_1[_i]; // Try to match the candidate with this word var result = matchTextChunk(candidate, subWordTextChunk, /*punctuationStripped:*/ true); if (!result) { @@ -38386,7 +42089,7 @@ var ts; // 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. + // and I will both match in UI. var currentCandidate = 0; var currentChunkSpan = 0; var firstMatch = undefined; @@ -38415,13 +42118,13 @@ var ts; // 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. + // 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. + // part are both upper case. if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) || !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) { break; @@ -38451,42 +42154,6 @@ var ts; } } 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), @@ -38505,7 +42172,7 @@ var ts; if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 2 /* Latest */)) { return false; } - // TODO: find a way to determine this for any unicode characters in a + // 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(); @@ -38518,19 +42185,11 @@ var ts; if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 2 /* Latest */)) { return false; } - // TODO: find a way to determine this for any unicode characters in a + // 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)) { @@ -38567,7 +42226,7 @@ var ts; if (ch < 127 /* maxAsciiCharacter */) { return ch; } - // TODO: find a way to compute this for any unicode characters in a + // TODO: find a way to compute this for any unicode characters in a // non-allocating manner. return String.fromCharCode(ch).toLowerCase().charCodeAt(0); } @@ -38585,9 +42244,10 @@ var ts; for (var i = 0; i < pattern.length; i++) { var ch = pattern.charCodeAt(i); if (isWordChar(ch)) { - if (wordLength++ === 0) { + if (wordLength === 0) { wordStart = i; } + wordLength++; } else { if (wordLength > 0) { @@ -38718,7 +42378,7 @@ var ts; 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. + // be uppercase and the previous character can't be uppercase. // // For example, breaking "AddMetadata" on words would make: Add Metadata // @@ -38901,14 +42561,14 @@ var ts; if (!candidates.length) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - if (ts.isJavaScript(sourceFile.fileName)) { + if (ts.isSourceFileJavaScript(sourceFile)) { return createJavaScriptSignatureHelpItems(argumentInfo); } return undefined; } return createSignatureHelpItems(candidates, resolvedSignature, argumentInfo); function createJavaScriptSignatureHelpItems(argumentInfo) { - if (argumentInfo.invocation.kind !== 168 /* CallExpression */) { + if (argumentInfo.invocation.kind !== 171 /* CallExpression */) { return undefined; } // See if we can find some symbol with the call expression name that has call signatures. @@ -38916,7 +42576,7 @@ var ts; var expression = callExpression.expression; var name = expression.kind === 69 /* Identifier */ ? expression - : expression.kind === 166 /* PropertyAccessExpression */ + : expression.kind === 169 /* PropertyAccessExpression */ ? expression.name : undefined; if (!name || !name.text) { @@ -38928,8 +42588,8 @@ var ts; var nameToDeclarations = sourceFile_1.getNamedDeclarations(); var declarations = ts.getProperty(nameToDeclarations, name.text); if (declarations) { - for (var _b = 0; _b < declarations.length; _b++) { - var declaration = declarations[_b]; + for (var _b = 0, declarations_7 = declarations; _b < declarations_7.length; _b++) { + var declaration = declarations_7[_b]; var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -38949,7 +42609,7 @@ var ts; * in the argument of an invocation; returns undefined otherwise. */ function getImmediatelyContainingArgumentInfo(node) { - if (node.parent.kind === 168 /* CallExpression */ || node.parent.kind === 169 /* NewExpression */) { + if (node.parent.kind === 171 /* CallExpression */ || node.parent.kind === 172 /* NewExpression */) { var callExpression = node.parent; // There are 3 cases to handle: // 1. The token introduces a list, and should begin a sig help session @@ -39002,25 +42662,25 @@ var ts; }; } } - else if (node.kind === 11 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 170 /* TaggedTemplateExpression */) { + else if (node.kind === 11 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 173 /* 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 */) { + else if (node.kind === 12 /* TemplateHead */ && node.parent.parent.kind === 173 /* TaggedTemplateExpression */) { var templateExpression = node.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 183 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 186 /* 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 */) { + else if (node.parent.kind === 193 /* TemplateSpan */ && node.parent.parent.parent.kind === 173 /* TaggedTemplateExpression */) { var templateSpan = node.parent; var templateExpression = templateSpan.parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 183 /* TemplateExpression */); + ts.Debug.assert(templateExpression.kind === 186 /* 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; @@ -39045,8 +42705,8 @@ var ts; // arg index. var argumentIndex = 0; var listChildren = argumentsList.getChildren(); - for (var _i = 0; _i < listChildren.length; _i++) { - var child = listChildren[_i]; + for (var _i = 0, listChildren_1 = listChildren; _i < listChildren_1.length; _i++) { + var child = listChildren_1[_i]; if (child === node) { break; } @@ -39138,7 +42798,7 @@ var ts; // // 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 */) { + if (template.kind === 186 /* TemplateExpression */) { var lastSpan = ts.lastOrUndefined(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); @@ -39147,7 +42807,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node) { - for (var n = node; n.kind !== 248 /* SourceFile */; n = n.parent) { + for (var n = node; n.kind !== 251 /* SourceFile */; n = n.parent) { if (ts.isFunctionBlock(n)) { return undefined; } @@ -39347,40 +43007,40 @@ var ts; 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 */: + case 217 /* ClassDeclaration */: + case 218 /* InterfaceDeclaration */: + case 220 /* EnumDeclaration */: + case 168 /* ObjectLiteralExpression */: + case 164 /* ObjectBindingPattern */: + case 156 /* TypeLiteral */: + case 195 /* Block */: + case 222 /* ModuleBlock */: + case 223 /* CaseBlock */: return nodeEndsWith(n, 16 /* CloseBraceToken */, sourceFile); - case 244 /* CatchClause */: + case 247 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 169 /* NewExpression */: + case 172 /* NewExpression */: if (!n.arguments) { return true; } // fall through - case 168 /* CallExpression */: - case 172 /* ParenthesizedExpression */: - case 160 /* ParenthesizedType */: + case 171 /* CallExpression */: + case 175 /* ParenthesizedExpression */: + case 161 /* ParenthesizedType */: return nodeEndsWith(n, 18 /* CloseParenToken */, sourceFile); - case 152 /* FunctionType */: - case 153 /* ConstructorType */: + case 153 /* FunctionType */: + case 154 /* 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 */: + case 145 /* Constructor */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 216 /* FunctionDeclaration */: + case 176 /* FunctionExpression */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 149 /* ConstructSignature */: + case 148 /* CallSignature */: + case 177 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -39390,64 +43050,64 @@ var ts; // 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 */: + case 221 /* ModuleDeclaration */: return n.body && isCompletedNode(n.body, sourceFile); - case 196 /* IfStatement */: + case 199 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 195 /* ExpressionStatement */: + case 198 /* 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 */: + case 167 /* ArrayLiteralExpression */: + case 165 /* ArrayBindingPattern */: + case 170 /* ElementAccessExpression */: + case 137 /* ComputedPropertyName */: + case 158 /* TupleType */: return nodeEndsWith(n, 20 /* CloseBracketToken */, sourceFile); - case 149 /* IndexSignature */: + case 150 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 20 /* CloseBracketToken */, sourceFile); - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + case 244 /* CaseClause */: + case 245 /* 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 */: + case 202 /* ForStatement */: + case 203 /* ForInStatement */: + case 204 /* ForOfStatement */: + case 201 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 197 /* DoStatement */: + case 200 /* 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 */: + case 155 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 176 /* TypeOfExpression */: - case 175 /* DeleteExpression */: - case 177 /* VoidExpression */: - case 184 /* YieldExpression */: - case 185 /* SpreadElementExpression */: + case 179 /* TypeOfExpression */: + case 178 /* DeleteExpression */: + case 180 /* VoidExpression */: + case 187 /* YieldExpression */: + case 188 /* SpreadElementExpression */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 170 /* TaggedTemplateExpression */: + case 173 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 183 /* TemplateExpression */: + case 186 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 190 /* TemplateSpan */: + case 193 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 179 /* PrefixUnaryExpression */: + case 182 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 181 /* BinaryExpression */: + case 184 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 182 /* ConditionalExpression */: + case 185 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -39503,7 +43163,7 @@ var ts; // 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) { + if (c.kind === 274 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -39591,8 +43251,8 @@ var ts; return n; } var children = n.getChildren(); - for (var _i = 0; _i < children.length; _i++) { - var child = children[_i]; + for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { + var child = children_1[_i]; var shouldDiveInChildNode = // previous token is enclosed somewhere in the child (child.pos <= previousToken.pos && child.end > previousToken.end) || @@ -39609,7 +43269,7 @@ var ts; function findPrecedingToken(position, sourceFile, startNode) { return find(startNode || sourceFile); function findRightmostToken(n) { - if (isToken(n) || n.kind === 236 /* JsxText */) { + if (isToken(n) || n.kind === 239 /* JsxText */) { return n; } var children = n.getChildren(); @@ -39617,7 +43277,7 @@ var ts; return candidate && findRightmostToken(candidate); } function find(n) { - if (isToken(n) || n.kind === 236 /* JsxText */) { + if (isToken(n) || n.kind === 239 /* JsxText */) { return n; } var children = n.getChildren(); @@ -39631,10 +43291,10 @@ var ts; // 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 */)) { + if (position < child.end && (nodeHasTokens(child) || child.kind === 239 /* JsxText */)) { var start = child.getStart(sourceFile); var lookInPreviousChild = (start >= position) || - (child.kind === 236 /* JsxText */ && start === child.end); // whitespace only JsxText + (child.kind === 239 /* 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); @@ -39646,8 +43306,8 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 248 /* SourceFile */); - // Here we know that none of child token nodes embrace the position, + ts.Debug.assert(startNode !== undefined || n.kind === 251 /* 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' @@ -39668,7 +43328,7 @@ var ts; ts.findPrecedingToken = findPrecedingToken; function isInString(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); - return token && token.kind === 9 /* StringLiteral */ && position > token.getStart(); + return token && (token.kind === 9 /* StringLiteral */ || token.kind === 163 /* StringLiteralType */) && position > token.getStart(); } ts.isInString = isInString; function isInComment(sourceFile, position) { @@ -39754,17 +43414,17 @@ var ts; function getNodeModifiers(node) { var flags = ts.getCombinedNodeFlags(node); var result = []; - if (flags & 32 /* Private */) + if (flags & 16 /* Private */) result.push(ts.ScriptElementKindModifier.privateMemberModifier); - if (flags & 64 /* Protected */) + if (flags & 32 /* Protected */) result.push(ts.ScriptElementKindModifier.protectedMemberModifier); - if (flags & 16 /* Public */) + if (flags & 8 /* Public */) result.push(ts.ScriptElementKindModifier.publicMemberModifier); - if (flags & 128 /* Static */) + if (flags & 64 /* Static */) result.push(ts.ScriptElementKindModifier.staticModifier); - if (flags & 256 /* Abstract */) + if (flags & 128 /* Abstract */) result.push(ts.ScriptElementKindModifier.abstractModifier); - if (flags & 1 /* Export */) + if (flags & 2 /* Export */) result.push(ts.ScriptElementKindModifier.exportedModifier); if (ts.isInAmbientContext(node)) result.push(ts.ScriptElementKindModifier.ambientModifier); @@ -39772,17 +43432,17 @@ var ts; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 151 /* TypeReference */ || node.kind === 168 /* CallExpression */) { + if (node.kind === 152 /* TypeReference */ || node.kind === 171 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 214 /* ClassDeclaration */ || node.kind === 215 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 217 /* ClassDeclaration */ || node.kind === 218 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; } ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 134 /* LastToken */; + return n.kind >= 0 /* FirstToken */ && n.kind <= 135 /* LastToken */; } ts.isToken = isToken; function isWord(kind) { @@ -39798,6 +43458,7 @@ var ts; ts.isComment = isComment; function isStringOrRegularExpressionOrTemplateLiteral(kind) { if (kind === 9 /* StringLiteral */ + || kind === 163 /* StringLiteralType */ || kind === 10 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(kind)) { return true; @@ -39840,13 +43501,40 @@ var ts; return true; } ts.compareDataObjects = compareDataObjects; + function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { + if (node.kind === 167 /* ArrayLiteralExpression */ || + node.kind === 168 /* ObjectLiteralExpression */) { + // [a,b,c] from: + // [a, b, c] = someExpression; + if (node.parent.kind === 184 /* BinaryExpression */ && + node.parent.left === node && + node.parent.operatorToken.kind === 56 /* EqualsToken */) { + return true; + } + // [a, b, c] from: + // for([a, b, c] of expression) + if (node.parent.kind === 204 /* ForOfStatement */ && + node.parent.initializer === node) { + return true; + } + // [a, b, c] of + // [x, [a, b, c] ] = someExpression + // or + // {x, a: {a, b, c} } = someExpression + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 248 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + return true; + } + } + return false; + } + ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; })(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 */; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 139 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); @@ -40034,7 +43722,7 @@ var ts; ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && - (location.parent.kind === 226 /* ImportSpecifier */ || location.parent.kind === 230 /* ExportSpecifier */) && + (location.parent.kind === 229 /* ImportSpecifier */ || location.parent.kind === 233 /* ExportSpecifier */) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -40091,6 +43779,7 @@ var ts; advance: advance, readTokenInfo: readTokenInfo, isOnToken: isOnToken, + getCurrentLeadingTrivia: function () { return leadingTrivia; }, lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, close: function () { ts.Debug.assert(scanner !== undefined); @@ -40156,10 +43845,10 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 238 /* JsxAttribute */: - case 235 /* JsxOpeningElement */: - case 237 /* JsxClosingElement */: - case 234 /* JsxSelfClosingElement */: + case 241 /* JsxAttribute */: + case 238 /* JsxOpeningElement */: + case 240 /* JsxClosingElement */: + case 237 /* JsxSelfClosingElement */: return node.kind === 69 /* Identifier */; } } @@ -40366,7 +44055,7 @@ var ts; return false; }; return FormattingContext; - })(); + }()); formatting.FormattingContext = FormattingContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -40405,7 +44094,7 @@ var ts; "flag=" + this.Flag + "]"; }; return Rule; - })(); + }()); formatting.Rule = Rule; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -40452,7 +44141,7 @@ var ts; return new RuleDescriptor(left, right); }; return RuleDescriptor; - })(); + }()); formatting.RuleDescriptor = RuleDescriptor; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -40494,7 +44183,7 @@ var ts; return result; }; return RuleOperation; - })(); + }()); formatting.RuleOperation = RuleOperation; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -40529,7 +44218,7 @@ var ts; }; RuleOperationContext.Any = new RuleOperationContext(); return RuleOperationContext; - })(); + }()); formatting.RuleOperationContext = RuleOperationContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -40633,6 +44322,7 @@ var ts; // 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.SpaceBeforeArrow = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 34 /* EqualsGreaterThanToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext), 2 /* Space */)); 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 */)); @@ -40658,72 +44348,68 @@ var ts; 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 */)); + this.NoSpaceBetweenTagAndTemplateString = new formatting.Rule(formatting.RuleDescriptor.create3(69 /* Identifier */, formatting.Shared.TokenRange.FromTokens([11 /* NoSubstitutionTemplateLiteral */, 12 /* TemplateHead */])), 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, - ]; + 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.NoSpaceBetweenTagAndTemplateString, + // TypeScript-specific rules + this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport, + this.SpaceAfterCertainTypeScriptKeywords, this.SpaceBeforeCertainTypeScriptKeywords, + this.SpaceAfterModuleName, + this.SpaceBeforeArrow, 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 - ]; + 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.SpaceAfterComma = new formatting.Rule(formatting.RuleDescriptor.create3(24 /* CommaToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsNextTokenNotCloseBracket), 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 */)); @@ -40755,15 +44441,20 @@ var ts; 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 opening and before closing template string braces + 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.SpaceAfterTemplateHeadAndMiddle = 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), 2 /* Space */)); + 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 */)); + this.SpaceBeforeTemplateMiddleAndTail = 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), 2 /* Space */)); // 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; + for (var name_34 in o) { + if (o[name_34] === rule) { + return name_34; } } throw new Error("Unknown rule"); @@ -40772,40 +44463,40 @@ var ts; /// Contexts /// Rules.IsForContext = function (context) { - return context.contextNode.kind === 199 /* ForStatement */; + return context.contextNode.kind === 202 /* 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 */: + case 184 /* BinaryExpression */: + case 185 /* ConditionalExpression */: + case 192 /* AsExpression */: + case 151 /* TypePredicate */: + case 159 /* UnionType */: + case 160 /* IntersectionType */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 163 /* BindingElement */: + case 166 /* BindingElement */: // equals in type X = ... - case 216 /* TypeAliasDeclaration */: + case 219 /* TypeAliasDeclaration */: // equal in import a = module('a'); - case 221 /* ImportEqualsDeclaration */: + case 224 /* ImportEqualsDeclaration */: // equal in let a = 0; - case 211 /* VariableDeclaration */: + case 214 /* VariableDeclaration */: // equal in p = 0; - case 138 /* Parameter */: - case 247 /* EnumMember */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 139 /* Parameter */: + case 250 /* EnumMember */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: return context.currentTokenSpan.kind === 56 /* EqualsToken */ || context.nextTokenSpan.kind === 56 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 200 /* ForInStatement */: + case 203 /* 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 */; + case 204 /* ForOfStatement */: + return context.currentTokenSpan.kind === 135 /* OfKeyword */ || context.nextTokenSpan.kind === 135 /* OfKeyword */; } return false; }; @@ -40813,7 +44504,7 @@ var ts; return !Rules.IsBinaryOpContext(context); }; Rules.IsConditionalOperatorContext = function (context) { - return context.contextNode.kind === 182 /* ConditionalExpression */; + return context.contextNode.kind === 185 /* ConditionalExpression */; }; Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { //// This check is mainly used inside SpaceBeforeOpenBraceInControl and SpaceBeforeOpenBraceInFunction. @@ -40857,93 +44548,93 @@ var ts; return true; } switch (node.kind) { - case 192 /* Block */: - case 220 /* CaseBlock */: - case 165 /* ObjectLiteralExpression */: - case 219 /* ModuleBlock */: + case 195 /* Block */: + case 223 /* CaseBlock */: + case 168 /* ObjectLiteralExpression */: + case 222 /* ModuleBlock */: return true; } return false; }; Rules.IsFunctionDeclContext = function (context) { switch (context.contextNode.kind) { - case 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 216 /* FunctionDeclaration */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: //case SyntaxKind.MemberFunctionDeclaration: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: ///case SyntaxKind.MethodSignature: - case 147 /* CallSignature */: - case 173 /* FunctionExpression */: - case 144 /* Constructor */: - case 174 /* ArrowFunction */: + case 148 /* CallSignature */: + case 176 /* FunctionExpression */: + case 145 /* Constructor */: + case 177 /* ArrowFunction */: //case SyntaxKind.ConstructorDeclaration: //case SyntaxKind.SimpleArrowFunctionExpression: //case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 215 /* InterfaceDeclaration */: + case 218 /* InterfaceDeclaration */: return true; } return false; }; Rules.IsFunctionDeclarationOrFunctionExpressionContext = function (context) { - return context.contextNode.kind === 213 /* FunctionDeclaration */ || context.contextNode.kind === 173 /* FunctionExpression */; + return context.contextNode.kind === 216 /* FunctionDeclaration */ || context.contextNode.kind === 176 /* 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 */: + case 217 /* ClassDeclaration */: + case 189 /* ClassExpression */: + case 218 /* InterfaceDeclaration */: + case 220 /* EnumDeclaration */: + case 156 /* TypeLiteral */: + case 221 /* 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 */: + case 217 /* ClassDeclaration */: + case 221 /* ModuleDeclaration */: + case 220 /* EnumDeclaration */: + case 195 /* Block */: + case 247 /* CatchClause */: + case 222 /* ModuleBlock */: + case 209 /* 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 */: + case 199 /* IfStatement */: + case 209 /* SwitchStatement */: + case 202 /* ForStatement */: + case 203 /* ForInStatement */: + case 204 /* ForOfStatement */: + case 201 /* WhileStatement */: + case 212 /* TryStatement */: + case 200 /* DoStatement */: + case 208 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: - case 244 /* CatchClause */: + case 247 /* CatchClause */: return true; default: return false; } }; Rules.IsObjectContext = function (context) { - return context.contextNode.kind === 165 /* ObjectLiteralExpression */; + return context.contextNode.kind === 168 /* ObjectLiteralExpression */; }; Rules.IsFunctionCallContext = function (context) { - return context.contextNode.kind === 168 /* CallExpression */; + return context.contextNode.kind === 171 /* CallExpression */; }; Rules.IsNewContext = function (context) { - return context.contextNode.kind === 169 /* NewExpression */; + return context.contextNode.kind === 172 /* NewExpression */; }; Rules.IsFunctionCallOrNewContext = function (context) { return Rules.IsFunctionCallContext(context) || Rules.IsNewContext(context); @@ -40951,8 +44642,11 @@ var ts; Rules.IsPreviousTokenNotComma = function (context) { return context.currentTokenSpan.kind !== 24 /* CommaToken */; }; + Rules.IsNextTokenNotCloseBracket = function (context) { + return context.nextTokenSpan.kind !== 20 /* CloseBracketToken */; + }; Rules.IsArrowFunctionContext = function (context) { - return context.contextNode.kind === 174 /* ArrowFunction */; + return context.contextNode.kind === 177 /* ArrowFunction */; }; Rules.IsSameLineTokenContext = function (context) { return context.TokensAreOnSameLine(); @@ -40970,41 +44664,41 @@ var ts; while (ts.isExpression(node)) { node = node.parent; } - return node.kind === 139 /* Decorator */; + return node.kind === 140 /* Decorator */; }; Rules.IsStartOfVariableDeclarationList = function (context) { - return context.currentTokenParent.kind === 212 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 215 /* 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 */; + return context.contextNode.kind === 221 /* ModuleDeclaration */; }; Rules.IsObjectTypeContext = function (context) { - return context.contextNode.kind === 155 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + return context.contextNode.kind === 156 /* 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 */: + case 152 /* TypeReference */: + case 174 /* TypeAssertionExpression */: + case 217 /* ClassDeclaration */: + case 189 /* ClassExpression */: + case 218 /* InterfaceDeclaration */: + case 216 /* FunctionDeclaration */: + case 176 /* FunctionExpression */: + case 177 /* ArrowFunction */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 148 /* CallSignature */: + case 149 /* ConstructSignature */: + case 171 /* CallExpression */: + case 172 /* NewExpression */: + case 191 /* ExpressionWithTypeArguments */: return true; default: return false; @@ -41015,16 +44709,16 @@ var ts; Rules.IsTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); }; Rules.IsTypeAssertionContext = function (context) { - return context.contextNode.kind === 171 /* TypeAssertionExpression */; + return context.contextNode.kind === 174 /* TypeAssertionExpression */; }; Rules.IsVoidOpContext = function (context) { - return context.currentTokenSpan.kind === 103 /* VoidKeyword */ && context.currentTokenParent.kind === 177 /* VoidExpression */; + return context.currentTokenSpan.kind === 103 /* VoidKeyword */ && context.currentTokenParent.kind === 180 /* VoidExpression */; }; Rules.IsYieldOrYieldStarWithOperand = function (context) { - return context.contextNode.kind === 184 /* YieldExpression */ && context.contextNode.expression !== undefined; + return context.contextNode.kind === 187 /* YieldExpression */ && context.contextNode.expression !== undefined; }; return Rules; - })(); + }()); formatting.Rules = Rules; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41045,7 +44739,7 @@ var ts; return result; }; RulesMap.prototype.Initialize = function (rules) { - this.mapRowLength = 134 /* LastToken */ + 1; + this.mapRowLength = 135 /* 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); @@ -41092,7 +44786,7 @@ var ts; return null; }; return RulesMap; - })(); + }()); formatting.RulesMap = RulesMap; var MaskBitSize = 5; var Mask = 0x1f; @@ -41144,7 +44838,7 @@ var ts; this.rulesInsertionIndexBitmap = temp; }; return RulesBucketConstructionState; - })(); + }()); formatting.RulesBucketConstructionState = RulesBucketConstructionState; var RulesBucket = (function () { function RulesBucket() { @@ -41179,7 +44873,7 @@ var ts; state.IncreaseInsertionIndex(position); }; return RulesBucket; - })(); + }()); formatting.RulesBucket = RulesBucket; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41195,7 +44889,7 @@ var ts; function TokenRangeAccess(from, to, except) { this.tokens = []; for (var token = from; token <= to; token++) { - if (except.indexOf(token) < 0) { + if (ts.indexOf(except, token) < 0) { this.tokens.push(token); } } @@ -41207,7 +44901,7 @@ var ts; return this.tokens.indexOf(token) >= 0; }; return TokenRangeAccess; - })(); + }()); Shared.TokenRangeAccess = TokenRangeAccess; var TokenValuesAccess = (function () { function TokenValuesAccess(tks) { @@ -41220,7 +44914,7 @@ var ts; return this.tokens.indexOf(token) >= 0; }; return TokenValuesAccess; - })(); + }()); Shared.TokenValuesAccess = TokenValuesAccess; var TokenSingleValueAccess = (function () { function TokenSingleValueAccess(token) { @@ -41233,14 +44927,14 @@ var ts; 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++) { + for (var token = 0 /* FirstToken */; token <= 135 /* LastToken */; token++) { result.push(token); } return result; @@ -41252,7 +44946,7 @@ var ts; return "[allTokens]"; }; return TokenAllAccess; - })(); + }()); Shared.TokenAllAccess = TokenAllAccess; var TokenRange = (function () { function TokenRange(tokenAccess) { @@ -41282,9 +44976,9 @@ var ts; }; TokenRange.Any = TokenRange.AllTokens(); TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */])); - TokenRange.Keywords = TokenRange.FromRange(70 /* FirstKeyword */, 134 /* LastKeyword */); + TokenRange.Keywords = TokenRange.FromRange(70 /* FirstKeyword */, 135 /* LastKeyword */); TokenRange.BinaryOperators = TokenRange.FromRange(25 /* FirstBinaryOperator */, 68 /* LastBinaryOperator */); - TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90 /* InKeyword */, 91 /* InstanceOfKeyword */, 134 /* OfKeyword */, 116 /* AsKeyword */, 124 /* IsKeyword */]); + TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([90 /* InKeyword */, 91 /* InstanceOfKeyword */, 135 /* 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 */]); @@ -41294,7 +44988,7 @@ var ts; 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 = {})); @@ -41380,6 +45074,14 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); } + if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { + rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); + rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); + } + else { + rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); + rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); + } if (options.InsertSpaceAfterSemicolonInForStatements) { rules.push(this.globalRules.SpaceAfterSemicolonInFor); } @@ -41405,7 +45107,7 @@ var ts; return rules; }; return RulesProvider; - })(); + }()); formatting.RulesProvider = RulesProvider; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -41506,17 +45208,17 @@ var ts; // 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 */: + case 217 /* ClassDeclaration */: + case 218 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 218 /* ModuleDeclaration */: + case 221 /* 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 body && body.kind === 195 /* Block */ && ts.rangeContainsRange(body.statements, node); + case 251 /* SourceFile */: + case 195 /* Block */: + case 222 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 244 /* CatchClause */: + case 247 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -41614,17 +45316,17 @@ var ts; */ function getOwnOrInheritedDelta(n, options, sourceFile) { var previousLine = -1 /* Unknown */; - var childKind = 0 /* Unknown */; + var child; while (n) { var line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line; if (previousLine !== -1 /* Unknown */ && line !== previousLine) { break; } - if (formatting.SmartIndenter.shouldIndentChildNode(n.kind, childKind)) { + if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { return options.IndentSize; } previousLine = line; - childKind = n.kind; + child = n; n = n.parent; } return 0; @@ -41654,6 +45356,13 @@ var ts; var delta = getOwnOrInheritedDelta(enclosingNode, options, sourceFile); processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta); } + if (!formattingScanner.isOnToken()) { + var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); + if (leadingTrivia) { + processTrivia(leadingTrivia, enclosingNode, enclosingNode, undefined); + trimTrailingWhitespacesForRemainingRange(); + } + } formattingScanner.close(); return edits; // local functions @@ -41665,7 +45374,8 @@ var ts; * to inherited indentation from its predecessors. */ function tryComputeIndentationForListItem(startPos, endPos, parentStartLine, range, inheritedIndentation) { - if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos)) { + if (ts.rangeOverlapsWithStartEnd(range, startPos, endPos) || + ts.rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) { if (inheritedIndentation !== -1 /* Unknown */) { return inheritedIndentation; } @@ -41682,32 +45392,7 @@ var ts; } 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; + var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent @@ -41715,7 +45400,15 @@ var ts; indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta() + delta); + delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta); + } + else if (indentation === -1 /* Unknown */) { + if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + indentation = parentDynamicIndentation.getIndentation(); + } + else { + indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node); + } } return { indentation: indentation, @@ -41727,25 +45420,25 @@ var ts; 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 */: + case 217 /* ClassDeclaration */: return 73 /* ClassKeyword */; + case 218 /* InterfaceDeclaration */: return 107 /* InterfaceKeyword */; + case 216 /* FunctionDeclaration */: return 87 /* FunctionKeyword */; + case 220 /* EnumDeclaration */: return 220 /* EnumDeclaration */; + case 146 /* GetAccessor */: return 123 /* GetKeyword */; + case 147 /* SetAccessor */: return 129 /* SetKeyword */; + case 144 /* MethodDeclaration */: if (node.asteriskToken) { return 37 /* AsteriskToken */; } // fall-through - case 141 /* PropertyDeclaration */: - case 138 /* Parameter */: + case 142 /* PropertyDeclaration */: + case 139 /* Parameter */: return node.name.kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { return { - getIndentationForComment: function (kind, tokenIndentation) { + getIndentationForComment: function (kind, tokenIndentation, container) { switch (kind) { // preceding comment to the token that closes the indentation scope inherits the indentation from the scope // .. { @@ -41754,11 +45447,11 @@ var ts; case 16 /* CloseBraceToken */: case 20 /* CloseBracketToken */: case 18 /* CloseParenToken */: - return indentation + delta; + return indentation + getEffectiveDelta(delta, container); } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; }, - getIndentationForToken: function (line, kind) { + getIndentationForToken: function (line, kind, container) { 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 @@ -41779,20 +45472,20 @@ var ts; 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; + return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; } }, getIndentation: function () { return indentation; }, - getDelta: function () { return delta; }, + getDelta: function (child) { return getEffectiveDelta(delta, child); }, recomputeIndentation: function (lineAdded) { - if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent.kind, node.kind)) { + if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { if (lineAdded) { indentation += options.IndentSize; } else { indentation -= options.IndentSize; } - if (formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0 /* Unknown */)) { + if (formatting.SmartIndenter.shouldIndentChildNode(node)) { delta = options.IndentSize; } else { @@ -41801,6 +45494,10 @@ var ts; } } }; + function getEffectiveDelta(delta, child) { + // Delta value should be zero when the node explicitly prevents indentation of the child node + return formatting.SmartIndenter.nodeWillIndentChild(node, child, true) ? delta : 0; + } } function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) { if (!ts.rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) { @@ -41872,10 +45569,10 @@ var ts; // 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); + consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 139 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 140 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); childContextNode = node; @@ -41908,8 +45605,8 @@ var ts; } } var inheritedIndentation = -1 /* Unknown */; - for (var _i = 0; _i < nodes.length; _i++) { - var child = nodes[_i]; + for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { + var child = nodes_6[_i]; inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListElement*/ true); } if (listEndToken !== 0 /* Unknown */) { @@ -41926,7 +45623,7 @@ var ts; } } } - function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation) { + function consumeTokenAndAdvanceScanner(currentTokenInfo, parent, dynamicIndentation, container) { ts.Debug.assert(ts.rangeContainsRange(parent, currentTokenInfo.token)); var lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine(); var indentToken = false; @@ -41938,8 +45635,8 @@ var ts; 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; + // save previousRange since processRange will overwrite this value with current one + var savePreviousRange = previousRange; lineAdded = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation); if (rangeHasError) { // do not indent comments\token if token range overlaps with some error @@ -41950,7 +45647,9 @@ var ts; indentToken = lineAdded; } else { - indentToken = lastTriviaWasNewLine && tokenStart.line !== prevStartLine; + // indent token only if end line of previous range does not match start line of the token + var prevEndLine = savePreviousRange && sourceFile.getLineAndCharacterOfPosition(savePreviousRange.end).line; + indentToken = lastTriviaWasNewLine && tokenStart.line !== prevEndLine; } } } @@ -41959,10 +45658,10 @@ var ts; } if (indentToken) { var tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ? - dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind) : + dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container) : -1 /* Unknown */; if (currentTokenInfo.leadingTrivia) { - var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation); + var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); var indentNextTokenOrTrivia = true; for (var _i = 0, _a = currentTokenInfo.leadingTrivia; _i < _a.length; _i++) { var triviaItem = _a[_i]; @@ -41998,8 +45697,8 @@ var ts; } } function processTrivia(trivia, parent, contextNode, dynamicIndentation) { - for (var _i = 0; _i < trivia.length; _i++) { - var triviaItem = trivia[_i]; + for (var _i = 0, trivia_1 = trivia; _i < trivia_1.length; _i++) { + var triviaItem = trivia_1[_i]; if (ts.isComment(triviaItem.kind) && ts.rangeContainsRange(originalRange, triviaItem)) { var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos); processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation); @@ -42051,9 +45750,7 @@ var ts; } } // 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 */; + trimTrailingWhitespaces = !(rule.Operation.Action & 8 /* Delete */) && rule.Flag !== 1 /* CanDeleteNewLines */; } else { trimTrailingWhitespaces = true; @@ -42136,16 +45833,36 @@ var ts; 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); + var whitespaceStart = getTrailingWhitespaceStartPosition(lineStartPosition, lineEndPosition); + if (whitespaceStart !== -1) { + ts.Debug.assert(whitespaceStart === lineStartPosition || !ts.isWhiteSpace(sourceFile.text.charCodeAt(whitespaceStart - 1))); + recordDelete(whitespaceStart, lineEndPosition + 1 - whitespaceStart); } } } + /** + * @param start The position of the first character in range + * @param end The position of the last character in range + */ + function getTrailingWhitespaceStartPosition(start, end) { + var pos = end; + while (pos >= start && ts.isWhiteSpace(sourceFile.text.charCodeAt(pos))) { + pos--; + } + if (pos !== end) { + return pos + 1; + } + return -1; + } + /** + * Trimming will be done for lines after the previous range + */ + function trimTrailingWhitespacesForRemainingRange() { + var startPosition = previousRange ? previousRange.end : originalRange.pos; + var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; + trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); + } function newTextChange(start, len, newText) { return { span: ts.createTextSpan(start, len), newText: newText }; } @@ -42199,20 +45916,20 @@ var ts; } function isSomeBlock(kind) { switch (kind) { - case 192 /* Block */: - case 219 /* ModuleBlock */: + case 195 /* Block */: + case 222 /* 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 */: + case 145 /* Constructor */: + case 216 /* FunctionDeclaration */: + case 176 /* FunctionExpression */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 177 /* ArrowFunction */: if (node.typeParameters === list) { return 25 /* LessThanToken */; } @@ -42220,8 +45937,8 @@ var ts; return 17 /* OpenParenToken */; } break; - case 168 /* CallExpression */: - case 169 /* NewExpression */: + case 171 /* CallExpression */: + case 172 /* NewExpression */: if (node.typeArguments === list) { return 25 /* LessThanToken */; } @@ -42229,7 +45946,7 @@ var ts; return 17 /* OpenParenToken */; } break; - case 151 /* TypeReference */: + case 152 /* TypeReference */: if (node.typeArguments === list) { return 25 /* LessThanToken */; } @@ -42258,7 +45975,7 @@ var ts; if (!options.ConvertTabsToSpaces) { var tabs = Math.floor(indentation / options.TabSize); var spaces = indentation - tabs * options.TabSize; - var tabString; + var tabString = void 0; if (!internedTabsIndentation) { internedTabsIndentation = []; } @@ -42271,7 +45988,7 @@ var ts; return spaces ? tabString + repeat(" ", spaces) : tabString; } else { - var spacesString; + var spacesString = void 0; var quotient = Math.floor(indentation / options.IndentSize); var remainder = indentation % options.IndentSize; if (!internedSpacesIndentation) { @@ -42345,7 +46062,7 @@ var ts; 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 */) { + if (precedingToken.kind === 24 /* CommaToken */ && precedingToken.parent.kind !== 184 /* 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 */) { @@ -42359,7 +46076,7 @@ var ts; var currentStart; var indentationDelta; while (current) { - if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current.kind, previous ? previous.kind : 0 /* Unknown */)) { + if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous)) { currentStart = getStartLineAndCharacterForNode(current, sourceFile); if (nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile)) { indentationDelta = 0; @@ -42426,7 +46143,7 @@ var ts; } } // 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) { + if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { indentationDelta += options.IndentSize; } current = parent; @@ -42464,7 +46181,7 @@ var ts; // - 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); + (parent.kind === 251 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -42497,7 +46214,7 @@ var ts; return sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); } function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 196 /* IfStatement */ && parent.elseStatement === child) { + if (parent.kind === 199 /* IfStatement */ && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 80 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -42509,23 +46226,23 @@ var ts; function getContainingList(node, sourceFile) { if (node.parent) { switch (node.parent.kind) { - case 151 /* TypeReference */: + case 152 /* TypeReference */: if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd())) { return node.parent.typeArguments; } break; - case 165 /* ObjectLiteralExpression */: + case 168 /* ObjectLiteralExpression */: return node.parent.properties; - case 164 /* ArrayLiteralExpression */: + case 167 /* 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 */: { + case 216 /* FunctionDeclaration */: + case 176 /* FunctionExpression */: + case 177 /* ArrowFunction */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 148 /* CallSignature */: + case 149 /* ConstructSignature */: { var start = node.getStart(sourceFile); if (node.parent.typeParameters && ts.rangeContainsStartEnd(node.parent.typeParameters, start, node.getEnd())) { @@ -42536,8 +46253,8 @@ var ts; } break; } - case 169 /* NewExpression */: - case 168 /* CallExpression */: { + case 172 /* NewExpression */: + case 171 /* CallExpression */: { var start = node.getStart(sourceFile); if (node.parent.typeArguments && ts.rangeContainsStartEnd(node.parent.typeArguments, start, node.getEnd())) { @@ -42567,8 +46284,8 @@ var ts; if (node.kind === 18 /* CloseParenToken */) { return -1 /* Unknown */; } - if (node.parent && (node.parent.kind === 168 /* CallExpression */ || - node.parent.kind === 169 /* NewExpression */) && + if (node.parent && (node.parent.kind === 171 /* CallExpression */ || + node.parent.kind === 172 /* NewExpression */) && node.parent.expression !== node) { var fullCallOrNewExpression = node.parent.expression; var startingExpression = getStartingExpression(fullCallOrNewExpression); @@ -42586,17 +46303,16 @@ var ts; function getStartingExpression(node) { while (true) { switch (node.kind) { - case 168 /* CallExpression */: - case 169 /* NewExpression */: - case 166 /* PropertyAccessExpression */: - case 167 /* ElementAccessExpression */: + case 171 /* CallExpression */: + case 172 /* NewExpression */: + case 169 /* PropertyAccessExpression */: + case 170 /* ElementAccessExpression */: node = node.expression; break; default: return node; } } - return node; } } function deriveActualIndentationFromList(list, index, sourceFile, options) { @@ -42654,80 +46370,85 @@ var ts; 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 */: + case 198 /* ExpressionStatement */: + case 217 /* ClassDeclaration */: + case 189 /* ClassExpression */: + case 218 /* InterfaceDeclaration */: + case 220 /* EnumDeclaration */: + case 219 /* TypeAliasDeclaration */: + case 167 /* ArrayLiteralExpression */: + case 195 /* Block */: + case 222 /* ModuleBlock */: + case 168 /* ObjectLiteralExpression */: + case 156 /* TypeLiteral */: + case 158 /* TupleType */: + case 223 /* CaseBlock */: + case 245 /* DefaultClause */: + case 244 /* CaseClause */: + case 175 /* ParenthesizedExpression */: + case 169 /* PropertyAccessExpression */: + case 171 /* CallExpression */: + case 172 /* NewExpression */: + case 196 /* VariableStatement */: + case 214 /* VariableDeclaration */: + case 230 /* ExportAssignment */: + case 207 /* ReturnStatement */: + case 185 /* ConditionalExpression */: + case 165 /* ArrayBindingPattern */: + case 164 /* ObjectBindingPattern */: + case 238 /* JsxOpeningElement */: + case 237 /* JsxSelfClosingElement */: + case 243 /* JsxExpression */: + case 143 /* MethodSignature */: + case 148 /* CallSignature */: + case 149 /* ConstructSignature */: + case 139 /* Parameter */: + case 153 /* FunctionType */: + case 154 /* ConstructorType */: + case 161 /* ParenthesizedType */: + case 173 /* TaggedTemplateExpression */: + case 181 /* AwaitExpression */: + case 228 /* NamedImports */: return true; } return false; } + /* @internal */ + function nodeWillIndentChild(parent, child, indentByDefault) { + var childKind = child ? child.kind : 0 /* Unknown */; + switch (parent.kind) { + case 200 /* DoStatement */: + case 201 /* WhileStatement */: + case 203 /* ForInStatement */: + case 204 /* ForOfStatement */: + case 202 /* ForStatement */: + case 199 /* IfStatement */: + case 216 /* FunctionDeclaration */: + case 176 /* FunctionExpression */: + case 144 /* MethodDeclaration */: + case 177 /* ArrowFunction */: + case 145 /* Constructor */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + return childKind !== 195 /* Block */; + case 236 /* JsxElement */: + return childKind !== 240 /* JsxClosingElement */; + } + // No explicit rule for given nodes so the result will follow the default value argument + return indentByDefault; + } + SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; + /* + Function returns true when the parent node should indent the given child by an explicit rule + */ 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; - } + return nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, 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 __()); -}; /// /// /// @@ -42759,7 +46480,7 @@ var ts; return undefined; }; return StringScriptSnapshot; - })(); + }()); function fromString(text) { return new StringScriptSnapshot(text); } @@ -42807,15 +46528,18 @@ var ts; ]; var jsDocCompletionEntries; function createNode(kind, pos, end, flags, parent) { - var node = new (ts.getNodeConstructor(kind))(); - node.pos = pos; - node.end = end; + var node = new NodeObject(kind, pos, end); node.flags = flags; node.parent = parent; return node; } var NodeObject = (function () { - function NodeObject() { + function NodeObject(kind, pos, end) { + this.kind = kind; + this.pos = pos; + this.end = end; + this.flags = 0 /* None */; + this.parent = undefined; } NodeObject.prototype.getSourceFile = function () { return ts.getSourceFileOfNode(this); @@ -42849,17 +46573,17 @@ var ts; while (pos < end) { var token = scanner.scan(); var textPos = scanner.getTextPos(); - nodes.push(createNode(token, pos, textPos, 4096 /* Synthetic */, this)); + nodes.push(createNode(token, pos, textPos, 2048 /* Synthetic */, this)); pos = textPos; } return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(271 /* SyntaxList */, nodes.pos, nodes.end, 4096 /* Synthetic */, this); + var list = createNode(274 /* SyntaxList */, nodes.pos, nodes.end, 2048 /* Synthetic */, this); list._children = []; var pos = nodes.pos; - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { + var node = nodes_7[_i]; if (pos < node.pos) { pos = this.addSyntheticNodes(list._children, pos, node.pos); } @@ -42874,27 +46598,27 @@ var ts; NodeObject.prototype.createChildren = function (sourceFile) { var _this = this; var children; - if (this.kind >= 135 /* FirstNode */) { + if (this.kind >= 136 /* FirstNode */) { scanner.setText((sourceFile || this.getSourceFile()).text); children = []; - var pos = this.pos; + var pos_3 = this.pos; var processNode = function (node) { - if (pos < node.pos) { - pos = _this.addSyntheticNodes(children, pos, node.pos); + if (pos_3 < node.pos) { + pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos); } children.push(node); - pos = node.end; + pos_3 = node.end; }; var processNodes = function (nodes) { - if (pos < nodes.pos) { - pos = _this.addSyntheticNodes(children, pos, nodes.pos); + if (pos_3 < nodes.pos) { + pos_3 = _this.addSyntheticNodes(children, pos_3, nodes.pos); } children.push(_this.createSyntaxList(nodes)); - pos = nodes.end; + pos_3 = nodes.end; }; ts.forEachChild(this, processNode, processNodes); - if (pos < this.end) { - this.addSyntheticNodes(children, pos, this.end); + if (pos_3 < this.end) { + this.addSyntheticNodes(children, pos_3, this.end); } scanner.setText(undefined); } @@ -42921,7 +46645,7 @@ var ts; return undefined; } var child = children[0]; - return child.kind < 135 /* FirstNode */ ? child : child.getFirstToken(sourceFile); + return child.kind < 136 /* FirstNode */ ? child : child.getFirstToken(sourceFile); }; NodeObject.prototype.getLastToken = function (sourceFile) { var children = this.getChildren(sourceFile); @@ -42929,10 +46653,10 @@ var ts; if (!child) { return undefined; } - return child.kind < 135 /* FirstNode */ ? child : child.getLastToken(sourceFile); + return child.kind < 136 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; return NodeObject; - })(); + }()); var SymbolObject = (function () { function SymbolObject(flags, name) { this.flags = flags; @@ -42954,7 +46678,7 @@ var ts; return this.documentationComment; }; return SymbolObject; - })(); + }()); function getJsDocCommentsFromDeclarations(declarations, name, canUseParsedParamTagComments) { var documentationComment = []; var docComments = getJsDocCommentsSeparatedByNewLines(); @@ -42972,31 +46696,31 @@ var ts; // 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 + // Eg. const 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); + var sourceFileOfDeclaration_1 = 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 (canUseParsedParamTagComments && declaration.kind === 139 /* Parameter */) { + ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration_1), function (jsDocCommentTextRange) { + var cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration_1); 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 */) { + if (declaration.kind === 221 /* ModuleDeclaration */ && declaration.body.kind === 221 /* 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 */) { + while (declaration.kind === 221 /* ModuleDeclaration */ && declaration.parent.kind === 221 /* 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); + ts.forEach(getJsDocCommentTextRange(declaration.kind === 214 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration_1), function (jsDocCommentTextRange) { + var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration_1); if (cleanedJsDocComment) { ts.addRange(jsDocCommentParts, cleanedJsDocComment); } @@ -43043,7 +46767,8 @@ var ts; } function pushDocCommentLineText(docComments, text, blankLineCount) { // Add the empty lines in between texts - while (blankLineCount--) { + while (blankLineCount) { + blankLineCount--; docComments.push(ts.textPart("")); } docComments.push(ts.textPart(text)); @@ -43269,7 +46994,7 @@ var ts; : undefined; }; return TypeObject; - })(); + }()); var SignatureObject = (function () { function SignatureObject(checker) { this.checker = checker; @@ -43295,11 +47020,11 @@ var ts; return this.documentationComment; }; return SignatureObject; - })(); + }()); var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); - function SourceFileObject() { - _super.apply(this, arguments); + function SourceFileObject(kind, pos, end) { + _super.call(this, kind, pos, end); } SourceFileObject.prototype.update = function (newText, textChangeRange) { return ts.updateSourceFile(this, newText, textChangeRange); @@ -43335,13 +47060,13 @@ var ts; } function getDeclarationName(declaration) { if (declaration.name) { - var result_2 = getTextOfIdentifierOrLiteral(declaration.name); - if (result_2 !== undefined) { - return result_2; + var result_3 = getTextOfIdentifierOrLiteral(declaration.name); + if (result_3 !== undefined) { + return result_3; } - if (declaration.name.kind === 136 /* ComputedPropertyName */) { + if (declaration.name.kind === 137 /* ComputedPropertyName */) { var expr = declaration.name.expression; - if (expr.kind === 166 /* PropertyAccessExpression */) { + if (expr.kind === 169 /* PropertyAccessExpression */) { return expr.name.text; } return getTextOfIdentifierOrLiteral(expr); @@ -43361,9 +47086,9 @@ var ts; } function visit(node) { switch (node.kind) { - case 213 /* FunctionDeclaration */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 216 /* FunctionDeclaration */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -43383,60 +47108,60 @@ var ts; 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 */: + case 217 /* ClassDeclaration */: + case 218 /* InterfaceDeclaration */: + case 219 /* TypeAliasDeclaration */: + case 220 /* EnumDeclaration */: + case 221 /* ModuleDeclaration */: + case 224 /* ImportEqualsDeclaration */: + case 233 /* ExportSpecifier */: + case 229 /* ImportSpecifier */: + case 224 /* ImportEqualsDeclaration */: + case 226 /* ImportClause */: + case 227 /* NamespaceImport */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 156 /* TypeLiteral */: addDeclaration(node); // fall through - case 144 /* Constructor */: - case 193 /* VariableStatement */: - case 212 /* VariableDeclarationList */: - case 161 /* ObjectBindingPattern */: - case 162 /* ArrayBindingPattern */: - case 219 /* ModuleBlock */: + case 145 /* Constructor */: + case 196 /* VariableStatement */: + case 215 /* VariableDeclarationList */: + case 164 /* ObjectBindingPattern */: + case 165 /* ArrayBindingPattern */: + case 222 /* ModuleBlock */: ts.forEachChild(node, visit); break; - case 192 /* Block */: + case 195 /* Block */: if (ts.isFunctionBlock(node)) { ts.forEachChild(node, visit); } break; - case 138 /* Parameter */: + case 139 /* Parameter */: // Only consider properties defined as constructor parameters - if (!(node.flags & 112 /* AccessibilityModifier */)) { + if (!(node.flags & 56 /* AccessibilityModifier */)) { break; } // fall through - case 211 /* VariableDeclaration */: - case 163 /* BindingElement */: + case 214 /* VariableDeclaration */: + case 166 /* BindingElement */: if (ts.isBindingPattern(node.name)) { ts.forEachChild(node.name, visit); break; } - case 247 /* EnumMember */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 250 /* EnumMember */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: addDeclaration(node); break; - case 228 /* ExportDeclaration */: + case 231 /* 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 */: + case 225 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: @@ -43448,7 +47173,7 @@ var ts; // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 224 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 227 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -43461,12 +47186,12 @@ var ts; } }; return SourceFileObject; - })(NodeObject); + }(NodeObject)); var TextChange = (function () { function TextChange() { } return TextChange; - })(); + }()); ts.TextChange = TextChange; var HighlightSpanKind; (function (HighlightSpanKind) { @@ -43556,7 +47281,7 @@ var ts; // enum E ScriptElementKind.enumElement = "enum"; // Inside module and script only - // let v = .. + // const v = .. ScriptElementKind.variableElement = "var"; // Inside function ScriptElementKind.localVariableElement = "local var"; @@ -43621,8 +47346,14 @@ var ts; ClassificationTypeNames.typeAliasName = "type alias name"; ClassificationTypeNames.parameterName = "parameter name"; ClassificationTypeNames.docCommentTagName = "doc comment tag name"; + ClassificationTypeNames.jsxOpenTagName = "jsx open tag name"; + ClassificationTypeNames.jsxCloseTagName = "jsx close tag name"; + ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name"; + ClassificationTypeNames.jsxAttribute = "jsx attribute"; + ClassificationTypeNames.jsxText = "jsx text"; + ClassificationTypeNames.jsxAttributeStringLiteralValue = "jsx attribute string literal value"; return ClassificationTypeNames; - })(); + }()); ts.ClassificationTypeNames = ClassificationTypeNames; (function (ClassificationType) { ClassificationType[ClassificationType["comment"] = 1] = "comment"; @@ -43643,6 +47374,12 @@ var ts; ClassificationType[ClassificationType["typeAliasName"] = 16] = "typeAliasName"; ClassificationType[ClassificationType["parameterName"] = 17] = "parameterName"; ClassificationType[ClassificationType["docCommentTagName"] = 18] = "docCommentTagName"; + ClassificationType[ClassificationType["jsxOpenTagName"] = 19] = "jsxOpenTagName"; + ClassificationType[ClassificationType["jsxCloseTagName"] = 20] = "jsxCloseTagName"; + ClassificationType[ClassificationType["jsxSelfClosingTagName"] = 21] = "jsxSelfClosingTagName"; + ClassificationType[ClassificationType["jsxAttribute"] = 22] = "jsxAttribute"; + ClassificationType[ClassificationType["jsxText"] = 23] = "jsxText"; + ClassificationType[ClassificationType["jsxAttributeStringLiteralValue"] = 24] = "jsxAttributeStringLiteralValue"; })(ts.ClassificationType || (ts.ClassificationType = {})); var ClassificationType = ts.ClassificationType; function displayPartsToString(displayParts) { @@ -43658,16 +47395,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 173 /* FunctionExpression */) { + if (declaration.kind === 176 /* FunctionExpression */) { return true; } - if (declaration.kind !== 211 /* VariableDeclaration */ && declaration.kind !== 213 /* FunctionDeclaration */) { + if (declaration.kind !== 214 /* VariableDeclaration */ && declaration.kind !== 216 /* 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) { + for (var parent_10 = declaration.parent; !ts.isFunctionBlock(parent_10); parent_10 = parent_10.parent) { // Reached source file or module block - if (parent_8.kind === 248 /* SourceFile */ || parent_8.kind === 219 /* ModuleBlock */) { + if (parent_10.kind === 251 /* SourceFile */ || parent_10.kind === 222 /* ModuleBlock */) { return false; } } @@ -43679,7 +47416,6 @@ var ts; // Always default to "ScriptTarget.ES5" for the language service return { target: 1 /* ES5 */, - module: 0 /* None */, jsx: 1 /* Preserve */ }; } @@ -43690,13 +47426,15 @@ var ts; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; + this.getCanonicalFileName = getCanonicalFileName; // script id => script index - this.fileNameToEntry = ts.createFileMap(getCanonicalFileName); + this.currentDirectory = host.getCurrentDirectory(); + this.fileNameToEntry = ts.createFileMap(); // 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); + for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) { + var fileName = rootFileNames_1[_i]; + this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName)); } // store the compilation settings this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); @@ -43704,7 +47442,7 @@ var ts; HostCache.prototype.compilationSettings = function () { return this._compilationSettings; }; - HostCache.prototype.createEntry = function (fileName) { + HostCache.prototype.createEntry = function (fileName, path) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); if (scriptSnapshot) { @@ -43714,40 +47452,41 @@ var ts; scriptSnapshot: scriptSnapshot }; } - this.fileNameToEntry.set(fileName, entry); + this.fileNameToEntry.set(path, entry); return entry; }; - HostCache.prototype.getEntry = function (fileName) { - return this.fileNameToEntry.get(fileName); + HostCache.prototype.getEntry = function (path) { + return this.fileNameToEntry.get(path); }; - HostCache.prototype.contains = function (fileName) { - return this.fileNameToEntry.contains(fileName); + HostCache.prototype.contains = function (path) { + return this.fileNameToEntry.contains(path); }; HostCache.prototype.getOrCreateEntry = function (fileName) { - if (this.contains(fileName)) { - return this.getEntry(fileName); + var path = ts.toPath(fileName, this.currentDirectory, this.getCanonicalFileName); + if (this.contains(path)) { + return this.getEntry(path); } - return this.createEntry(fileName); + return this.createEntry(fileName, path); }; HostCache.prototype.getRootFileNames = function () { var fileNames = []; - this.fileNameToEntry.forEachValue(function (value) { + this.fileNameToEntry.forEachValue(function (path, value) { if (value) { fileNames.push(value.hostFileName); } }); return fileNames; }; - HostCache.prototype.getVersion = function (fileName) { - var file = this.getEntry(fileName); + HostCache.prototype.getVersion = function (path) { + var file = this.getEntry(path); return file && file.version; }; - HostCache.prototype.getScriptSnapshot = function (fileName) { - var file = this.getEntry(fileName); + HostCache.prototype.getScriptSnapshot = function (path) { + var file = this.getEntry(path); return file && file.scriptSnapshot; }; return HostCache; - })(); + }()); var SyntaxTreeCache = (function () { function SyntaxTreeCache(host) { this.host = host; @@ -43762,7 +47501,7 @@ var ts; var sourceFile; if (this.currentFileName !== fileName) { // This is a new file, just parse it - sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 2 /* Latest */, version, /*setNodeParents:*/ true); + 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. @@ -43779,7 +47518,7 @@ var ts; return this.currentSourceFile; }; return SyntaxTreeCache; - })(); + }()); function setSourceFileFields(sourceFile, scriptSnapshot, version) { sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; @@ -43796,6 +47535,8 @@ var ts; function transpileModule(input, transpileOptions) { var options = transpileOptions.compilerOptions ? ts.clone(transpileOptions.compilerOptions) : getDefaultCompilerOptions(); options.isolatedModules = true; + // transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths. + options.suppressOutputPathCheck = true; // Filename can be non-ts file. options.allowNonTsExtensions = true; // We are not returning a sourceFile for lib file when asked by the program, @@ -43824,7 +47565,7 @@ var ts; sourceMapText = text; } else { - ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: " + name); + ts.Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: '" + name + "'"); outputText = text; } }, @@ -43834,7 +47575,8 @@ var ts; getCurrentDirectory: function () { return ""; }, getNewLine: function () { return newLine; }, fileExists: function (fileName) { return fileName === inputFileName; }, - readFile: function (fileName) { return ""; } + readFile: function (fileName) { return ""; }, + directoryExists: function (directoryExists) { return true; } }; var program = ts.createProgram([inputFileName], options, compilerHost); var diagnostics; @@ -43863,8 +47605,6 @@ var ts; 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; @@ -43876,7 +47616,7 @@ var ts; if (version !== sourceFile.version) { // Once incremental parsing is ready, then just call into this function. if (!ts.disableIncrementalParsing) { - var newText; + var newText = void 0; // 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) @@ -43916,70 +47656,65 @@ var ts; } } // Otherwise, just create a new source file. - return createLanguageServiceSourceFile(sourceFile.fileName, scriptSnapshot, sourceFile.languageVersion, version, /*setNodeParents:*/ true); + 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) { + function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. var buckets = {}; - var getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); + var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyFromCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx; + return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + +"|" + settings.allowJs; } function getBucketForCompilationSettings(settings, createIfMissing) { var key = getKeyFromCompilationSettings(settings); var bucket = ts.lookUp(buckets, key); if (!bucket && createIfMissing) { - buckets[key] = bucket = ts.createFileMap(getCanonicalFileName); + buckets[key] = bucket = ts.createFileMap(); } return bucket; } function reportStats() { - var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === '_'; }).map(function (name) { + 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); + entries.forEachValue(function (key, entry) { sourceFiles.push({ - name: i, + name: key, 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); + return JSON.stringify(bucketInfoArray, undefined, 2); } function acquireDocument(fileName, compilationSettings, scriptSnapshot, version) { - return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring:*/ true); + return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring*/ true); } function updateDocument(fileName, compilationSettings, scriptSnapshot, version) { - return acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, /*acquiring:*/ false); + 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); + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = bucket.get(path); 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); + var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false); entry = { sourceFile: sourceFile, languageServiceRefCount: 0, owners: [] }; - bucket.set(fileName, entry); + bucket.set(path, entry); } else { // We have an entry for this file. However, it may be for a different version of @@ -44000,13 +47735,14 @@ var ts; return entry.sourceFile; } function releaseDocument(fileName, compilationSettings) { - var bucket = getBucketForCompilationSettings(compilationSettings, false); + var bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ false); ts.Debug.assert(bucket !== undefined); - var entry = bucket.get(fileName); + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = bucket.get(path); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - bucket.remove(fileName); + bucket.remove(path); } } return { @@ -44017,8 +47753,9 @@ var ts; }; } ts.createDocumentRegistry = createDocumentRegistry; - function preProcessFile(sourceText, readImportFiles) { + function preProcessFile(sourceText, readImportFiles, detectJavaScriptImports) { if (readImportFiles === void 0) { readImportFiles = true; } + if (detectJavaScriptImports === void 0) { detectJavaScriptImports = false; } var referencedFiles = []; var importedFiles = []; var ambientExternalModules; @@ -44052,116 +47789,66 @@ var ts; 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 */) { + /** + * Returns true if at least one token was consumed from the stream + */ + function tryConsumeDeclare() { + var token = scanner.getToken(); + if (token === 122 /* DeclareKeyword */) { + // declare module "mod" + token = scanner.scan(); + if (token === 125 /* ModuleKeyword */) { token = scanner.scan(); if (token === 9 /* StringLiteral */) { - // import "mod"; - recordModuleName(); - continue; + recordAmbientExternalModule(); } - else { - if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + } + return true; + } + return false; + } + /** + * Returns true if at least one token was consumed from the stream + */ + function tryConsumeImport() { + var token = scanner.getToken(); + if (token === 89 /* ImportKeyword */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // import "mod"; + recordModuleName(); + return true; + } + else { + if (token === 69 /* Identifier */ || ts.isKeyword(token)) { + token = scanner.scan(); + if (token === 133 /* FromKeyword */) { 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 === 9 /* StringLiteral */) { + // import d from "mod"; + recordModuleName(); + return true; } } - 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 === 56 /* EqualsToken */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { + return true; } } - else if (token === 37 /* AsteriskToken */) { + else if (token === 24 /* CommaToken */) { + // consume comma and keep going 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 { + // unknown syntax + return true; } } - } - 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 */) { + // make sure that it stops on EOF + while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { token = scanner.scan(); } if (token === 16 /* CloseBraceToken */) { @@ -44169,49 +47856,171 @@ var ts; if (token === 133 /* FromKeyword */) { token = scanner.scan(); if (token === 9 /* StringLiteral */) { - // export {a as A} from "mod"; - // export {a, b as B} from "mod" + // 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(); + } + } + } + } + } + } + return true; + } + return false; + } + function tryConsumeExport() { + var token = scanner.getToken(); + if (token === 82 /* ExportKeyword */) { + token = scanner.scan(); + if (token === 15 /* OpenBraceToken */) { + token = scanner.scan(); + // consume "{ a as B, c, d as D}" clauses + // make sure it stops on EOF + while (token !== 16 /* CloseBraceToken */ && token !== 1 /* EndOfFileToken */) { + token = scanner.scan(); + } + if (token === 16 /* CloseBraceToken */) { token = scanner.scan(); if (token === 133 /* FromKeyword */) { token = scanner.scan(); if (token === 9 /* StringLiteral */) { - // export * from "mod" + // export {a as A} from "mod"; + // export {a, b as B} from "mod" recordModuleName(); } } } - else if (token === 89 /* ImportKeyword */) { + } + else if (token === 37 /* AsteriskToken */) { + token = scanner.scan(); + if (token === 133 /* FromKeyword */) { 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(); - } - } - } + 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 */) { + if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) { + return true; } } } } + return true; + } + return false; + } + function tryConsumeRequireCall(skipCurrentToken) { + var token = skipCurrentToken ? scanner.scan() : scanner.getToken(); + if (token === 127 /* RequireKeyword */) { + token = scanner.scan(); + if (token === 17 /* OpenParenToken */) { + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // require("mod"); + recordModuleName(); + } + } + return true; + } + return false; + } + function tryConsumeDefine() { + var token = scanner.getToken(); + if (token === 69 /* Identifier */ && scanner.getTokenValue() === "define") { + token = scanner.scan(); + if (token !== 17 /* OpenParenToken */) { + return true; + } + token = scanner.scan(); + if (token === 9 /* StringLiteral */) { + // looks like define ("modname", ... - skip string literal and comma + token = scanner.scan(); + if (token === 24 /* CommaToken */) { + token = scanner.scan(); + } + else { + // unexpected token + return true; + } + } + // should be start of dependency list + if (token !== 19 /* OpenBracketToken */) { + return true; + } + // skip open bracket token = scanner.scan(); + var i = 0; + // scan until ']' or EOF + while (token !== 20 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { + // record string literals as module names + if (token === 9 /* StringLiteral */) { + recordModuleName(); + i++; + } + token = scanner.scan(); + } + return true; + } + return false; + } + function processImports() { + scanner.setText(sourceText); + 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") + // (for JavaScript files) require("mod") + while (true) { + if (scanner.getToken() === 1 /* EndOfFileToken */) { + break; + } + // check if at least one of alternative have moved scanner forward + if (tryConsumeDeclare() || + tryConsumeImport() || + tryConsumeExport() || + (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false) || tryConsumeDefine()))) { + continue; + } + else { + scanner.scan(); + } } scanner.setText(undefined); } if (readImportFiles) { - processImport(); + processImports(); } processTripleSlashDirectives(); return { referencedFiles: referencedFiles, importedFiles: importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientExternalModules }; @@ -44220,7 +48029,7 @@ var ts; /// Helpers function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 207 /* LabeledStatement */ && referenceNode.label.text === labelName) { + if (referenceNode.kind === 210 /* LabeledStatement */ && referenceNode.label.text === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -44229,12 +48038,12 @@ var ts; } function isJumpStatementTarget(node) { return node.kind === 69 /* Identifier */ && - (node.parent.kind === 203 /* BreakStatement */ || node.parent.kind === 202 /* ContinueStatement */) && + (node.parent.kind === 206 /* BreakStatement */ || node.parent.kind === 205 /* ContinueStatement */) && node.parent.label === node; } function isLabelOfLabeledStatement(node) { return node.kind === 69 /* Identifier */ && - node.parent.kind === 207 /* LabeledStatement */ && + node.parent.kind === 210 /* LabeledStatement */ && node.parent.label === node; } /** @@ -44242,7 +48051,7 @@ var ts; * Note: 'node' cannot be a SourceFile. */ function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 207 /* LabeledStatement */; owner = owner.parent) { + for (var owner = node.parent; owner.kind === 210 /* LabeledStatement */; owner = owner.parent) { if (owner.label.text === labelName) { return true; } @@ -44253,25 +48062,25 @@ var ts; return isLabelOfLabeledStatement(node) || isJumpStatementTarget(node); } function isRightSideOfQualifiedName(node) { - return node.parent.kind === 135 /* QualifiedName */ && node.parent.right === node; + return node.parent.kind === 136 /* QualifiedName */ && node.parent.right === node; } function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 166 /* PropertyAccessExpression */ && node.parent.name === node; + return node && node.parent && node.parent.kind === 169 /* 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; + return node && node.parent && node.parent.kind === 171 /* 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; + return node && node.parent && node.parent.kind === 172 /* NewExpression */ && node.parent.expression === node; } function isNameOfModuleDeclaration(node) { - return node.parent.kind === 218 /* ModuleDeclaration */ && node.parent.name === node; + return node.parent.kind === 221 /* ModuleDeclaration */ && node.parent.name === node; } function isNameOfFunctionDeclaration(node) { return node.kind === 69 /* Identifier */ && @@ -44280,22 +48089,22 @@ var ts; /** 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; + (node.parent.kind === 248 /* PropertyAssignment */ || node.parent.kind === 249 /* 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 */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: + case 248 /* PropertyAssignment */: + case 250 /* EnumMember */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 221 /* ModuleDeclaration */: return node.parent.name === node; - case 167 /* ElementAccessExpression */: + case 170 /* ElementAccessExpression */: return node.parent.argumentExpression === node; } } @@ -44354,7 +48163,7 @@ var ts; })(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++) { + for (var i = 70 /* FirstKeyword */; i <= 135 /* LastKeyword */; i++) { keywordCompletions.push({ name: ts.tokenToString(i), kind: ScriptElementKind.keyword, @@ -44369,17 +48178,17 @@ var ts; 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 */: + case 251 /* SourceFile */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 216 /* FunctionDeclaration */: + case 176 /* FunctionExpression */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 217 /* ClassDeclaration */: + case 218 /* InterfaceDeclaration */: + case 220 /* EnumDeclaration */: + case 221 /* ModuleDeclaration */: return node; } } @@ -44387,38 +48196,38 @@ var ts; 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 */: + case 221 /* ModuleDeclaration */: return ScriptElementKind.moduleElement; + case 217 /* ClassDeclaration */: return ScriptElementKind.classElement; + case 218 /* InterfaceDeclaration */: return ScriptElementKind.interfaceElement; + case 219 /* TypeAliasDeclaration */: return ScriptElementKind.typeElement; + case 220 /* EnumDeclaration */: return ScriptElementKind.enumElement; + case 214 /* 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 */: + case 216 /* FunctionDeclaration */: return ScriptElementKind.functionElement; + case 146 /* GetAccessor */: return ScriptElementKind.memberGetAccessorElement; + case 147 /* SetAccessor */: return ScriptElementKind.memberSetAccessorElement; + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: return ScriptElementKind.memberFunctionElement; - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 142 /* PropertyDeclaration */: + case 141 /* 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 */: + case 150 /* IndexSignature */: return ScriptElementKind.indexSignatureElement; + case 149 /* ConstructSignature */: return ScriptElementKind.constructSignatureElement; + case 148 /* CallSignature */: return ScriptElementKind.callSignatureElement; + case 145 /* Constructor */: return ScriptElementKind.constructorImplementationElement; + case 138 /* TypeParameter */: return ScriptElementKind.typeParameterElement; + case 250 /* EnumMember */: return ScriptElementKind.variableElement; + case 139 /* Parameter */: return (node.flags & 56 /* AccessibilityModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; + case 224 /* ImportEqualsDeclaration */: + case 229 /* ImportSpecifier */: + case 226 /* ImportClause */: + case 233 /* ExportSpecifier */: + case 227 /* NamespaceImport */: return ScriptElementKind.alias; } return ScriptElementKind.unknown; @@ -44437,15 +48246,16 @@ var ts; } }; return CancellationTokenObject; - })(); + }()); function createLanguageService(host, documentRegistry) { - if (documentRegistry === void 0) { documentRegistry = createDocumentRegistry(); } + if (documentRegistry === void 0) { documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); var ruleProvider; var program; var lastProjectVersion; var useCaseSensitivefileNames = false; var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); + var currentDirectory = host.getCurrentDirectory(); // Check if the localized messages json is set, otherwise query the host for it if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); @@ -44455,10 +48265,9 @@ var ts; host.log(message); } } - var getCanonicalFileName = createGetCanonicalFileName(useCaseSensitivefileNames); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitivefileNames); function getValidSourceFile(fileName) { - fileName = ts.normalizeSlashes(fileName); - var sourceFile = program.getSourceFile(getCanonicalFileName(fileName)); + var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { throw new Error("Could not find file: '" + fileName + "'."); } @@ -44500,7 +48309,8 @@ var ts; (oldSettings.target !== newSettings.target || oldSettings.module !== newSettings.module || oldSettings.noResolve !== newSettings.noResolve || - oldSettings.jsx !== newSettings.jsx); + oldSettings.jsx !== newSettings.jsx || + oldSettings.allowJs !== newSettings.allowJs); // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -44510,7 +48320,7 @@ var ts; getNewLine: function () { return ts.getNewLineOrDefaultFromHost(host); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: function (fileName, data, writeByteOrderMark) { }, - getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { // stub missing host functionality ts.Debug.assert(!host.resolveModuleNames); @@ -44520,6 +48330,10 @@ var ts; // stub missing host functionality var entry = hostCache.getOrCreateEntry(fileName); return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + }, + directoryExists: function (directoryName) { + ts.Debug.assert(!host.resolveModuleNames); + return ts.directoryProbablyExists(directoryName, host); } }; if (host.resolveModuleNames) { @@ -44530,11 +48344,10 @@ var ts; // 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); + for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { + var oldSourceFile = oldSourceFiles_1[_i]; + if (!newProgram.getSourceFile(oldSourceFile.fileName) || changesInCompilationSettingsAffectSyntax) { + documentRegistry.releaseDocument(oldSourceFile.fileName, oldSettings); } } } @@ -44590,7 +48403,11 @@ var ts; return documentRegistry.acquireDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version); } function sourceFileUpToDate(sourceFile) { - return sourceFile && sourceFile.version === hostCache.getVersion(sourceFile.fileName); + if (!sourceFile) { + return false; + } + var path = sourceFile.path || ts.toPath(sourceFile.fileName, currentDirectory, getCanonicalFileName); + return sourceFile.version === hostCache.getVersion(path); } function programUpToDate() { // If we haven't create a program yet, then it is not up-to-date @@ -44603,8 +48420,8 @@ var ts; 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]; + for (var _i = 0, rootFileNames_2 = rootFileNames; _i < rootFileNames_2.length; _i++) { + var fileName = rootFileNames_2[_i]; if (!sourceFileUpToDate(program.getSourceFile(fileName))) { return false; } @@ -44639,12 +48456,6 @@ var ts; 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); @@ -44655,151 +48466,6 @@ var ts; 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)); @@ -44816,7 +48482,7 @@ var ts; // 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) + // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) return undefined; } } @@ -44839,22 +48505,16 @@ var ts; // 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)) { + if (!ts.isIdentifier(name, 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 isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); var isJsDocTagName = false; var start = new Date().getTime(); var currentToken = ts.getTokenAtPosition(sourceFile, position); @@ -44864,7 +48524,7 @@ var ts; 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. + // 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; @@ -44879,9 +48539,9 @@ var ts; isJsDocTagName = true; } switch (tag.kind) { - case 269 /* JSDocTypeTag */: - case 267 /* JSDocParameterTag */: - case 268 /* JSDocReturnTag */: + case 272 /* JSDocTypeTag */: + case 270 /* JSDocParameterTag */: + case 271 /* JSDocReturnTag */: var tagWithExpression = tag; if (tagWithExpression.typeExpression) { insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; @@ -44893,7 +48553,7 @@ var ts; 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 + // 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; @@ -44908,9 +48568,9 @@ var ts; // 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(); + var start_6 = new Date().getTime(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_3)); + log("getCompletionData: Get previous token 2: " + (new Date().getTime() - start_6)); } // Find the node where completion is requested on. // Also determine whether we are trying to complete with members of that node @@ -44926,13 +48586,13 @@ var ts; log("Returning an empty list because completion was requested in an invalid position."); return undefined; } - var parent_9 = contextToken.parent, kind = contextToken.kind; + var parent_11 = contextToken.parent, kind = contextToken.kind; if (kind === 21 /* DotToken */) { - if (parent_9.kind === 166 /* PropertyAccessExpression */) { + if (parent_11.kind === 169 /* PropertyAccessExpression */) { node = contextToken.parent.expression; isRightOfDot = true; } - else if (parent_9.kind === 135 /* QualifiedName */) { + else if (parent_11.kind === 136 /* QualifiedName */) { node = contextToken.parent.left; isRightOfDot = true; } @@ -44947,8 +48607,9 @@ var ts; isRightOfOpenTag = true; location = contextToken; } - else if (kind === 39 /* SlashToken */ && contextToken.parent.kind === 237 /* JsxClosingElement */) { + else if (kind === 39 /* SlashToken */ && contextToken.parent.kind === 240 /* JsxClosingElement */) { isStartingCloseTag = true; + location = contextToken; } } } @@ -44972,7 +48633,10 @@ var ts; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; - symbols = [typeChecker.getSymbolAtLocation(tagName)]; + var tagSymbol = typeChecker.getSymbolAtLocation(tagName); + if (!typeChecker.isUnknownSymbol(tagSymbol)) { + symbols = [tagSymbol]; + } isMemberCompletion = true; isNewIdentifierLocation = false; } @@ -44990,7 +48654,7 @@ var ts; // Right of dot member completion list isMemberCompletion = true; isNewIdentifierLocation = false; - if (node.kind === 69 /* Identifier */ || node.kind === 135 /* QualifiedName */ || node.kind === 166 /* PropertyAccessExpression */) { + if (node.kind === 69 /* Identifier */ || node.kind === 136 /* QualifiedName */ || node.kind === 169 /* PropertyAccessExpression */) { var symbol = typeChecker.getSymbolAtLocation(node); // This is an alias, follow what it aliases if (symbol && symbol.flags & 8388608 /* Alias */) { @@ -45045,8 +48709,8 @@ var ts; return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { - var attrsType; - if ((jsxContainer.kind === 234 /* JsxSelfClosingElement */) || (jsxContainer.kind === 235 /* JsxOpeningElement */)) { + var attrsType = void 0; + if ((jsxContainer.kind === 237 /* JsxSelfClosingElement */) || (jsxContainer.kind === 238 /* JsxOpeningElement */)) { // Cursor is inside a JSX self-closing element or opening element attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); if (attrsType) { @@ -45118,15 +48782,15 @@ var ts; return result; } function isInJsxText(contextToken) { - if (contextToken.kind === 236 /* JsxText */) { + if (contextToken.kind === 239 /* JsxText */) { return true; } if (contextToken.kind === 27 /* GreaterThanToken */ && contextToken.parent) { - if (contextToken.parent.kind === 235 /* JsxOpeningElement */) { + if (contextToken.parent.kind === 238 /* JsxOpeningElement */) { return true; } - if (contextToken.parent.kind === 237 /* JsxClosingElement */ || contextToken.parent.kind === 234 /* JsxSelfClosingElement */) { - return contextToken.parent.parent && contextToken.parent.parent.kind === 233 /* JsxElement */; + if (contextToken.parent.kind === 240 /* JsxClosingElement */ || contextToken.parent.kind === 237 /* JsxSelfClosingElement */) { + return contextToken.parent.parent && contextToken.parent.parent.kind === 236 /* JsxElement */; } } return false; @@ -45136,40 +48800,40 @@ var ts; 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| + return containingNodeKind === 171 /* CallExpression */ // func( a, | + || containingNodeKind === 145 /* Constructor */ // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + || containingNodeKind === 172 /* NewExpression */ // new C(a, | + || containingNodeKind === 167 /* ArrayLiteralExpression */ // [a, | + || containingNodeKind === 184 /* BinaryExpression */ // const x = (a, | + || containingNodeKind === 153 /* 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 */ + return containingNodeKind === 171 /* CallExpression */ // func( | + || containingNodeKind === 145 /* Constructor */ // constructor( | + || containingNodeKind === 172 /* NewExpression */ // new C(a| + || containingNodeKind === 175 /* ParenthesizedExpression */ // const x = (a| + || containingNodeKind === 161 /* 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 */ + return containingNodeKind === 167 /* ArrayLiteralExpression */ // [ | + || containingNodeKind === 150 /* IndexSignature */ // [ | : string ] + || containingNodeKind === 137 /* 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.| + return containingNodeKind === 221 /* ModuleDeclaration */; // module A.| case 15 /* OpenBraceToken */: - return containingNodeKind === 214 /* ClassDeclaration */; // class A{ | + return containingNodeKind === 217 /* ClassDeclaration */; // class A{ | case 56 /* EqualsToken */: - return containingNodeKind === 211 /* VariableDeclaration */ // let x = a| - || containingNodeKind === 181 /* BinaryExpression */; // x = a| + return containingNodeKind === 214 /* VariableDeclaration */ // const x = a| + || containingNodeKind === 184 /* BinaryExpression */; // x = a| case 12 /* TemplateHead */: - return containingNodeKind === 183 /* TemplateExpression */; // `aa ${| + return containingNodeKind === 186 /* TemplateExpression */; // `aa ${| case 13 /* TemplateMiddle */: - return containingNodeKind === 190 /* TemplateSpan */; // `aa ${10} dd ${| + return containingNodeKind === 193 /* TemplateSpan */; // `aa ${10} dd ${| case 112 /* PublicKeyword */: case 110 /* PrivateKeyword */: case 111 /* ProtectedKeyword */: - return containingNodeKind === 141 /* PropertyDeclaration */; // class A{ public | + return containingNodeKind === 142 /* PropertyDeclaration */; // class A{ public | } // Previous token may have been a keyword that was converted to an identifier. switch (previousToken.getText()) { @@ -45183,15 +48847,16 @@ var ts; } function isInStringOrRegularExpressionOrTemplateLiteral(contextToken) { if (contextToken.kind === 9 /* StringLiteral */ + || contextToken.kind === 163 /* StringLiteralType */ || contextToken.kind === 10 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_4 = contextToken.getStart(); + var start_7 = 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) { + if (start_7 < position && position < end) { return true; } if (position === end) { @@ -45212,14 +48877,14 @@ var ts; isMemberCompletion = true; var typeForObject; var existingMembers; - if (objectLikeContainer.kind === 165 /* ObjectLiteralExpression */) { + if (objectLikeContainer.kind === 168 /* 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 */) { + else if (objectLikeContainer.kind === 164 /* ObjectBindingPattern */) { // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); @@ -45265,9 +48930,9 @@ var ts; * @returns true if 'symbols' was successfully populated; false otherwise. */ function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { - var declarationKind = namedImportsOrExports.kind === 225 /* NamedImports */ ? - 222 /* ImportDeclaration */ : - 228 /* ExportDeclaration */; + var declarationKind = namedImportsOrExports.kind === 228 /* NamedImports */ ? + 225 /* ImportDeclaration */ : + 231 /* ExportDeclaration */; var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; if (!moduleSpecifier) { @@ -45290,11 +48955,11 @@ var ts; function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { - case 15 /* OpenBraceToken */: // let x = { | + case 15 /* OpenBraceToken */: // const 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; + var parent_12 = contextToken.parent; + if (parent_12 && (parent_12.kind === 168 /* ObjectLiteralExpression */ || parent_12.kind === 164 /* ObjectBindingPattern */)) { + return parent_12; } break; } @@ -45311,8 +48976,8 @@ var ts; case 15 /* OpenBraceToken */: // import { | case 24 /* CommaToken */: switch (contextToken.parent.kind) { - case 225 /* NamedImports */: - case 229 /* NamedExports */: + case 228 /* NamedImports */: + case 232 /* NamedExports */: return contextToken.parent; } } @@ -45321,37 +48986,37 @@ var ts; } function tryGetContainingJsxElement(contextToken) { if (contextToken) { - var parent_11 = contextToken.parent; + var parent_13 = 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; + case 241 /* JsxAttribute */: + case 242 /* JsxSpreadAttribute */: + if (parent_13 && (parent_13.kind === 237 /* JsxSelfClosingElement */ || parent_13.kind === 238 /* JsxOpeningElement */)) { + return parent_13; } - else if (parent_11.kind === 238 /* JsxAttribute */) { - return parent_11.parent; + else if (parent_13.kind === 241 /* JsxAttribute */) { + return parent_13.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; + if (parent_13 && ((parent_13.kind === 241 /* JsxAttribute */) || (parent_13.kind === 242 /* JsxSpreadAttribute */))) { + return parent_13.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_13 && + parent_13.kind === 243 /* JsxExpression */ && + parent_13.parent && + (parent_13.parent.kind === 241 /* JsxAttribute */)) { + return parent_13.parent.parent; } - if (parent_11 && parent_11.kind === 239 /* JsxSpreadAttribute */) { - return parent_11.parent; + if (parent_13 && parent_13.kind === 242 /* JsxSpreadAttribute */) { + return parent_13.parent; } break; } @@ -45360,16 +49025,16 @@ var ts; } 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 */: + case 176 /* FunctionExpression */: + case 177 /* ArrowFunction */: + case 216 /* FunctionDeclaration */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 148 /* CallSignature */: + case 149 /* ConstructSignature */: + case 150 /* IndexSignature */: return true; } return false; @@ -45381,54 +49046,54 @@ var ts; var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { case 24 /* CommaToken */: - return containingNodeKind === 211 /* VariableDeclaration */ || - containingNodeKind === 212 /* VariableDeclarationList */ || - containingNodeKind === 193 /* VariableStatement */ || - containingNodeKind === 217 /* EnumDeclaration */ || + return containingNodeKind === 214 /* VariableDeclaration */ || + containingNodeKind === 215 /* VariableDeclarationList */ || + containingNodeKind === 196 /* VariableStatement */ || + containingNodeKind === 220 /* EnumDeclaration */ || isFunction(containingNodeKind) || - containingNodeKind === 214 /* ClassDeclaration */ || - containingNodeKind === 186 /* ClassExpression */ || - containingNodeKind === 215 /* InterfaceDeclaration */ || - containingNodeKind === 162 /* ArrayBindingPattern */ || - containingNodeKind === 216 /* TypeAliasDeclaration */; // type Map, K, | + containingNodeKind === 217 /* ClassDeclaration */ || + containingNodeKind === 189 /* ClassExpression */ || + containingNodeKind === 218 /* InterfaceDeclaration */ || + containingNodeKind === 165 /* ArrayBindingPattern */ || + containingNodeKind === 219 /* TypeAliasDeclaration */; // type Map, K, | case 21 /* DotToken */: - return containingNodeKind === 162 /* ArrayBindingPattern */; // var [.| + return containingNodeKind === 165 /* ArrayBindingPattern */; // var [.| case 54 /* ColonToken */: - return containingNodeKind === 163 /* BindingElement */; // var {x :html| + return containingNodeKind === 166 /* BindingElement */; // var {x :html| case 19 /* OpenBracketToken */: - return containingNodeKind === 162 /* ArrayBindingPattern */; // var [x| + return containingNodeKind === 165 /* ArrayBindingPattern */; // var [x| case 17 /* OpenParenToken */: - return containingNodeKind === 244 /* CatchClause */ || + return containingNodeKind === 247 /* CatchClause */ || isFunction(containingNodeKind); case 15 /* OpenBraceToken */: - return containingNodeKind === 217 /* EnumDeclaration */ || - containingNodeKind === 215 /* InterfaceDeclaration */ || - containingNodeKind === 155 /* TypeLiteral */; // let x : { | + return containingNodeKind === 220 /* EnumDeclaration */ || + containingNodeKind === 218 /* InterfaceDeclaration */ || + containingNodeKind === 156 /* TypeLiteral */; // const x : { | case 23 /* SemicolonToken */: - return containingNodeKind === 140 /* PropertySignature */ && + return containingNodeKind === 141 /* PropertySignature */ && contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 215 /* InterfaceDeclaration */ || - contextToken.parent.parent.kind === 155 /* TypeLiteral */); // let x : { a; | + (contextToken.parent.parent.kind === 218 /* InterfaceDeclaration */ || + contextToken.parent.parent.kind === 156 /* TypeLiteral */); // const x : { a; | case 25 /* LessThanToken */: - return containingNodeKind === 214 /* ClassDeclaration */ || - containingNodeKind === 186 /* ClassExpression */ || - containingNodeKind === 215 /* InterfaceDeclaration */ || - containingNodeKind === 216 /* TypeAliasDeclaration */ || + return containingNodeKind === 217 /* ClassDeclaration */ || + containingNodeKind === 189 /* ClassExpression */ || + containingNodeKind === 218 /* InterfaceDeclaration */ || + containingNodeKind === 219 /* TypeAliasDeclaration */ || isFunction(containingNodeKind); case 113 /* StaticKeyword */: - return containingNodeKind === 141 /* PropertyDeclaration */; + return containingNodeKind === 142 /* PropertyDeclaration */; case 22 /* DotDotDotToken */: - return containingNodeKind === 138 /* Parameter */ || + return containingNodeKind === 139 /* Parameter */ || (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 162 /* ArrayBindingPattern */); // var [...z| + contextToken.parent.parent.kind === 165 /* ArrayBindingPattern */); // var [...z| case 112 /* PublicKeyword */: case 110 /* PrivateKeyword */: case 111 /* ProtectedKeyword */: - return containingNodeKind === 138 /* Parameter */; + return containingNodeKind === 139 /* Parameter */; case 116 /* AsKeyword */: - return containingNodeKind === 226 /* ImportSpecifier */ || - containingNodeKind === 230 /* ExportSpecifier */ || - containingNodeKind === 224 /* NamespaceImport */; + return containingNodeKind === 229 /* ImportSpecifier */ || + containingNodeKind === 233 /* ExportSpecifier */ || + containingNodeKind === 227 /* NamespaceImport */; case 73 /* ClassKeyword */: case 81 /* EnumKeyword */: case 107 /* InterfaceKeyword */: @@ -45482,14 +49147,14 @@ var ts; */ function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { var exisingImportsOrExports = {}; - for (var _i = 0; _i < namedImportsOrExports.length; _i++) { - var element = namedImportsOrExports[_i]; + for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { + var element = namedImportsOrExports_1[_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; + var name_35 = element.propertyName || element.name; + exisingImportsOrExports[name_35.text] = true; } if (ts.isEmpty(exisingImportsOrExports)) { return exportsOfModule; @@ -45507,12 +49172,13 @@ var ts; return contextualMemberSymbols; } var existingMemberNames = {}; - for (var _i = 0; _i < existingMembers.length; _i++) { - var m = existingMembers[_i]; + for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { + var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 245 /* PropertyAssignment */ && - m.kind !== 246 /* ShorthandPropertyAssignment */ && - m.kind !== 163 /* BindingElement */) { + if (m.kind !== 248 /* PropertyAssignment */ && + m.kind !== 249 /* ShorthandPropertyAssignment */ && + m.kind !== 166 /* BindingElement */ && + m.kind !== 144 /* MethodDeclaration */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -45520,8 +49186,11 @@ var ts; continue; } var existingName = void 0; - if (m.kind === 163 /* BindingElement */ && m.propertyName) { - existingName = m.propertyName.text; + if (m.kind === 166 /* BindingElement */ && m.propertyName) { + // include only identifiers in completion list + if (m.propertyName.kind === 69 /* Identifier */) { + existingName = m.propertyName.text; + } } else { // TODO(jfreeman): Account for computed property name @@ -45541,13 +49210,13 @@ var ts; */ function filterJsxAttributes(symbols, attributes) { var seenNames = {}; - for (var _i = 0; _i < attributes.length; _i++) { - var attr = attributes[_i]; + for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { + var attr = attributes_1[_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 */) { + if (attr.kind === 241 /* JsxAttribute */) { seenNames[attr.name.text] = true; } } @@ -45560,47 +49229,64 @@ var ts; 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; + var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; 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()); + var sourceFile = getValidSourceFile(fileName); + var entries = []; + if (ts.isSourceFileJavaScript(sourceFile)) { + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries); + ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); } else { if (!symbols || symbols.length === 0) { - return undefined; + if (sourceFile.languageVariant === 1 /* JSX */ && + location.parent && location.parent.kind === 240 /* JsxClosingElement */) { + // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, + // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. + // For example: + // var x =
completion list at "1" will contain "div" with type any + var tagName = location.parent.parent.openingElement.tagName; + entries.push({ + name: tagName.text, + kind: undefined, + kindModifiers: undefined, + sortText: "0" + }); + } + else { + return undefined; + } } - entries = getCompletionEntriesFromSymbols(symbols); + getCompletionEntriesFromSymbols(symbols, entries); } // 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() { + function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { 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); - } + var nameTable = getNameTable(sourceFile); + for (var name_36 in nameTable) { + // Skip identifiers produced only from the current location + if (nameTable[name_36] === position) { + continue; + } + if (!uniqueNames[name_36]) { + uniqueNames[name_36] = name_36; + var displayName = getCompletionEntryDisplayName(name_36, target, /*performCharacterChecks*/ true); + if (displayName) { + var entry = { + name: displayName, + kind: ScriptElementKind.warning, + kindModifiers: "", + sortText: "1" + }; + entries.push(entry); } } } @@ -45620,7 +49306,7 @@ var ts; // 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); + var displayName = getCompletionEntryDisplayNameForSymbol(symbol, program.getCompilerOptions().target, /*performCharacterChecks*/ true, location); if (!displayName) { return undefined; } @@ -45638,25 +49324,24 @@ var ts; sortText: "0" }; } - function getCompletionEntriesFromSymbols(symbols) { + function getCompletionEntriesFromSymbols(symbols, entries) { var start = new Date().getTime(); - var entries = []; + var uniqueNames = {}; if (symbols) { - var nameToSymbol = {}; - for (var _i = 0; _i < symbols.length; _i++) { - var symbol = symbols[_i]; + for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { + var symbol = symbols_4[_i]; var entry = createCompletionEntry(symbol, location); if (entry) { var id = ts.escapeIdentifier(entry.name); - if (!ts.lookUp(nameToSymbol, id)) { + if (!ts.lookUp(uniqueNames, id)) { entries.push(entry); - nameToSymbol[id] = symbol; + uniqueNames[id] = id; } } } } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (new Date().getTime() - start)); - return entries; + return uniqueNames; } } function getCompletionEntryDetails(fileName, position, entryName) { @@ -45666,11 +49351,11 @@ var ts; if (completionData) { var symbols = completionData.symbols, location_2 = completionData.location; // Find the symbol with the matching entry name. - var target = program.getCompilerOptions().target; + var target_2 = 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; }); + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, target_2, /*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 { @@ -45699,7 +49384,7 @@ var ts; function getSymbolKind(symbol, location) { var flags = symbol.getFlags(); if (flags & 32 /* Class */) - return ts.getDeclarationOfKind(symbol, 186 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 189 /* ClassExpression */) ? ScriptElementKind.localClassElement : ScriptElementKind.classElement; if (flags & 384 /* Enum */) return ScriptElementKind.enumElement; @@ -45764,7 +49449,7 @@ var ts; }); if (!unionPropertyKind) { // If this was union of all methods, - //make sure it has call signatures before we can label it as method + // 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; @@ -45798,10 +49483,10 @@ var ts; if (symbolKind === ScriptElementKind.memberGetAccessorElement || symbolKind === ScriptElementKind.memberSetAccessorElement) { symbolKind = ScriptElementKind.memberVariableElement; } - var signature; + var signature = void 0; type = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (type) { - if (location.parent && location.parent.kind === 166 /* PropertyAccessExpression */) { + if (location.parent && location.parent.kind === 169 /* 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)) { @@ -45809,8 +49494,8 @@ var ts; } } // try get the call/construct signature from the type if it matches - var callExpression; - if (location.kind === 168 /* CallExpression */ || location.kind === 169 /* NewExpression */) { + var callExpression = void 0; + if (location.kind === 171 /* CallExpression */ || location.kind === 172 /* NewExpression */) { callExpression = location; } else if (isCallExpressionTarget(location) || isNewExpressionTarget(location)) { @@ -45823,7 +49508,7 @@ var ts; // Use the first candidate: signature = candidateSignatures[0]; } - var useConstructSignatures = callExpression.kind === 169 /* NewExpression */ || callExpression.expression.kind === 95 /* SuperKeyword */; + var useConstructSignatures = callExpression.kind === 172 /* 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 @@ -45876,24 +49561,24 @@ var ts; } } else if ((isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304 /* Accessor */)) || - (location.kind === 121 /* ConstructorKeyword */ && location.parent.kind === 144 /* Constructor */)) { + (location.kind === 121 /* ConstructorKeyword */ && location.parent.kind === 145 /* Constructor */)) { // get the signature from the declaration and write it var functionDeclaration = location.parent; - var allSignatures = functionDeclaration.kind === 144 /* Constructor */ ? type.getConstructSignatures() : type.getCallSignatures(); + var allSignatures = functionDeclaration.kind === 145 /* Constructor */ ? type.getConstructSignatures() : type.getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration)) { signature = typeChecker.getSignatureFromDeclaration(functionDeclaration); } else { signature = allSignatures[0]; } - if (functionDeclaration.kind === 144 /* Constructor */) { + if (functionDeclaration.kind === 145 /* Constructor */) { // show (constructor) Type(...) signature symbolKind = ScriptElementKind.constructorImplementationElement; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 147 /* CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration.kind === 148 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -45902,7 +49587,7 @@ var ts; } } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo) { - if (ts.getDeclarationOfKind(symbol, 186 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 189 /* 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 @@ -45946,7 +49631,7 @@ var ts; } if (symbolFlags & 1536 /* Module */) { addNewLineIfDisplayPartsExist(); - var declaration = ts.getDeclarationOfKind(symbol, 218 /* ModuleDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 221 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 69 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 126 /* NamespaceKeyword */ : 125 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); @@ -45969,35 +49654,37 @@ var ts; } 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()); + var declaration = ts.getDeclarationOfKind(symbol, 138 /* TypeParameter */); + ts.Debug.assert(declaration !== undefined); + declaration = declaration.parent; + if (declaration) { + if (ts.isFunctionLikeKind(declaration.kind)) { + var signature = typeChecker.getSignatureFromDeclaration(declaration); + if (declaration.kind === 149 /* ConstructSignature */) { + displayParts.push(ts.keywordPart(92 /* NewKeyword */)); + displayParts.push(ts.spacePart()); + } + else if (declaration.kind !== 148 /* CallSignature */ && declaration.name) { + addFullSymbolName(declaration.symbol); + } + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } - else if (signatureDeclaration.kind !== 147 /* CallSignature */ && signatureDeclaration.name) { - addFullSymbolName(signatureDeclaration.symbol); + else { + // Type alias type parameter + // For example + // type list = T[]; // Both T will go through same code path + displayParts.push(ts.keywordPart(132 /* TypeKeyword */)); + displayParts.push(ts.spacePart()); + addFullSymbolName(declaration.symbol); + writeTypeParametersOfSymbol(declaration.symbol, sourceFile); } - 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 */) { + if (declaration.kind === 250 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -46013,7 +49700,7 @@ var ts; displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 221 /* ImportEqualsDeclaration */) { + if (declaration.kind === 224 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); @@ -46142,13 +49829,14 @@ var ts; } var typeChecker = program.getTypeChecker(); var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol) { + if (!symbol || typeChecker.isUnknownSymbol(symbol)) { // Try getting just type at this position and show switch (node.kind) { case 69 /* Identifier */: - case 166 /* PropertyAccessExpression */: - case 135 /* QualifiedName */: + case 169 /* PropertyAccessExpression */: + case 136 /* QualifiedName */: case 97 /* ThisKeyword */: + case 162 /* ThisType */: case 95 /* SuperKeyword */: // For the identifiers/this/super etc get the type at position var type = typeChecker.getTypeAtLocation(node); @@ -46227,8 +49915,8 @@ var ts; 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 */))) { + if ((selectConstructors && d.kind === 145 /* Constructor */) || + (!selectConstructors && (d.kind === 216 /* FunctionDeclaration */ || d.kind === 144 /* MethodDeclaration */ || d.kind === 143 /* MethodSignature */))) { declarations.push(d); if (d.body) definition = d; @@ -46297,16 +49985,16 @@ var ts; // 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 */) { + if (node.parent.kind === 249 /* 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); }); + var shorthandSymbolKind_1 = getSymbolKind(shorthandSymbol, node); + var shorthandSymbolName_1 = typeChecker.symbolToString(shorthandSymbol); + var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); + return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); } return getDefinitionFromSymbol(symbol, node); } @@ -46328,13 +50016,13 @@ var ts; return undefined; } if (type.flags & 16384 /* Union */) { - var result = []; + var result_4 = []; ts.forEach(type.types, function (t) { if (t.symbol) { - ts.addRange(/*to*/ result, /*from*/ getDefinitionFromSymbol(t.symbol, node)); + ts.addRange(/*to*/ result_4, /*from*/ getDefinitionFromSymbol(t.symbol, node)); } }); - return result; + return result_4; } if (!type.symbol) { return undefined; @@ -46344,10 +50032,10 @@ var ts; function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); if (results) { - var sourceFile = getCanonicalFileName(ts.normalizeSlashes(fileName)); + var sourceFile_2 = 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; }); + results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_2; }); } return results; } @@ -46373,10 +50061,11 @@ var ts; function getSemanticDocumentHighlights(node) { if (node.kind === 69 /* Identifier */ || node.kind === 97 /* ThisKeyword */ || + node.kind === 162 /* ThisType */ || node.kind === 95 /* SuperKeyword */ || isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) { - var referencedSymbols = getReferencedSymbolsForNode(node, sourceFilesToSearch, /*findInStrings:*/ false, /*findInComments:*/ false); + var referencedSymbols = getReferencedSymbolsForNode(node, sourceFilesToSearch, /*findInStrings*/ false, /*findInComments*/ false); return convertReferencedSymbols(referencedSymbols); } return undefined; @@ -46386,8 +50075,8 @@ var ts; } var fileNameToDocumentHighlights = {}; var result = []; - for (var _i = 0; _i < referencedSymbols.length; _i++) { - var referencedSymbol = referencedSymbols[_i]; + for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { + var referencedSymbol = referencedSymbols_1[_i]; for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { var referenceEntry = _b[_a]; var fileName_1 = referenceEntry.fileName; @@ -46426,75 +50115,75 @@ var ts; switch (node.kind) { case 88 /* IfKeyword */: case 80 /* ElseKeyword */: - if (hasKind(node.parent, 196 /* IfStatement */)) { + if (hasKind(node.parent, 199 /* IfStatement */)) { return getIfElseOccurrences(node.parent); } break; case 94 /* ReturnKeyword */: - if (hasKind(node.parent, 204 /* ReturnStatement */)) { + if (hasKind(node.parent, 207 /* ReturnStatement */)) { return getReturnOccurrences(node.parent); } break; case 98 /* ThrowKeyword */: - if (hasKind(node.parent, 208 /* ThrowStatement */)) { + if (hasKind(node.parent, 211 /* ThrowStatement */)) { return getThrowOccurrences(node.parent); } break; case 72 /* CatchKeyword */: - if (hasKind(parent(parent(node)), 209 /* TryStatement */)) { + if (hasKind(parent(parent(node)), 212 /* TryStatement */)) { return getTryCatchFinallyOccurrences(node.parent.parent); } break; case 100 /* TryKeyword */: case 85 /* FinallyKeyword */: - if (hasKind(parent(node), 209 /* TryStatement */)) { + if (hasKind(parent(node), 212 /* TryStatement */)) { return getTryCatchFinallyOccurrences(node.parent); } break; case 96 /* SwitchKeyword */: - if (hasKind(node.parent, 206 /* SwitchStatement */)) { + if (hasKind(node.parent, 209 /* SwitchStatement */)) { return getSwitchCaseDefaultOccurrences(node.parent); } break; case 71 /* CaseKeyword */: case 77 /* DefaultKeyword */: - if (hasKind(parent(parent(parent(node))), 206 /* SwitchStatement */)) { + if (hasKind(parent(parent(parent(node))), 209 /* 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 */)) { + if (hasKind(node.parent, 206 /* BreakStatement */) || hasKind(node.parent, 205 /* 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 */)) { + if (hasKind(node.parent, 202 /* ForStatement */) || + hasKind(node.parent, 203 /* ForInStatement */) || + hasKind(node.parent, 204 /* ForOfStatement */)) { return getLoopBreakContinueOccurrences(node.parent); } break; case 104 /* WhileKeyword */: case 79 /* DoKeyword */: - if (hasKind(node.parent, 198 /* WhileStatement */) || hasKind(node.parent, 197 /* DoStatement */)) { + if (hasKind(node.parent, 201 /* WhileStatement */) || hasKind(node.parent, 200 /* DoStatement */)) { return getLoopBreakContinueOccurrences(node.parent); } break; case 121 /* ConstructorKeyword */: - if (hasKind(node.parent, 144 /* Constructor */)) { + if (hasKind(node.parent, 145 /* Constructor */)) { return getConstructorOccurrences(node.parent); } break; case 123 /* GetKeyword */: case 129 /* SetKeyword */: - if (hasKind(node.parent, 145 /* GetAccessor */) || hasKind(node.parent, 146 /* SetAccessor */)) { + if (hasKind(node.parent, 146 /* GetAccessor */) || hasKind(node.parent, 147 /* SetAccessor */)) { return getGetAndSetOccurrences(node.parent); } break; default: - if (ts.isModifier(node.kind) && node.parent && - (ts.isDeclaration(node.parent) || node.parent.kind === 193 /* VariableStatement */)) { + if (ts.isModifierKind(node.kind) && node.parent && + (ts.isDeclaration(node.parent) || node.parent.kind === 196 /* VariableStatement */)) { return getModifierOccurrences(node.kind, node.parent); } } @@ -46510,10 +50199,10 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 208 /* ThrowStatement */) { + if (node.kind === 211 /* ThrowStatement */) { statementAccumulator.push(node); } - else if (node.kind === 209 /* TryStatement */) { + else if (node.kind === 212 /* TryStatement */) { var tryStatement = node; if (tryStatement.catchClause) { aggregate(tryStatement.catchClause); @@ -46531,7 +50220,6 @@ var ts; ts.forEachChild(node, aggregate); } } - ; } /** * For lack of a better name, this function takes a throw statement and returns the @@ -46541,19 +50229,19 @@ var ts; 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; + var parent_14 = child.parent; + if (ts.isFunctionBlock(parent_14) || parent_14.kind === 251 /* SourceFile */) { + return parent_14; } // 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 (parent_14.kind === 212 /* TryStatement */) { + var tryStatement = parent_14; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; } } - child = parent_12; + child = parent_14; } return undefined; } @@ -46562,14 +50250,13 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 203 /* BreakStatement */ || node.kind === 202 /* ContinueStatement */) { + if (node.kind === 206 /* BreakStatement */ || node.kind === 205 /* ContinueStatement */) { statementAccumulator.push(node); } else if (!ts.isFunctionLike(node)) { ts.forEachChild(node, aggregate); } } - ; } function ownsBreakOrContinueStatement(owner, statement) { var actualOwner = getBreakOrContinueOwner(statement); @@ -46578,16 +50265,16 @@ var ts; 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 */) { + case 209 /* SwitchStatement */: + if (statement.kind === 205 /* ContinueStatement */) { continue; } // Fall through. - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 198 /* WhileStatement */: - case 197 /* DoStatement */: + case 202 /* ForStatement */: + case 203 /* ForInStatement */: + case 204 /* ForOfStatement */: + case 201 /* WhileStatement */: + case 200 /* DoStatement */: if (!statement.label || isLabeledBy(node_2, statement.label.text)) { return node_2; } @@ -46606,24 +50293,24 @@ var ts; 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 */)))) { + if (!(container.kind === 217 /* ClassDeclaration */ || + container.kind === 189 /* ClassExpression */ || + (declaration.kind === 139 /* Parameter */ && hasKind(container, 145 /* Constructor */)))) { return undefined; } } else if (modifier === 113 /* StaticKeyword */) { - if (!(container.kind === 214 /* ClassDeclaration */ || container.kind === 186 /* ClassExpression */)) { + if (!(container.kind === 217 /* ClassDeclaration */ || container.kind === 189 /* ClassExpression */)) { return undefined; } } else if (modifier === 82 /* ExportKeyword */ || modifier === 122 /* DeclareKeyword */) { - if (!(container.kind === 219 /* ModuleBlock */ || container.kind === 248 /* SourceFile */)) { + if (!(container.kind === 222 /* ModuleBlock */ || container.kind === 251 /* SourceFile */)) { return undefined; } } else if (modifier === 115 /* AbstractKeyword */) { - if (!(container.kind === 214 /* ClassDeclaration */ || declaration.kind === 214 /* ClassDeclaration */)) { + if (!(container.kind === 217 /* ClassDeclaration */ || declaration.kind === 217 /* ClassDeclaration */)) { return undefined; } } @@ -46635,33 +50322,33 @@ var ts; var modifierFlag = getFlagFromModifier(modifier); var nodes; switch (container.kind) { - case 219 /* ModuleBlock */: - case 248 /* SourceFile */: + case 222 /* ModuleBlock */: + case 251 /* SourceFile */: // Container is either a class declaration or the declaration is a classDeclaration - if (modifierFlag & 256 /* Abstract */) { + if (modifierFlag & 128 /* Abstract */) { nodes = declaration.members.concat(declaration); } else { nodes = container.statements; } break; - case 144 /* Constructor */: + case 145 /* Constructor */: nodes = container.parameters.concat(container.parent.members); break; - case 214 /* ClassDeclaration */: - case 186 /* ClassExpression */: + case 217 /* ClassDeclaration */: + case 189 /* 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 */) { + if (modifierFlag & 56 /* AccessibilityModifier */) { var constructor = ts.forEach(container.members, function (member) { - return member.kind === 144 /* Constructor */ && member; + return member.kind === 145 /* Constructor */ && member; }); if (constructor) { nodes = nodes.concat(constructor.parameters); } } - else if (modifierFlag & 256 /* Abstract */) { + else if (modifierFlag & 128 /* Abstract */) { nodes = nodes.concat(container); } break; @@ -46677,19 +50364,19 @@ var ts; function getFlagFromModifier(modifier) { switch (modifier) { case 112 /* PublicKeyword */: - return 16 /* Public */; + return 8 /* Public */; case 110 /* PrivateKeyword */: - return 32 /* Private */; + return 16 /* Private */; case 111 /* ProtectedKeyword */: - return 64 /* Protected */; + return 32 /* Protected */; case 113 /* StaticKeyword */: - return 128 /* Static */; + return 64 /* Static */; case 82 /* ExportKeyword */: - return 1 /* Export */; + return 2 /* Export */; case 122 /* DeclareKeyword */: - return 2 /* Ambient */; + return 4 /* Ambient */; case 115 /* AbstractKeyword */: - return 256 /* Abstract */; + return 128 /* Abstract */; default: ts.Debug.fail(); } @@ -46708,8 +50395,8 @@ var ts; } function getGetAndSetOccurrences(accessorDeclaration) { var keywords = []; - tryPushAccessorKeyword(accessorDeclaration.symbol, 145 /* GetAccessor */); - tryPushAccessorKeyword(accessorDeclaration.symbol, 146 /* SetAccessor */); + tryPushAccessorKeyword(accessorDeclaration.symbol, 146 /* GetAccessor */); + tryPushAccessorKeyword(accessorDeclaration.symbol, 147 /* SetAccessor */); return ts.map(keywords, getHighlightSpanForNode); function tryPushAccessorKeyword(accessorSymbol, accessorKind) { var accessor = ts.getDeclarationOfKind(accessorSymbol, accessorKind); @@ -46732,7 +50419,7 @@ var ts; 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 */) { + if (loopNode.kind === 200 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 104 /* WhileKeyword */)) { @@ -46753,13 +50440,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 199 /* ForStatement */: - case 200 /* ForInStatement */: - case 201 /* ForOfStatement */: - case 197 /* DoStatement */: - case 198 /* WhileStatement */: + case 202 /* ForStatement */: + case 203 /* ForInStatement */: + case 204 /* ForOfStatement */: + case 200 /* DoStatement */: + case 201 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 206 /* SwitchStatement */: + case 209 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -46813,7 +50500,7 @@ var ts; 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 */))) { + if (!(func && hasKind(func.body, 195 /* Block */))) { return undefined; } var keywords = []; @@ -46829,7 +50516,7 @@ var ts; 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) { + while (hasKind(ifStatement.parent, 199 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { ifStatement = ifStatement.parent; } // Now traverse back down through the else branches, aggregating if/else keywords of if-statements. @@ -46842,7 +50529,7 @@ var ts; break; } } - if (!hasKind(ifStatement.elseStatement, 196 /* IfStatement */)) { + if (!hasKind(ifStatement.elseStatement, 199 /* IfStatement */)) { break; } ifStatement = ifStatement.elseStatement; @@ -46888,8 +50575,8 @@ var ts; return undefined; } var result = []; - for (var _i = 0; _i < documentHighlights.length; _i++) { - var entry = documentHighlights[_i]; + for (var _i = 0, documentHighlights_1 = documentHighlights; _i < documentHighlights_1.length; _i++) { + var entry = documentHighlights_1[_i]; for (var _a = 0, _b = entry.highlightSpans; _a < _b.length; _a++) { var highlightSpan = _b[_a]; result.push({ @@ -46907,8 +50594,8 @@ var ts; return undefined; } var referenceEntries = []; - for (var _i = 0; _i < referenceSymbols.length; _i++) { - var referenceSymbol = referenceSymbols[_i]; + for (var _i = 0, referenceSymbols_1 = referenceSymbols; _i < referenceSymbols_1.length; _i++) { + var referenceSymbol = referenceSymbols_1[_i]; ts.addRange(referenceEntries, referenceSymbol.references); } return referenceEntries; @@ -46918,11 +50605,11 @@ var ts; return convertReferences(referencedSymbols); } function getReferencesAtPosition(fileName, position) { - var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false); + 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); + 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; }); } @@ -46935,8 +50622,8 @@ var ts; } 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 && + // node.kind !== SyntaxKind.ThisKeyword && + // node.kind !== SyntaxKind.SuperKeyword && !isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && !isNameOfExternalModuleImportOrDeclaration(node)) { return undefined; @@ -46959,7 +50646,7 @@ var ts; return getLabelReferencesInNode(node.parent, node); } } - if (node.kind === 97 /* ThisKeyword */) { + if (node.kind === 97 /* ThisKeyword */ || node.kind === 162 /* ThisType */) { return getReferencesForThisKeyword(node, sourceFiles); } if (node.kind === 95 /* SuperKeyword */) { @@ -46993,11 +50680,11 @@ var ts; } else { var internedName = getInternedName(symbol, node, declarations); - for (var _i = 0; _i < sourceFiles.length; _i++) { - var sourceFile = sourceFiles[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = getNameTable(sourceFile); - if (ts.lookUp(nameTable, internedName)) { + if (ts.lookUp(nameTable, internedName) !== undefined) { result = result || []; getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex); } @@ -47020,10 +50707,8 @@ var ts; 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 isImportSpecifierSymbol(symbol) { + return (symbol.flags & 8388608 /* Alias */) && !!ts.getDeclarationOfKind(symbol, 229 /* ImportSpecifier */); } function getInternedName(symbol, location, declarations) { // If this is an export or import specifier it could have been renamed using the 'as' syntax. @@ -47049,14 +50734,14 @@ var ts; // 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 */)) { + if (valueDeclaration && (valueDeclaration.kind === 176 /* FunctionExpression */ || valueDeclaration.kind === 189 /* 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; }); + var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 16 /* Private */) ? d : undefined; }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 214 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 217 /* ClassDeclaration */); } } // If the symbol is an import we would like to find it if we are looking for what it imports. @@ -47069,11 +50754,11 @@ var ts; if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) { return undefined; } - var scope = undefined; + var scope; var declarations = symbol.getDeclarations(); if (declarations) { - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; var container = getContainerNode(declaration); if (!container) { return undefined; @@ -47082,7 +50767,7 @@ var ts; // Different declarations have different containers, bail out return undefined; } - if (container.kind === 248 /* SourceFile */ && !ts.isExternalModule(container)) { + if (container.kind === 251 /* 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; @@ -47181,7 +50866,7 @@ var ts; var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, container.getStart(), container.getEnd()); if (possiblePositions.length) { // Build the set of symbols to search for, initially it has only the current symbol - var searchSymbols = populateSearchSymbolSet(searchSymbol, searchLocation); + var searchSymbols_1 = populateSearchSymbolSet(searchSymbol, searchLocation); ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); @@ -47213,12 +50898,12 @@ var ts; if (referenceSymbol) { var referenceSymbolDeclaration = referenceSymbol.valueDeclaration; var shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(referenceSymbolDeclaration); - var relatedSymbol = getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation); + var relatedSymbol = getRelatedSymbol(searchSymbols_1, referenceSymbol, referenceLocation); if (relatedSymbol) { var referencedSymbol = getReferencedSymbol(relatedSymbol); referencedSymbol.references.push(getReferenceEntryFromNode(referenceLocation)); } - else if (!(referenceSymbol.flags & 67108864 /* Transient */) && searchSymbols.indexOf(shorthandValueSymbol) >= 0) { + else if (!(referenceSymbol.flags & 67108864 /* Transient */) && searchSymbols_1.indexOf(shorthandValueSymbol) >= 0) { var referencedSymbol = getReferencedSymbol(shorthandValueSymbol); referencedSymbol.references.push(getReferenceEntryFromNode(referenceSymbolDeclaration.name)); } @@ -47248,20 +50933,20 @@ var ts; } } function getReferencesForSuperKeyword(superKeyword) { - var searchSpaceNode = ts.getSuperContainer(superKeyword, /*includeFunctions*/ false); + var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false); if (!searchSpaceNode) { return undefined; } // Whether 'super' occurs in a static context within a class. - var staticFlag = 128 /* Static */; + var staticFlag = 64 /* 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 */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 145 /* Constructor */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -47277,11 +50962,11 @@ var ts; if (!node || node.kind !== 95 /* SuperKeyword */) { return; } - var container = ts.getSuperContainer(node, /*includeFunctions*/ false); + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ 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) { + if (container && (64 /* Static */ & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { references.push(getReferenceEntryFromNode(node)); } }); @@ -47291,29 +50976,29 @@ var ts; 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 */; + var staticFlag = 64 /* Static */; switch (searchSpaceNode.kind) { - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } // fall through - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: - case 144 /* Constructor */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: + case 145 /* Constructor */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: staticFlag &= searchSpaceNode.flags; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 248 /* SourceFile */: + case 251 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // Fall through - case 213 /* FunctionDeclaration */: - case 173 /* FunctionExpression */: + case 216 /* FunctionDeclaration */: + case 176 /* 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. @@ -47322,7 +51007,7 @@ var ts; } var references = []; var possiblePositions; - if (searchSpaceNode.kind === 248 /* SourceFile */) { + if (searchSpaceNode.kind === 251 /* SourceFile */) { ts.forEach(sourceFiles, function (sourceFile) { possiblePositions = getPossibleSymbolReferencePositions(sourceFile, "this", sourceFile.getStart(), sourceFile.getEnd()); getThisReferencesInFile(sourceFile, sourceFile, possiblePositions, references); @@ -47348,33 +51033,33 @@ var ts; ts.forEach(possiblePositions, function (position) { cancellationToken.throwIfCancellationRequested(); var node = ts.getTouchingWord(sourceFile, position); - if (!node || node.kind !== 97 /* ThisKeyword */) { + if (!node || (node.kind !== 97 /* ThisKeyword */ && node.kind !== 162 /* ThisType */)) { return; } var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); switch (searchSpaceNode.kind) { - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: + case 176 /* FunctionExpression */: + case 216 /* FunctionDeclaration */: if (searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { result.push(getReferenceEntryFromNode(node)); } break; - case 186 /* ClassExpression */: - case 214 /* ClassDeclaration */: + case 189 /* ClassExpression */: + case 217 /* 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) { + if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 64 /* Static */) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; - case 248 /* SourceFile */: - if (container.kind === 248 /* SourceFile */ && !ts.isExternalModule(container)) { + case 251 /* SourceFile */: + if (container.kind === 251 /* SourceFile */ && !ts.isExternalModule(container)) { result.push(getReferenceEntryFromNode(node)); } break; @@ -47386,9 +51071,17 @@ var ts; // 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)) { + if (isImportSpecifierSymbol(symbol)) { result.push(typeChecker.getAliasedSymbol(symbol)); } + // For export specifiers, the exported name can be refering to a local symbol, e.g.: + // import {a} from "mod"; + // export {a as somethingElse} + // We want the *local* declaration of 'a' as declared in the import, + // *not* as declared within "mod" (or farther) + if (location.parent.kind === 233 /* ExportSpecifier */) { + result.push(typeChecker.getExportSpecifierLocalTargetSymbol(location.parent)); + } // 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 @@ -47401,8 +51094,8 @@ var ts; * 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 }; + * const name = "Foo"; + * const 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. @@ -47412,6 +51105,14 @@ var ts; result.push(shorthandValueSymbol); } } + // If the symbol.valueDeclaration is a property parameter declaration, + // we should include both parameter declaration symbol and property declaration symbol + // Parameter Declaration symbol is only visible within function scope, so the symbol is stored in contructor.locals. + // Property Declaration symbol is a member of the class, so the symbol is stored in its class Declaration.symbol.members + if (symbol.valueDeclaration && symbol.valueDeclaration.kind === 139 /* Parameter */ && + ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { + result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); + } // 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) { @@ -47420,19 +51121,44 @@ var ts; } // 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); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ {}); } }); return result; } - function getPropertySymbolsFromBaseTypes(symbol, propertyName, result) { - if (symbol && symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + /** + * Find symbol of the given property-name and add the symbol to the given result array + * @param symbol a symbol to start searching for the given propertyName + * @param propertyName a name of property to serach for + * @param result an array of symbol of found property symbols + * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisitng of the same symbol. + * The value of previousIterationSymbol is undefined when the function is first called. + */ + function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache) { + if (!symbol) { + return; + } + // If the current symbol is the same as the previous-iteration symbol, we can just return the symbol that has already been visited + // This is particularly important for the following cases, so that we do not infinitely visit the same symbol. + // For example: + // interface C extends C { + // /*findRef*/propName: string; + // } + // The first time getPropertySymbolsFromBaseTypes is called when finding-all-references at propName, + // the symbol argument will be the symbol of an interface "C" and previousIterationSymbol is undefined, + // the function will add any found symbol of the property-name, then its sub-routine will call + // getPropertySymbolsFromBaseTypes again to walk up any base types to prevent revisiting already + // visited symbol, interface "C", the sub-routine will pass the current symbol as previousIterationSymbol. + if (ts.hasProperty(previousIterationSymbolsCache, symbol.name)) { + return; + } + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { ts.forEach(symbol.getDeclarations(), function (declaration) { - if (declaration.kind === 214 /* ClassDeclaration */) { + if (declaration.kind === 217 /* ClassDeclaration */) { getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); } - else if (declaration.kind === 215 /* InterfaceDeclaration */) { + else if (declaration.kind === 218 /* InterfaceDeclaration */) { ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); } }); @@ -47447,7 +51173,8 @@ var ts; result.push(propertySymbol); } // Visit the typeReference as well to see if it directly or indirectly use that property - getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result); + previousIterationSymbolsCache[symbol.name] = symbol; + getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache); } } } @@ -47458,12 +51185,22 @@ var ts; } // If the reference symbol is an alias, check if what it is aliasing is one of the search // symbols. - if (isImportOrExportSpecifierImportSymbol(referenceSymbol)) { + if (isImportSpecifierSymbol(referenceSymbol)) { var aliasedSymbol = typeChecker.getAliasedSymbol(referenceSymbol); if (searchSymbols.indexOf(aliasedSymbol) >= 0) { return aliasedSymbol; } } + // For export specifiers, it can be a local symbol, e.g. + // import {a} from "mod"; + // export {a as somethingElse} + // We want the local target of the export (i.e. the import symbol) and not the final target (i.e. "mod".a) + if (referenceLocation.parent.kind === 233 /* ExportSpecifier */) { + var aliasedSymbol = typeChecker.getExportSpecifierLocalTargetSymbol(referenceLocation.parent); + 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 @@ -47482,9 +51219,9 @@ var ts; // 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; }); + var result_5 = []; + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result_5, /*previousIterationSymbolsCache*/ {}); + return ts.forEach(result_5, function (s) { return searchSymbols.indexOf(s) >= 0 ? s : undefined; }); } return undefined; }); @@ -47493,28 +51230,28 @@ var ts; if (isNameOfPropertyAssignment(node)) { var objectLiteral = node.parent.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name_34 = node.text; + var name_37 = 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); + var unionProperty = contextualType.getProperty(name_37); if (unionProperty) { return [unionProperty]; } else { - var result_4 = []; + var result_6 = []; ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name_34); + var symbol = t.getProperty(name_37); if (symbol) { - result_4.push(symbol); + result_6.push(symbol); } }); - return result_4; + return result_6; } } else { - var symbol_1 = contextualType.getProperty(name_34); + var symbol_1 = contextualType.getProperty(name_37); if (symbol_1) { return [symbol_1]; } @@ -47532,7 +51269,7 @@ var ts; */ function getIntersectingMeaningFromDeclarations(meaning, declarations) { if (declarations) { - var lastIterationMeaning; + var lastIterationMeaning = void 0; 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 @@ -47540,8 +51277,8 @@ var ts; // 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]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; var declarationMeaning = getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -47572,10 +51309,10 @@ var ts; } var parent = node.parent; if (parent) { - if (parent.kind === 180 /* PostfixUnaryExpression */ || parent.kind === 179 /* PrefixUnaryExpression */) { + if (parent.kind === 183 /* PostfixUnaryExpression */ || parent.kind === 182 /* PrefixUnaryExpression */) { return true; } - else if (parent.kind === 181 /* BinaryExpression */ && parent.left === node) { + else if (parent.kind === 184 /* BinaryExpression */ && parent.left === node) { var operator = parent.operatorToken.kind; return 56 /* FirstAssignment */ <= operator && operator <= 68 /* LastAssignment */; } @@ -47587,9 +51324,6 @@ var ts; 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); @@ -47609,34 +51343,34 @@ var ts; } 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 */: + case 139 /* Parameter */: + case 214 /* VariableDeclaration */: + case 166 /* BindingElement */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: + case 248 /* PropertyAssignment */: + case 249 /* ShorthandPropertyAssignment */: + case 250 /* EnumMember */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 145 /* Constructor */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 216 /* FunctionDeclaration */: + case 176 /* FunctionExpression */: + case 177 /* ArrowFunction */: + case 247 /* CatchClause */: return 1 /* Value */; - case 137 /* TypeParameter */: - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: - case 155 /* TypeLiteral */: + case 138 /* TypeParameter */: + case 218 /* InterfaceDeclaration */: + case 219 /* TypeAliasDeclaration */: + case 156 /* TypeLiteral */: return 2 /* Type */; - case 214 /* ClassDeclaration */: - case 217 /* EnumDeclaration */: + case 217 /* ClassDeclaration */: + case 220 /* EnumDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 218 /* ModuleDeclaration */: - if (node.name.kind === 9 /* StringLiteral */) { + case 221 /* ModuleDeclaration */: + if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; } else if (ts.getModuleInstanceState(node) === 1 /* Instantiated */) { @@ -47645,27 +51379,27 @@ var ts; else { return 4 /* Namespace */; } - case 225 /* NamedImports */: - case 226 /* ImportSpecifier */: - case 221 /* ImportEqualsDeclaration */: - case 222 /* ImportDeclaration */: - case 227 /* ExportAssignment */: - case 228 /* ExportDeclaration */: + case 228 /* NamedImports */: + case 229 /* ImportSpecifier */: + case 224 /* ImportEqualsDeclaration */: + case 225 /* ImportDeclaration */: + case 230 /* ExportAssignment */: + case 231 /* ExportDeclaration */: return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; // An external module can be a Value - case 248 /* SourceFile */: + case 251 /* 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); + return node.parent.kind === 152 /* TypeReference */ || + (node.parent.kind === 191 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || + (node.kind === 97 /* ThisKeyword */ && !ts.isExpression(node)) || + node.kind === 162 /* ThisType */; } function isNamespaceReference(node) { return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); @@ -47673,32 +51407,32 @@ var ts; function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 166 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 166 /* PropertyAccessExpression */) { + if (root.parent.kind === 169 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 169 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 188 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 243 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 191 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 246 /* 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 (decl.kind === 217 /* ClassDeclaration */ && root.parent.parent.token === 106 /* ImplementsKeyword */) || + (decl.kind === 218 /* 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 */) { + if (root.parent.kind === 136 /* QualifiedName */) { + while (root.parent && root.parent.kind === 136 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 151 /* TypeReference */ && !isLastClause; + return root.parent.kind === 152 /* TypeReference */ && !isLastClause; } function isInRightSideOfImport(node) { - while (node.parent.kind === 135 /* QualifiedName */) { + while (node.parent.kind === 136 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -47708,15 +51442,15 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - if (node.parent.kind === 135 /* QualifiedName */ && + if (node.parent.kind === 136 /* QualifiedName */ && node.parent.right === node && - node.parent.parent.kind === 221 /* ImportEqualsDeclaration */) { + node.parent.parent.kind === 224 /* ImportEqualsDeclaration */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } return 4 /* Namespace */; } function getMeaningFromLocation(node) { - if (node.parent.kind === 227 /* ExportAssignment */) { + if (node.parent.kind === 230 /* ExportAssignment */) { return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; } else if (isInRightSideOfImport(node)) { @@ -47756,14 +51490,16 @@ var ts; return; } switch (node.kind) { - case 166 /* PropertyAccessExpression */: - case 135 /* QualifiedName */: + case 169 /* PropertyAccessExpression */: + case 136 /* QualifiedName */: case 9 /* StringLiteral */: + case 163 /* StringLiteralType */: case 84 /* FalseKeyword */: case 99 /* TrueKeyword */: case 93 /* NullKeyword */: case 95 /* SuperKeyword */: case 97 /* ThisKeyword */: + case 162 /* ThisType */: case 69 /* Identifier */: break; // Cant create the text span @@ -47780,7 +51516,7 @@ var ts; // 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 */ && + if (nodeForStartPos.parent.parent.kind === 221 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -47804,7 +51540,7 @@ var ts; } function getNavigationBarItems(fileName) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(sourceFile, host.getCompilationSettings()); } function getSemanticClassifications(fileName, span) { return convertClassifications(getEncodedSemanticClassifications(fileName, span)); @@ -47821,10 +51557,10 @@ var ts; // 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 */: + case 221 /* ModuleDeclaration */: + case 217 /* ClassDeclaration */: + case 218 /* InterfaceDeclaration */: + case 216 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } @@ -47878,7 +51614,7 @@ var ts; */ function hasValueSideModule(symbol) { return ts.forEach(symbol.declarations, function (declaration) { - return declaration.kind === 218 /* ModuleDeclaration */ && + return declaration.kind === 221 /* ModuleDeclaration */ && ts.getModuleInstanceState(declaration) === 1 /* Instantiated */; }); } @@ -47926,6 +51662,12 @@ var ts; case 16 /* typeAliasName */: return ClassificationTypeNames.typeAliasName; case 17 /* parameterName */: return ClassificationTypeNames.parameterName; case 18 /* docCommentTagName */: return ClassificationTypeNames.docCommentTagName; + case 19 /* jsxOpenTagName */: return ClassificationTypeNames.jsxOpenTagName; + case 20 /* jsxCloseTagName */: return ClassificationTypeNames.jsxCloseTagName; + case 21 /* jsxSelfClosingTagName */: return ClassificationTypeNames.jsxSelfClosingTagName; + case 22 /* jsxAttribute */: return ClassificationTypeNames.jsxAttribute; + case 23 /* jsxText */: return ClassificationTypeNames.jsxText; + case 24 /* jsxAttributeStringLiteralValue */: return ClassificationTypeNames.jsxAttributeStringLiteralValue; } } function convertClassifications(classifications) { @@ -47949,8 +51691,8 @@ var ts; 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 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 */ }; @@ -48033,16 +51775,16 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); pos = tag.tagName.end; switch (tag.kind) { - case 267 /* JSDocParameterTag */: + case 270 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 270 /* JSDocTemplateTag */: + case 273 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); break; - case 269 /* JSDocTypeTag */: + case 272 /* JSDocTypeTag */: processElement(tag.typeExpression); break; - case 268 /* JSDocReturnTag */: + case 271 /* JSDocReturnTag */: processElement(tag.typeExpression); break; } @@ -48079,7 +51821,8 @@ var ts; 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++) { + var i; + for (i = start; i < end; i++) { if (ts.isLineBreak(text.charCodeAt(i))) { break; } @@ -48099,19 +51842,53 @@ var ts; pushClassification(start, end - start, type); } } - function classifyToken(token) { - if (ts.nodeIsMissing(token)) { - return; + /** + * Returns true if node should be treated as classified and no further processing is required. + * False will mean that node is not classified and traverse routine should recurse into node contents. + */ + function tryClassifyNode(node) { + if (ts.nodeIsMissing(node)) { + return true; + } + var classifiedElementName = tryClassifyJsxElementName(node); + if (!ts.isToken(node) && node.kind !== 239 /* JsxText */ && classifiedElementName === undefined) { + return false; } - var tokenStart = classifyLeadingTriviaAndGetTokenStart(token); - var tokenWidth = token.end - tokenStart; + var tokenStart = node.kind === 239 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); + var tokenWidth = node.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { - var type = classifyTokenType(token.kind, token); + var type = classifiedElementName || classifyTokenType(node.kind, node); if (type) { pushClassification(tokenStart, tokenWidth, type); } } + return true; + } + function tryClassifyJsxElementName(token) { + switch (token.parent && token.parent.kind) { + case 238 /* JsxOpeningElement */: + if (token.parent.tagName === token) { + return 19 /* jsxOpenTagName */; + } + break; + case 240 /* JsxClosingElement */: + if (token.parent.tagName === token) { + return 20 /* jsxCloseTagName */; + } + break; + case 237 /* JsxSelfClosingElement */: + if (token.parent.tagName === token) { + return 21 /* jsxSelfClosingTagName */; + } + break; + case 241 /* JsxAttribute */: + if (token.parent.name === token) { + return 22 /* jsxAttribute */; + } + break; + } + return undefined; } // 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 @@ -48133,16 +51910,17 @@ var ts; 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 */) { + if (token.parent.kind === 214 /* VariableDeclaration */ || + token.parent.kind === 142 /* PropertyDeclaration */ || + token.parent.kind === 139 /* Parameter */ || + token.parent.kind === 241 /* JsxAttribute */) { return 5 /* operator */; } } - if (token.parent.kind === 181 /* BinaryExpression */ || - token.parent.kind === 179 /* PrefixUnaryExpression */ || - token.parent.kind === 180 /* PostfixUnaryExpression */ || - token.parent.kind === 182 /* ConditionalExpression */) { + if (token.parent.kind === 184 /* BinaryExpression */ || + token.parent.kind === 182 /* PrefixUnaryExpression */ || + token.parent.kind === 183 /* PostfixUnaryExpression */ || + token.parent.kind === 185 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -48151,8 +51929,8 @@ var ts; else if (tokenKind === 8 /* NumericLiteral */) { return 4 /* numericLiteral */; } - else if (tokenKind === 9 /* StringLiteral */) { - return 6 /* stringLiteral */; + else if (tokenKind === 9 /* StringLiteral */ || tokenKind === 163 /* StringLiteralType */) { + return token.parent.kind === 241 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 10 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -48162,35 +51940,38 @@ var ts; // TODO (drosen): we should *also* get another classification type for these literals. return 6 /* stringLiteral */; } + else if (tokenKind === 239 /* JsxText */) { + return 23 /* jsxText */; + } else if (tokenKind === 69 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 214 /* ClassDeclaration */: + case 217 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; - case 137 /* TypeParameter */: + case 138 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; - case 215 /* InterfaceDeclaration */: + case 218 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 217 /* EnumDeclaration */: + case 220 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 218 /* ModuleDeclaration */: + case 221 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; - case 138 /* Parameter */: + case 139 /* Parameter */: if (token.parent.name === token) { return 17 /* parameterName */; } @@ -48210,10 +51991,7 @@ var ts; 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 { + if (!tryClassifyNode(child)) { // Recurse into our child nodes. processElement(child); } @@ -48236,8 +52014,8 @@ var ts; if (matchKind) { var parentElement = token.parent; var childNodes = parentElement.getChildren(sourceFile); - for (var _i = 0; _i < childNodes.length; _i++) { - var current = childNodes[_i]; + for (var _i = 0, childNodes_1 = childNodes; _i < childNodes_1.length; _i++) { + var current = childNodes_1[_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)); @@ -48319,7 +52097,6 @@ var ts; * 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)) { @@ -48338,19 +52115,19 @@ var ts; 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 */: + case 216 /* FunctionDeclaration */: + case 144 /* MethodDeclaration */: + case 145 /* Constructor */: + case 217 /* ClassDeclaration */: + case 196 /* VariableStatement */: break findOwner; - case 248 /* SourceFile */: + case 251 /* SourceFile */: return undefined; - case 218 /* ModuleDeclaration */: + case 221 /* 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 */) { + if (commentOwner.parent.kind === 221 /* ModuleDeclaration */) { return undefined; } break findOwner; @@ -48363,8 +52140,7 @@ var ts; 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 newLine = ts.getNewLineOrDefaultFromHost(host); var docParams = ""; for (var i = 0, numParams = parameters.length; i < numParams; i++) { var currentName = parameters[i].name; @@ -48392,7 +52168,7 @@ var ts; if (ts.isFunctionLike(commentOwner)) { return commentOwner.parameters; } - if (commentOwner.kind === 193 /* VariableStatement */) { + if (commentOwner.kind === 196 /* VariableStatement */) { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; if (varDeclarations.length === 1 && varDeclarations[0].initializer) { @@ -48410,17 +52186,17 @@ var ts; * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. */ function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 172 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 175 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 173 /* FunctionExpression */: - case 174 /* ArrowFunction */: + case 176 /* FunctionExpression */: + case 177 /* ArrowFunction */: return rightHandSide.parameters; - case 186 /* ClassExpression */: + case 189 /* ClassExpression */: for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 144 /* Constructor */) { + if (member.kind === 145 /* Constructor */) { return member.parameters; } } @@ -48442,7 +52218,7 @@ var ts; var result = []; if (descriptors.length > 0) { var regExp = getTodoCommentsRegExp(); - var matchArray; + var matchArray = void 0; 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: @@ -48566,13 +52342,18 @@ var ts; if (declarations && declarations.length > 0) { // Disallow rename for elements that are defined in the standard TypeScript library. var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); + var canonicalDefaultLibName = getCanonicalFileName(ts.normalizePath(defaultLibFileName)); 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)); + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var current = declarations_10[_i]; + var sourceFile_3 = current.getSourceFile(); + // TODO (drosen): When is there no source file? + if (!sourceFile_3) { + continue; + } + var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_3.fileName)); + if (canonicalName === canonicalDefaultLibName) { + return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library)); } } } @@ -48581,10 +52362,10 @@ var ts; if (kind) { return { canRename: true, - localizedErrorMessage: undefined, + kind: kind, displayName: displayName, + localizedErrorMessage: undefined, fullDisplayName: typeChecker.getFullyQualifiedName(symbol), - kind: kind, kindModifiers: getSymbolModifiers(symbol), triggerSpan: ts.createTextSpan(node.getStart(), node.getWidth()) }; @@ -48592,7 +52373,7 @@ var ts; } } } - return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_this_element.key)); + return getRenameInfoError(ts.getLocaleSpecificMessage(ts.Diagnostics.You_cannot_rename_this_element)); function getRenameInfoError(localizedErrorMessage) { return { canRename: false, @@ -48660,7 +52441,7 @@ var ts; function walk(node) { switch (node.kind) { case 69 /* Identifier */: - nameTable[node.text] = node.text; + nameTable[node.text] = nameTable[node.text] === undefined ? node.pos : -1; break; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: @@ -48669,9 +52450,9 @@ var ts; // 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 */ || + node.parent.kind === 235 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node)) { - nameTable[node.text] = node.text; + nameTable[node.text] = nameTable[node.text] === undefined ? node.pos : -1; } break; default: @@ -48682,7 +52463,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 167 /* ElementAccessExpression */ && + node.parent.kind === 170 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /// Classifier @@ -48811,7 +52592,7 @@ var ts; // (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; + text = "\"\\\n" + text; offset = 3; break; case 2 /* InSingleQuoteStringLiteral */: @@ -48941,7 +52722,7 @@ var ts; var end = scanner.getTextPos(); addResult(start, end, classFromKind(token)); if (end >= text.length) { - if (token === 9 /* StringLiteral */) { + if (token === 9 /* StringLiteral */ || token === 163 /* StringLiteralType */) { // Check to see if we finished up on a multiline string literal. var tokenText = scanner.getTokenText(); if (scanner.isUnterminated()) { @@ -49064,7 +52845,7 @@ var ts; } } function isKeyword(token) { - return token >= 70 /* FirstKeyword */ && token <= 134 /* LastKeyword */; + return token >= 70 /* FirstKeyword */ && token <= 135 /* LastKeyword */; } function classFromKind(token) { if (isKeyword(token)) { @@ -49080,6 +52861,7 @@ var ts; case 8 /* NumericLiteral */: return 4 /* numericLiteral */; case 9 /* StringLiteral */: + case 163 /* StringLiteralType */: return 6 /* stringLiteral */; case 10 /* RegularExpressionLiteral */: return 7 /* regularExpressionLiteral */; @@ -49119,18 +52901,8 @@ var ts; 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; - }, + getNodeConstructor: function () { return NodeObject; }, + getSourceFileConstructor: function () { return SourceFileObject; }, getSymbolConstructor: function () { return SymbolObject; }, getTypeConstructor: function () { return TypeObject; }, getSignatureConstructor: function () { return SignatureObject; } @@ -49151,12 +52923,12 @@ var ts; */ function spanInSourceFileAtLocation(sourceFile, position) { // Cannot set breakpoint in dts file - if (sourceFile.flags & 8192 /* DeclarationFile */) { + if (sourceFile.flags & 4096 /* DeclarationFile */) { return undefined; } var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; - if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart()).line > lineOfPosition) { + if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { // Get previous token if the token is returned starts on new line // eg: let x =10; |--- cursor is here // let y = 10; @@ -49175,14 +52947,23 @@ var ts; // 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()); + var start = startNode.decorators ? + ts.skipTrivia(sourceFile.text, startNode.decorators.end) : + startNode.getStart(sourceFile); + return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); + } + function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) { + return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent)); } function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { - if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart()).line) { + if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) { return spanInNode(node); } return spanInNode(otherwiseOnNode); } + function spanInNodeArray(nodeArray) { + return ts.createTextSpanFromBounds(ts.skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end); + } function spanInPreviousNode(node) { return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); } @@ -49191,126 +52972,114 @@ var ts; } 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 */: + case 196 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 211 /* VariableDeclaration */: - case 141 /* PropertyDeclaration */: - case 140 /* PropertySignature */: + case 214 /* VariableDeclaration */: + case 142 /* PropertyDeclaration */: + case 141 /* PropertySignature */: return spanInVariableDeclaration(node); - case 138 /* Parameter */: + case 139 /* 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 */: + case 216 /* FunctionDeclaration */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 145 /* Constructor */: + case 176 /* FunctionExpression */: + case 177 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 192 /* Block */: + case 195 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // Fall through - case 219 /* ModuleBlock */: + case 222 /* ModuleBlock */: return spanInBlock(node); - case 244 /* CatchClause */: + case 247 /* CatchClause */: return spanInBlock(node.block); - case 195 /* ExpressionStatement */: + case 198 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 204 /* ReturnStatement */: + case 207 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 198 /* WhileStatement */: + case 201 /* WhileStatement */: // Span on while(...) - return textSpan(node, ts.findNextToken(node.expression, node)); - case 197 /* DoStatement */: + return textSpanEndingAtNextToken(node, node.expression); + case 200 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 210 /* DebuggerStatement */: + case 213 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 196 /* IfStatement */: + case 199 /* IfStatement */: // set on if(..) span - return textSpan(node, ts.findNextToken(node.expression, node)); - case 207 /* LabeledStatement */: + return textSpanEndingAtNextToken(node, node.expression); + case 210 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 203 /* BreakStatement */: - case 202 /* ContinueStatement */: + case 206 /* BreakStatement */: + case 205 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 199 /* ForStatement */: + case 202 /* 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 */: + case 203 /* ForInStatement */: + // span of for (a in ...) + return textSpanEndingAtNextToken(node, node.expression); + case 204 /* ForOfStatement */: + // span in initializer + return spanInInitializerOfForLike(node); + case 209 /* SwitchStatement */: // span on switch(...) - return textSpan(node, ts.findNextToken(node.expression, node)); - case 241 /* CaseClause */: - case 242 /* DefaultClause */: + return textSpanEndingAtNextToken(node, node.expression); + case 244 /* CaseClause */: + case 245 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 209 /* TryStatement */: + case 212 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 208 /* ThrowStatement */: + case 211 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 227 /* ExportAssignment */: + case 230 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 221 /* ImportEqualsDeclaration */: + case 224 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 222 /* ImportDeclaration */: + case 225 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 228 /* ExportDeclaration */: + case 231 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 218 /* ModuleDeclaration */: + case 221 /* 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 */: + case 217 /* ClassDeclaration */: + case 220 /* EnumDeclaration */: + case 250 /* EnumMember */: + case 166 /* BindingElement */: // span on complete node return textSpan(node); - case 205 /* WithStatement */: + case 208 /* WithStatement */: // span in statement return spanInNode(node.statement); + case 140 /* Decorator */: + return spanInNodeArray(node.parent.decorators); + case 164 /* ObjectBindingPattern */: + case 165 /* ArrayBindingPattern */: + return spanInBindingPattern(node); // No breakpoint in interface, type alias - case 215 /* InterfaceDeclaration */: - case 216 /* TypeAliasDeclaration */: + case 218 /* InterfaceDeclaration */: + case 219 /* TypeAliasDeclaration */: return undefined; // Tokens: case 23 /* SemicolonToken */: @@ -49322,6 +53091,8 @@ var ts; return spanInOpenBraceToken(node); case 16 /* CloseBraceToken */: return spanInCloseBraceToken(node); + case 20 /* CloseBracketToken */: + return spanInCloseBracketToken(node); case 17 /* OpenParenToken */: return spanInOpenParenToken(node); case 18 /* CloseParenToken */: @@ -49338,67 +53109,155 @@ var ts; case 72 /* CatchKeyword */: case 85 /* FinallyKeyword */: return spanInNextNode(node); + case 135 /* OfKeyword */: + return spanInOfKeyword(node); default: + // Destructuring pattern in destructuring assignment + // [a, b, c] of + // [a, b, c] = expression + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); + } + // Set breakpoint on identifier element of destructuring pattern + // a or ...c or d: x from + // [a, b, ...c] or { a, b } or { d: x } from destructuring pattern + if ((node.kind === 69 /* Identifier */ || + node.kind == 188 /* SpreadElementExpression */ || + node.kind === 248 /* PropertyAssignment */ || + node.kind === 249 /* ShorthandPropertyAssignment */) && + ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + return textSpan(node); + } + if (node.kind === 184 /* BinaryExpression */) { + var binaryExpression = node; + // Set breakpoint in destructuring pattern if its destructuring assignment + // [a, b, c] or {a, b, c} of + // [a, b, c] = expression or + // {a, b, c} = expression + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left)) { + return spanInArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left); + } + if (binaryExpression.operatorToken.kind === 56 /* EqualsToken */ && + ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.parent)) { + // Set breakpoint on assignment expression element of destructuring pattern + // a = expression of + // [a = expression, b, c] = someExpression or + // { a = expression, b, c } = someExpression + return textSpan(node); + } + if (binaryExpression.operatorToken.kind === 24 /* CommaToken */) { + return spanInNode(binaryExpression.left); + } + } + if (ts.isExpression(node)) { + switch (node.parent.kind) { + case 200 /* DoStatement */: + // Set span as if on while keyword + return spanInPreviousNode(node); + case 140 /* Decorator */: + // Set breakpoint on the decorator emit + return spanInNode(node.parent); + case 202 /* ForStatement */: + case 204 /* ForOfStatement */: + return textSpan(node); + case 184 /* BinaryExpression */: + if (node.parent.operatorToken.kind === 24 /* CommaToken */) { + // if this is comma expression, the breakpoint is possible in this expression + return textSpan(node); + } + break; + case 177 /* ArrowFunction */: + if (node.parent.body === node) { + // If this is body of arrow function, it is allowed to have the breakpoint + return textSpan(node); + } + break; + } + } // If this is name of property assignment, set breakpoint in the initializer - if (node.parent.kind === 245 /* PropertyAssignment */ && node.parent.name === node) { + if (node.parent.kind === 248 /* PropertyAssignment */ && + node.parent.name === node && + !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { 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); + if (node.parent.kind === 174 /* TypeAssertionExpression */ && node.parent.type === node) { + return spanInNextNode(node.parent.type); } // return type of function go to previous token if (ts.isFunctionLike(node.parent) && node.parent.type === node) { return spanInPreviousNode(node); } + // initializer of variable/parameter declaration go to previous node + if ((node.parent.kind === 214 /* VariableDeclaration */ || + node.parent.kind === 139 /* Parameter */)) { + var paramOrVarDecl = node.parent; + if (paramOrVarDecl.initializer === node || + paramOrVarDecl.type === node || + ts.isAssignmentOperator(node.kind)) { + return spanInPreviousNode(node); + } + } + if (node.parent.kind === 184 /* BinaryExpression */) { + var binaryExpression = node.parent; + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) && + (binaryExpression.right === node || + binaryExpression.operatorToken === node)) { + // If initializer of destructuring assignment move to previous token + return spanInPreviousNode(node); + } + } // Default go to parent to set the breakpoint return spanInNode(node.parent); } } + function textSpanFromVariableDeclaration(variableDeclaration) { + var declarations = variableDeclaration.parent.declarations; + if (declarations && declarations[0] === variableDeclaration) { + // First declaration - include let keyword + return textSpan(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration); + } + else { + // Span only on this declaration + return textSpan(variableDeclaration); + } + } 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 */) { + if (variableDeclaration.parent.parent.kind === 203 /* ForInStatement */) { 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); - } + // If this is a destructuring pattern set breakpoint in binding pattern + if (ts.isBindingPattern(variableDeclaration.name)) { + return spanInBindingPattern(variableDeclaration.name); } - else if (declarations && declarations[0] !== variableDeclaration) { + // Breakpoint is possible in variableDeclaration only if there is initialization + // or its declaration from 'for of' + if (variableDeclaration.initializer || + (variableDeclaration.flags & 2 /* Export */) || + variableDeclaration.parent.parent.kind === 204 /* ForOfStatement */) { + return textSpanFromVariableDeclaration(variableDeclaration); + } + var declarations = variableDeclaration.parent.declarations; + 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]); + // Because the variable declaration may be binding pattern and + // we would like to set breakpoint in last binding element if thats the case, + // use preceding token instead + return spanInNode(ts.findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent)); } } 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 */); + !!(parameter.flags & 8 /* Public */) || !!(parameter.flags & 16 /* Private */); } function spanInParameterDeclaration(parameter) { - if (canHaveSpanInParameterDeclaration(parameter)) { + if (ts.isBindingPattern(parameter.name)) { + // set breakpoint in binding pattern + return spanInBindingPattern(parameter.name); + } + else if (canHaveSpanInParameterDeclaration(parameter)) { return textSpan(parameter); } else { @@ -49415,8 +53274,8 @@ var ts; } } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { - return !!(functionDeclaration.flags & 1 /* Export */) || - (functionDeclaration.parent.kind === 214 /* ClassDeclaration */ && functionDeclaration.kind !== 144 /* Constructor */); + return !!(functionDeclaration.flags & 2 /* Export */) || + (functionDeclaration.parent.kind === 217 /* ClassDeclaration */ && functionDeclaration.kind !== 145 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -49439,34 +53298,39 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 218 /* ModuleDeclaration */: + case 221 /* 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 */: + case 201 /* WhileStatement */: + case 199 /* IfStatement */: + case 203 /* ForInStatement */: 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 */: + case 202 /* ForStatement */: + case 204 /* ForOfStatement */: 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 spanInInitializerOfForLike(forLikeStaement) { + if (forLikeStaement.initializer.kind === 215 /* VariableDeclarationList */) { + // declaration list, set breakpoint in first declaration + var variableDeclarationList = forLikeStaement.initializer; + if (variableDeclarationList.declarations.length > 0) { + return spanInNode(variableDeclarationList.declarations[0]); + } + } + else { + // Expression - set breakpoint in it + return spanInNode(forLikeStaement.initializer); + } + } 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); - } + return spanInInitializerOfForLike(forStatement); } if (forStatement.condition) { return textSpan(forStatement.condition); @@ -49475,16 +53339,44 @@ var ts; return textSpan(forStatement.incrementor); } } + function spanInBindingPattern(bindingPattern) { + // Set breakpoint in first binding element + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 190 /* OmittedExpression */ ? element : undefined; }); + if (firstBindingElement) { + return spanInNode(firstBindingElement); + } + // Empty binding pattern of binding element, set breakpoint on binding element + if (bindingPattern.parent.kind === 166 /* BindingElement */) { + return textSpan(bindingPattern.parent); + } + // Variable declaration is used as the span + return textSpanFromVariableDeclaration(bindingPattern.parent); + } + function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { + ts.Debug.assert(node.kind !== 165 /* ArrayBindingPattern */ && node.kind !== 164 /* ObjectBindingPattern */); + var elements = node.kind === 167 /* ArrayLiteralExpression */ ? + node.elements : + node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 190 /* OmittedExpression */ ? element : undefined; }); + if (firstBindingElement) { + return spanInNode(firstBindingElement); + } + // Could be ArrayLiteral from destructuring assignment or + // just nested element in another destructuring assignment + // set breakpoint on assignment when parent is destructuring assignment + // Otherwise set breakpoint for this element + return textSpan(node.parent.kind === 184 /* BinaryExpression */ ? node.parent : node); + } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 217 /* EnumDeclaration */: + case 220 /* 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 */: + case 217 /* 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 */: + case 223 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -49492,25 +53384,24 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 219 /* ModuleBlock */: + case 222 /* 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 */: + case 220 /* EnumDeclaration */: + case 217 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 192 /* Block */: + case 195 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // fall through. - case 244 /* CatchClause */: + case 247 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - ; - case 220 /* CaseBlock */: + case 223 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -49518,58 +53409,99 @@ var ts; return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; + case 164 /* ObjectBindingPattern */: + // Breakpoint in last binding element or binding pattern if it contains no elements + var bindingPattern = node.parent; + return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); // Default to parent node default: + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Breakpoint in last binding element or binding pattern if it contains no elements + var objectLiteral = node.parent; + return textSpan(ts.lastOrUndefined(objectLiteral.properties) || objectLiteral); + } + return spanInNode(node.parent); + } + } + function spanInCloseBracketToken(node) { + switch (node.parent.kind) { + case 165 /* ArrayBindingPattern */: + // Breakpoint in last binding element or binding pattern if it contains no elements + var bindingPattern = node.parent; + return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); + default: + if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + // Breakpoint in last binding element or binding pattern if it contains no elements + var arrayLiteral = node.parent; + return textSpan(ts.lastOrUndefined(arrayLiteral.elements) || arrayLiteral); + } + // Default to parent node return spanInNode(node.parent); } } function spanInOpenParenToken(node) { - if (node.parent.kind === 197 /* DoStatement */) { - // Go to while keyword and do action instead + if (node.parent.kind === 200 /* DoStatement */ || + node.parent.kind === 171 /* CallExpression */ || + node.parent.kind === 172 /* NewExpression */) { return spanInPreviousNode(node); } + if (node.parent.kind === 175 /* ParenthesizedExpression */) { + return spanInNextNode(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 */: + case 176 /* FunctionExpression */: + case 216 /* FunctionDeclaration */: + case 177 /* ArrowFunction */: + case 144 /* MethodDeclaration */: + case 143 /* MethodSignature */: + case 146 /* GetAccessor */: + case 147 /* SetAccessor */: + case 145 /* Constructor */: + case 201 /* WhileStatement */: + case 200 /* DoStatement */: + case 202 /* ForStatement */: + case 204 /* ForOfStatement */: + case 171 /* CallExpression */: + case 172 /* NewExpression */: + case 175 /* ParenthesizedExpression */: 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 */) { + if (ts.isFunctionLike(node.parent) || + node.parent.kind === 248 /* PropertyAssignment */ || + node.parent.kind === 139 /* Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 171 /* TypeAssertionExpression */) { - return spanInNode(node.parent.expression); + if (node.parent.kind === 174 /* TypeAssertionExpression */) { + return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 197 /* DoStatement */) { + if (node.parent.kind === 200 /* DoStatement */) { // Set span on while expression - return textSpan(node, ts.findNextToken(node.parent.expression, node.parent)); + return textSpanEndingAtNextToken(node, node.parent.expression); + } + // Default to parent node + return spanInNode(node.parent); + } + function spanInOfKeyword(node) { + if (node.parent.kind === 204 /* ForOfStatement */) { + // set using next token + return spanInNextNode(node); } // Default to parent node return spanInNode(node.parent); @@ -49596,6 +53528,9 @@ var ts; /// /* @internal */ var debugObjectHost = this; +// We need to use 'null' to interface with the managed side. +/* tslint:disable:no-null */ +/* tslint:disable:no-in-operator */ /* @internal */ var ts; (function (ts) { @@ -49607,7 +53542,6 @@ var ts; var ScriptSnapshotShimAdapter = (function () { function ScriptSnapshotShimAdapter(scriptSnapshotShim) { this.scriptSnapshotShim = scriptSnapshotShim; - this.lineStartPositions = null; } ScriptSnapshotShimAdapter.prototype.getText = function (start, end) { return this.scriptSnapshotShim.getText(start, end); @@ -49633,7 +53567,7 @@ var ts; } }; return ScriptSnapshotShimAdapter; - })(); + }()); var LanguageServiceShimHostAdapter = (function () { function LanguageServiceShimHostAdapter(shimHost) { var _this = this; @@ -49651,6 +53585,9 @@ var ts; }); }; } + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } } LanguageServiceShimHostAdapter.prototype.log = function (s) { if (this.loggingEnabled) { @@ -49680,7 +53617,6 @@ var ts; // TODO: should this be '==='? if (settingsJson == null || settingsJson == "") { throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings"); - return null; } return JSON.parse(settingsJson); }; @@ -49689,11 +53625,6 @@ var ts; 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); }; @@ -49721,17 +53652,10 @@ var ts; 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 this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; return LanguageServiceShimHostAdapter; - })(); + }()); ts.LanguageServiceShimHostAdapter = LanguageServiceShimHostAdapter; /** A cancellation that throttles calls to the host */ var ThrottledCancellationToken = (function () { @@ -49753,23 +53677,17 @@ var ts; return false; }; return ThrottledCancellationToken; - })(); + }()); var CoreServicesShimHostAdapter = (function () { function CoreServicesShimHostAdapter(shimHost) { + var _this = this; this.shimHost = shimHost; + if ("directoryExists" in this.shimHost) { + this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; + } } 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); - } + var encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); return JSON.parse(encoded); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { @@ -49779,18 +53697,19 @@ var ts; return this.shimHost.readFile(fileName); }; return CoreServicesShimHostAdapter; - })(); + }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; function simpleForwardCall(logger, actionDescription, action, logPerformance) { + var start; if (logPerformance) { logger.log(actionDescription); - var start = Date.now(); + start = Date.now(); } var result = action(); if (logPerformance) { var end = Date.now(); logger.log(actionDescription + " completed in " + (end - start) + " msec"); - if (typeof (result) === "string") { + if (typeof result === "string") { var str = result; if (str.length > 128) { str = str.substring(0, 128) + "..."; @@ -49823,7 +53742,7 @@ var ts; this.factory.unregisterShim(this); }; return ShimBase; - })(); + }()); function realizeDiagnostics(diagnostics, newLine) { return diagnostics.map(function (d) { return realizeDiagnostic(d, newLine); }); } @@ -49872,9 +53791,7 @@ var ts; * Update the list of scripts known to the compiler */ LanguageServiceShimObject.prototype.refresh = function (throwOnError) { - this.forwardJSONCall("refresh(" + throwOnError + ")", function () { - return null; - }); + this.forwardJSONCall("refresh(" + throwOnError + ")", function () { return null; }); }; LanguageServiceShimObject.prototype.cleanupSemanticCache = function () { var _this = this; @@ -49889,33 +53806,25 @@ var ts; }; 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; - }); + return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); }); }; 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; - }); + return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); }); }; 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))); - }); + return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { 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))); - }); + return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", + // directly serialize the spans out to a string. This is much faster to decode + // on the managed side versus a full JSON array. + function () { return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); }); }; LanguageServiceShimObject.prototype.getSyntacticDiagnostics = function (fileName) { var _this = this; @@ -49945,10 +53854,7 @@ var ts; */ 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; - }); + return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getQuickInfoAtPosition(fileName, position); }); }; /// NAMEORDOTTEDNAMESPAN /** @@ -49957,10 +53863,7 @@ var ts; */ 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; - }); + return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { return _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); }); }; /** * STATEMENTSPAN @@ -49968,18 +53871,12 @@ var ts; */ 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; - }); + return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); }); }; /// 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; - }); + return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position); }); }; /// GOTO DEFINITION /** @@ -49988,9 +53885,7 @@ var ts; */ LanguageServiceShimObject.prototype.getDefinitionAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getDefinitionAtPosition(fileName, position); - }); + return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); }); }; /// GOTO Type /** @@ -49999,29 +53894,20 @@ var ts; */ LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getTypeDefinitionAtPosition(fileName, position); - }); + 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); - }); + 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); - }); + 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; - }); + return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBraceMatchingAtPosition(fileName, position); }); }; /// GET SMART INDENT LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options /*Services.EditorOptions*/) { @@ -50034,21 +53920,15 @@ var ts; /// GET REFERENCES LanguageServiceShimObject.prototype.getReferencesAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { - return _this.languageService.getReferencesAtPosition(fileName, position); - }); + 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); - }); + 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); - }); + return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getOccurrencesAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getDocumentHighlights = function (fileName, position, filesToSearch) { var _this = this; @@ -50067,41 +53947,32 @@ var ts; */ 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; - }); + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position); }); }; /** 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; - }); + return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { return _this.languageService.getCompletionEntryDetails(fileName, position, entryName); }); }; 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; + return _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); }); }; 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; + return _this.languageService.getFormattingEditsForDocument(fileName, localOptions); }); }; 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; + return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); }); }; LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position) { @@ -50112,45 +53983,27 @@ var ts; /** 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; - }); + return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount); }); }; LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) { var _this = this; - return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { - var items = _this.languageService.getNavigationBarItems(fileName); - return items; - }); + return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; - return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { - var items = _this.languageService.getOutliningSpans(fileName); - return items; - }); + return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); }; 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; - }); + return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { return _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); }); }; /// 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 this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { return _this.languageService.getEmitOutput(fileName); }); }; return LanguageServiceShimObject; - })(ShimBase); + }(ShimBase)); function convertClassifications(classifications) { return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState }; } @@ -50169,17 +54022,17 @@ var ts; /// 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"; + for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) { + var item = _a[_i]; + result += item.length + "\n"; + result += item.classification + "\n"; } result += classification.finalLexState; return result; }; return ClassifierShimObject; - })(ShimBase); + }(ShimBase)); var CoreServicesShimObject = (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { @@ -50204,7 +54057,8 @@ var ts; }; CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) { return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { - var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength())); + // for now treat files as JavaScript + var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), /* readImportFiles */ true, /* detectJavaScriptImports */ true); var convertResult = { referencedFiles: [], importedFiles: [], @@ -50237,24 +54091,23 @@ var ts; return { options: {}, files: [], - errors: [realizeDiagnostic(result.error, '\r\n')] + errors: [realizeDiagnostic(result.error, "\r\n")] }; } - var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(ts.normalizeSlashes(fileName))); + var normalizedFileName = ts.normalizeSlashes(fileName); + var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); return { options: configFile.options, files: configFile.fileNames, - errors: realizeDiagnostics(configFile.errors, '\r\n') + errors: realizeDiagnostics(configFile.errors, "\r\n") }; }); }; CoreServicesShimObject.prototype.getDefaultCompilationSettings = function () { - return this.forwardJSONCall("getDefaultCompilationSettings()", function () { - return ts.getDefaultCompilerOptions(); - }); + return this.forwardJSONCall("getDefaultCompilationSettings()", function () { return ts.getDefaultCompilerOptions(); }); }; return CoreServicesShimObject; - })(ShimBase); + }(ShimBase)); var TypeScriptServicesFactory = (function () { function TypeScriptServicesFactory() { this._shims = []; @@ -50268,7 +54121,7 @@ var ts; TypeScriptServicesFactory.prototype.createLanguageServiceShim = function (host) { try { if (this.documentRegistry === undefined) { - this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var hostAdapter = new LanguageServiceShimHostAdapter(host); var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry); @@ -50301,7 +54154,7 @@ var ts; TypeScriptServicesFactory.prototype.close = function () { // Forget all the registered shims this._shims = []; - this.documentRegistry = ts.createDocumentRegistry(); + this.documentRegistry = undefined; }; TypeScriptServicesFactory.prototype.registerShim = function (shim) { this._shims.push(shim); @@ -50316,12 +54169,14 @@ var ts; throw new Error("Invalid operation"); }; return TypeScriptServicesFactory; - })(); + }()); ts.TypeScriptServicesFactory = TypeScriptServicesFactory; if (typeof module !== "undefined" && module.exports) { module.exports = ts; } })(ts || (ts = {})); +/* tslint:enable:no-in-operator */ +/* tslint:enable:no-null */ /// TODO: this is used by VS, clean this up on both sides of the interface /* @internal */ var TypeScript; @@ -50331,5 +54186,9 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); +/* tslint:disable:no-unused-variable */ +// 'toolsVersion' gets consumed by the managed side, so it's not unused. +// TODO: it should be moved into a namespace though. /* @internal */ -var toolsVersion = "1.7"; +var toolsVersion = "1.8"; +/* tslint:enable:no-unused-variable */ diff --git a/testapp/package.json b/testapp/package.json index 1af59463d..470669b75 100644 --- a/testapp/package.json +++ b/testapp/package.json @@ -10,13 +10,13 @@ "postinstall": "typings install" }, "dependencies": { - "angular2": "2.0.0-beta.8", + "angular2": "2.0.0-beta.14", "systemjs": "0.19.22", "es6-promise": "^3.0.2", - "es6-shim": "^0.33.3", + "es6-shim": "^0.35.0", "reflect-metadata": "0.1.2", "rxjs": "5.0.0-beta.2", - "zone.js": "0.5.15" + "zone.js": "0.6.10" }, "devDependencies": { "concurrently": "^2.0.0",